cabal-buck2 0.5.0.0 → 0.6.0.0
raw patch · 2025 files changed
+299116/−276 lines, 2025 filesdep ~bytestringdep ~containersdep ~filepathbinary-addedPVP ok
version bump matches the API change (PVP)
Dependency ranges changed: bytestring, containers, filepath
API changes (from Hackage documentation)
This diff is very large; some files are shown as “too large to diff”. Download the raw patch for the complete diff.
Files
- README.md +347/−103
- buck2/BUCK +10/−0
- buck2/LICENSE +30/−0
- buck2/README.md +229/−0
- buck2/alex_happy.bzl +51/−0
- buck2/cabal.bzl +748/−0
- buck2/cfg_constructor_if_standalone.bzl +67/−0
- buck2/cmm.bzl +142/−0
- buck2/constraints/BUCK +126/−0
- buck2/cxx.bzl +54/−0
- buck2/haskell.bzl +249/−0
- buck2/headers.bzl +48/−0
- buck2/hsc2hs.bzl +71/−0
- buck2/llvm.bzl +44/−0
- buck2/platforms/BUCK +103/−0
- buck2/platforms/defs.bzl +97/−0
- buck2/prelude/.buckconfig +38/−0
- buck2/prelude/BUCK +69/−0
- buck2/prelude/LICENSE-APACHE +201/−0
- buck2/prelude/LICENSE-MIT +21/−0
- buck2/prelude/abi/BUCK +29/−0
- buck2/prelude/abi/constraints/BUCK +20/−0
- buck2/prelude/alias.bzl +28/−0
- buck2/prelude/android/aapt2_link.bzl +209/−0
- buck2/prelude/android/android.bzl +43/−0
- buck2/prelude/android/android_aar.bzl +203/−0
- buck2/prelude/android/android_apk.bzl +335/−0
- buck2/prelude/android/android_binary.bzl +315/−0
- buck2/prelude/android/android_binary_native_library_rules.bzl +2927/−0
- buck2/prelude/android/android_binary_resources_rules.bzl +696/−0
- buck2/prelude/android/android_build_config.bzl +128/−0
- buck2/prelude/android/android_bundle.bzl +190/−0
- buck2/prelude/android/android_cpu_transitioned_dep.bzl +30/−0
- buck2/prelude/android/android_instrumentation_apk.bzl +193/−0
- buck2/prelude/android/android_instrumentation_test.bzl +360/−0
- buck2/prelude/android/android_library.bzl +223/−0
- buck2/prelude/android/android_manifest.bzl +89/−0
- buck2/prelude/android/android_prebuilt_aar.bzl +172/−0
- buck2/prelude/android/android_providers.bzl +401/−0
- buck2/prelude/android/android_resource.bzl +199/−0
- buck2/prelude/android/android_toolchain.bzl +83/−0
- buck2/prelude/android/apk_genrule.bzl +251/−0
- buck2/prelude/android/build_only_native_code.bzl +15/−0
- buck2/prelude/android/bundletool_util.bzl +41/−0
- buck2/prelude/android/configuration.bzl +204/−0
- buck2/prelude/android/constraints/BUCK +56/−0
- buck2/prelude/android/cpu_filters.bzl +25/−0
- buck2/prelude/android/dex_rules.bzl +975/−0
- buck2/prelude/android/duplicate_class_check.bzl +134/−0
- buck2/prelude/android/exopackage.bzl +31/−0
- buck2/prelude/android/gen_aidl.bzl +80/−0
- buck2/prelude/android/keystore.bzl +19/−0
- buck2/prelude/android/min_sdk_version.bzl +16/−0
- buck2/prelude/android/native_build_commands.bzl +124/−0
- buck2/prelude/android/prebuilt_native_library.bzl +39/−0
- buck2/prelude/android/preprocess_java_classes.bzl +84/−0
- buck2/prelude/android/r_dot_java.bzl +206/−0
- buck2/prelude/android/readme.md +448/−0
- buck2/prelude/android/relinker_linker_outputs.bzl +115/−0
- buck2/prelude/android/robolectric_test.bzl +158/−0
- buck2/prelude/android/tools/BUCK +133/−0
- buck2/prelude/android/tools/com/facebook/buck_generated/AppWithoutResourcesStub.java +13/−0
- buck2/prelude/android/tools/combine_apk_with_relinked_libs.py +192/−0
- buck2/prelude/android/tools/combine_native_library_dirs.py +97/−0
- buck2/prelude/android/tools/consolidate_class_names.py +103/−0
- buck2/prelude/android/tools/create_jdk_system_image.py +302/−0
- buck2/prelude/android/tools/duplicate_class_checker.py +168/−0
- buck2/prelude/android/tools/filter_dex.py +264/−0
- buck2/prelude/android/tools/filter_extra_resources.py +63/−0
- buck2/prelude/android/tools/filter_prebuilt_native_library_dir.py +57/−0
- buck2/prelude/android/tools/jdk_system_image.bzl +47/−0
- buck2/prelude/android/tools/merge_sequence.py +815/−0
- buck2/prelude/android/tools/native_libs_as_assets_metadata.py +84/−0
- buck2/prelude/android/tools/sort_pre_dexed_files.py +457/−0
- buck2/prelude/android/tools/tests/BUCK +31/−0
- buck2/prelude/android/tools/tests/test_combine_apk_with_relinked_libs.py +284/−0
- buck2/prelude/android/tools/tests/test_filter_dex.py +114/−0
- buck2/prelude/android/tools/tests/test_sort_pre_dexed_files.py +725/−0
- buck2/prelude/android/tools/unpack_aar.py +195/−0
- buck2/prelude/android/user/android_emulators.bzl +29/−0
- buck2/prelude/android/util.bzl +149/−0
- buck2/prelude/android/voltron.bzl +343/−0
- buck2/prelude/aosp/aosp_providers.bzl +17/−0
- buck2/prelude/apple/apple_app_intents.bzl +16/−0
- buck2/prelude/apple/apple_asset_catalog.bzl +153/−0
- buck2/prelude/apple/apple_asset_catalog_compilation_options.bzl +30/−0
- buck2/prelude/apple/apple_asset_catalog_types.bzl +31/−0
- buck2/prelude/apple/apple_binary.bzl +423/−0
- buck2/prelude/apple/apple_bundle.bzl +717/−0
- buck2/prelude/apple/apple_bundle_config.bzl +56/−0
- buck2/prelude/apple/apple_bundle_destination.bzl +159/−0
- buck2/prelude/apple/apple_bundle_part.bzl +666/−0
- buck2/prelude/apple/apple_bundle_resources.bzl +635/−0
- buck2/prelude/apple/apple_bundle_types.bzl +144/−0
- buck2/prelude/apple/apple_bundle_utility.bzl +115/−0
- buck2/prelude/apple/apple_code_signing_types.bzl +34/−0
- buck2/prelude/apple/apple_common.bzl +516/−0
- buck2/prelude/apple/apple_core_data.bzl +122/−0
- buck2/prelude/apple/apple_core_data_types.bzl +12/−0
- buck2/prelude/apple/apple_dsym.bzl +92/−0
- buck2/prelude/apple/apple_entitlements.bzl +71/−0
- buck2/prelude/apple/apple_error_handler.bzl +229/−0
- buck2/prelude/apple/apple_finalize_codesign.bzl +68/−0
- buck2/prelude/apple/apple_framework_versions.bzl +1195/−0
- buck2/prelude/apple/apple_frameworks.bzl +239/−0
- buck2/prelude/apple/apple_info_plist.bzl +223/−0
- buck2/prelude/apple/apple_info_plist_substitutions_parsing.bzl +68/−0
- buck2/prelude/apple/apple_library.bzl +771/−0
- buck2/prelude/apple/apple_library_types.bzl +22/−0
- buck2/prelude/apple/apple_macro_layer.bzl +154/−0
- buck2/prelude/apple/apple_metal_library.bzl +194/−0
- buck2/prelude/apple/apple_modular_utility.bzl +15/−0
- buck2/prelude/apple/apple_native.bzl +100/−0
- buck2/prelude/apple/apple_package.bzl +144/−0
- buck2/prelude/apple/apple_package_config.bzl +19/−0
- buck2/prelude/apple/apple_package_types.bzl +22/−0
- buck2/prelude/apple/apple_platforms.bzl +9/−0
- buck2/prelude/apple/apple_provisioning_profile_sources.bzl +53/−0
- buck2/prelude/apple/apple_resource.bzl +77/−0
- buck2/prelude/apple/apple_resource_bundle.bzl +97/−0
- buck2/prelude/apple/apple_resource_dedupe_alias.bzl +10/−0
- buck2/prelude/apple/apple_resource_types.bzl +70/−0
- buck2/prelude/apple/apple_resource_utility.bzl +16/−0
- buck2/prelude/apple/apple_rpaths.bzl +121/−0
- buck2/prelude/apple/apple_rules_decls.bzl +1909/−0
- buck2/prelude/apple/apple_rules_impl.bzl +15/−0
- buck2/prelude/apple/apple_rules_impl_utility.bzl +306/−0
- buck2/prelude/apple/apple_sdk.bzl +16/−0
- buck2/prelude/apple/apple_sdk_metadata.bzl +105/−0
- buck2/prelude/apple/apple_simulators.bzl +27/−0
- buck2/prelude/apple/apple_static_archive.bzl +110/−0
- buck2/prelude/apple/apple_stripping.bzl +24/−0
- buck2/prelude/apple/apple_swift_stdlib.bzl +15/−0
- buck2/prelude/apple/apple_target_sdk_version.bzl +96/−0
- buck2/prelude/apple/apple_test.bzl +421/−0
- buck2/prelude/apple/apple_test_device_types.bzl +46/−0
- buck2/prelude/apple/apple_test_frameworks_utility.bzl +60/−0
- buck2/prelude/apple/apple_test_host_app_transition.bzl +39/−0
- buck2/prelude/apple/apple_toolchain.bzl +62/−0
- buck2/prelude/apple/apple_toolchain_types.bzl +79/−0
- buck2/prelude/apple/apple_tools.bzl +37/−0
- buck2/prelude/apple/apple_universal_binaries.bzl +108/−0
- buck2/prelude/apple/apple_universal_executable.bzl +104/−0
- buck2/prelude/apple/apple_utility.bzl +82/−0
- buck2/prelude/apple/apple_xcuitest.bzl +104/−0
- buck2/prelude/apple/arch.bzl +16/−0
- buck2/prelude/apple/cxx_universal_executable.bzl +32/−0
- buck2/prelude/apple/debug.bzl +113/−0
- buck2/prelude/apple/mockingbird/mockingbird_mock.bzl +191/−0
- buck2/prelude/apple/mockingbird/mockingbird_types.bzl +50/−0
- buck2/prelude/apple/modularization_dependency_graph.bzl +55/−0
- buck2/prelude/apple/modulemap.bzl +111/−0
- buck2/prelude/apple/prebuilt_apple_framework.bzl +340/−0
- buck2/prelude/apple/prebuilt_apple_xcframework_macro_impl.bzl +276/−0
- buck2/prelude/apple/resource_groups.bzl +226/−0
- buck2/prelude/apple/scene_kit_assets.bzl +99/−0
- buck2/prelude/apple/scene_kit_assets_types.bzl +11/−0
- buck2/prelude/apple/swift/apple_sdk_clang_module.bzl +49/−0
- buck2/prelude/apple/swift/apple_sdk_modules_utility.bzl +93/−0
- buck2/prelude/apple/swift/apple_sdk_swift_module.bzl +66/−0
- buck2/prelude/apple/swift/swift_compilation.bzl +1727/−0
- buck2/prelude/apple/swift/swift_debug_info_utils.bzl +60/−0
- buck2/prelude/apple/swift/swift_helpers.bzl +298/−0
- buck2/prelude/apple/swift/swift_incremental_support.bzl +380/−0
- buck2/prelude/apple/swift/swift_module_map.bzl +52/−0
- buck2/prelude/apple/swift/swift_output_file_map.bzl +95/−0
- buck2/prelude/apple/swift/swift_pcm_compilation.bzl +290/−0
- buck2/prelude/apple/swift/swift_pcm_compilation_types.bzl +38/−0
- buck2/prelude/apple/swift/swift_sdk_flags.bzl +17/−0
- buck2/prelude/apple/swift/swift_sdk_pcm_compilation.bzl +256/−0
- buck2/prelude/apple/swift/swift_swiftinterface_compilation.bzl +190/−0
- buck2/prelude/apple/swift/swift_toolchain.bzl +143/−0
- buck2/prelude/apple/swift/swift_toolchain_macro_layer.bzl +22/−0
- buck2/prelude/apple/swift/swift_toolchain_types.bzl +198/−0
- buck2/prelude/apple/swift/swift_types.bzl +75/−0
- buck2/prelude/apple/tools/BUCK +150/−0
- buck2/prelude/apple/tools/bundling/BUCK +83/−0
- buck2/prelude/apple/tools/bundling/action_metadata.py +78/−0
- buck2/prelude/apple/tools/bundling/action_metadata_test.py +48/−0
- buck2/prelude/apple/tools/bundling/assemble_bundle.py +277/−0
- buck2/prelude/apple/tools/bundling/assemble_bundle_types.py +123/−0
- buck2/prelude/apple/tools/bundling/incremental_state.py +178/−0
- buck2/prelude/apple/tools/bundling/incremental_state_test.py +167/−0
- buck2/prelude/apple/tools/bundling/incremental_utils.py +251/−0
- buck2/prelude/apple/tools/bundling/incremental_utils_test.py +672/−0
- buck2/prelude/apple/tools/bundling/logging_utils.py +62/−0
- buck2/prelude/apple/tools/bundling/main.py +748/−0
- buck2/prelude/apple/tools/bundling/provisioning_manifest_main.py +85/−0
- buck2/prelude/apple/tools/bundling/resolve_signing_context_main.py +75/−0
- buck2/prelude/apple/tools/bundling/signing_context.py +261/−0
- buck2/prelude/apple/tools/bundling/signing_context_data.py +157/−0
- buck2/prelude/apple/tools/bundling/signing_context_data_test.py +219/−0
- buck2/prelude/apple/tools/bundling/signing_info.py +77/−0
- buck2/prelude/apple/tools/bundling/signing_info_main.py +44/−0
- buck2/prelude/apple/tools/bundling/signing_info_test.py +130/−0
- buck2/prelude/apple/tools/bundling/swift_support.py +85/−0
- buck2/prelude/apple/tools/bundling/test_resources/newer_version_action_metadata.json +6/−0
- buck2/prelude/apple/tools/bundling/test_resources/newer_version_incremental_state.json +6/−0
- buck2/prelude/apple/tools/bundling/test_resources/the.broken_json +2/−0
- buck2/prelude/apple/tools/bundling/test_resources/valid_action_metadata.json +13/−0
- buck2/prelude/apple/tools/bundling/test_resources/valid_incremental_state.json +48/−0
- buck2/prelude/apple/tools/code_signing/BUCK +89/−0
- buck2/prelude/apple/tools/code_signing/app_id.py +74/−0
- buck2/prelude/apple/tools/code_signing/app_id_test.py +64/−0
- buck2/prelude/apple/tools/code_signing/apple_platform.py +50/−0
- buck2/prelude/apple/tools/code_signing/codesign_bundle.py +914/−0
- buck2/prelude/apple/tools/code_signing/codesign_command_factory.py +172/−0
- buck2/prelude/apple/tools/code_signing/codesign_diagnostics_text.py +26/−0
- buck2/prelude/apple/tools/code_signing/dummy_binary_for_signing.c +13/−0
- buck2/prelude/apple/tools/code_signing/fast_adhoc.py +202/−0
- buck2/prelude/apple/tools/code_signing/identity.py +69/−0
- buck2/prelude/apple/tools/code_signing/identity_test.py +47/−0
- buck2/prelude/apple/tools/code_signing/info_plist_metadata.py +65/−0
- buck2/prelude/apple/tools/code_signing/info_plist_metadata_test.py +68/−0
- buck2/prelude/apple/tools/code_signing/list_codesign_identities.py +85/−0
- buck2/prelude/apple/tools/code_signing/main.py +215/−0
- buck2/prelude/apple/tools/code_signing/prepare_code_signing_entitlements.py +104/−0
- buck2/prelude/apple/tools/code_signing/prepare_code_signing_entitlements_test.py +437/−0
- buck2/prelude/apple/tools/code_signing/prepare_info_plist.py +51/−0
- buck2/prelude/apple/tools/code_signing/prepare_info_plist_test.py +75/−0
- buck2/prelude/apple/tools/code_signing/provisioning_profile_diagnostics.py +259/−0
- buck2/prelude/apple/tools/code_signing/provisioning_profile_diagnostics_test.py +110/−0
- buck2/prelude/apple/tools/code_signing/provisioning_profile_metadata.py +267/−0
- buck2/prelude/apple/tools/code_signing/provisioning_profile_metadata_test.py +69/−0
- buck2/prelude/apple/tools/code_signing/provisioning_profile_selection.py +389/−0
- buck2/prelude/apple/tools/code_signing/provisioning_profile_selection_test.py +659/−0
- buck2/prelude/apple/tools/code_signing/read_provisioning_profile_command_factory.py +39/−0
- buck2/prelude/apple/tools/code_signing/serialization.py +67/−0
- buck2/prelude/apple/tools/code_signing/signing_context_types.py +143/−0
- buck2/prelude/apple/tools/code_signing/signing_context_types_test.py +316/−0
- buck2/prelude/apple/tools/code_signing/test_resources/qualified_sample.mobileprovision +78/−0
- buck2/prelude/apple/tools/code_signing/test_resources/sample.mobileprovision +78/−0
- buck2/prelude/apple/tools/code_signing/test_resources/test1.plist +10/−0
- buck2/prelude/apple/tools/code_signing/test_resources/test2.plist +8/−0
- buck2/prelude/apple/tools/code_signing/test_resources/test3.plist +10/−0
- buck2/prelude/apple/tools/codesign_manifest_tree_postprocessor/BUCK +11/−0
- buck2/prelude/apple/tools/codesign_manifest_tree_postprocessor/main.py +97/−0
- buck2/prelude/apple/tools/dedupe_swift_module_map.py +65/−0
- buck2/prelude/apple/tools/defs.bzl +51/−0
- buck2/prelude/apple/tools/distributed_thin_lto/BUCK +36/−0
- buck2/prelude/apple/tools/distributed_thin_lto/dist_lto_planner.cpp +468/−0
- buck2/prelude/apple/tools/dry_codesign_tool.py +82/−0
- buck2/prelude/apple/tools/empty.c +0/−0
- buck2/prelude/apple/tools/framework_sanitizer.py +72/−0
- buck2/prelude/apple/tools/index/BUCK +27/−0
- buck2/prelude/apple/tools/index/merge_index_store.py +102/−0
- buck2/prelude/apple/tools/index/merge_index_store_tests.py +69/−0
- buck2/prelude/apple/tools/info_plist_processor/BUCK +40/−0
- buck2/prelude/apple/tools/info_plist_processor/main.py +194/−0
- buck2/prelude/apple/tools/info_plist_processor/preprocess.py +99/−0
- buck2/prelude/apple/tools/info_plist_processor/preprocess_test.py +91/−0
- buck2/prelude/apple/tools/info_plist_processor/process.py +269/−0
- buck2/prelude/apple/tools/info_plist_processor/process_test.py +464/−0
- buck2/prelude/apple/tools/ipa_package_maker.py +113/−0
- buck2/prelude/apple/tools/make_modulemap.py +209/−0
- buck2/prelude/apple/tools/make_swift_comp_db.py +60/−0
- buck2/prelude/apple/tools/make_swift_interface.py +290/−0
- buck2/prelude/apple/tools/make_vfsoverlay.py +96/−0
- buck2/prelude/apple/tools/plistlib_utils.py +32/−0
- buck2/prelude/apple/tools/re_compatibility_utils/BUCK +24/−0
- buck2/prelude/apple/tools/re_compatibility_utils/writable.py +54/−0
- buck2/prelude/apple/tools/resource_broker/BUCK +38/−0
- buck2/prelude/apple/tools/resource_broker/debug.py +31/−0
- buck2/prelude/apple/tools/resource_broker/ios.py +319/−0
- buck2/prelude/apple/tools/resource_broker/main.py +84/−0
- buck2/prelude/apple/tools/resource_broker/simctl_runtime.py +68/−0
- buck2/prelude/apple/tools/resource_broker/simulator.py +96/−0
- buck2/prelude/apple/tools/resource_broker/timeouts.py +15/−0
- buck2/prelude/apple/tools/resource_broker/utils.py +46/−0
- buck2/prelude/apple/tools/selective_debugging/BUCK +44/−0
- buck2/prelude/apple/tools/selective_debugging/macho.py +84/−0
- buck2/prelude/apple/tools/selective_debugging/macho_parser.py +136/−0
- buck2/prelude/apple/tools/selective_debugging/main.py +65/−0
- buck2/prelude/apple/tools/selective_debugging/scrubber.py +250/−0
- buck2/prelude/apple/tools/selective_debugging/scrubber_test.py +330/−0
- buck2/prelude/apple/tools/selective_debugging/spec.py +115/−0
- buck2/prelude/apple/tools/selective_debugging/spec_test.py +104/−0
- buck2/prelude/apple/tools/selective_debugging/test_resources/HelloWorld binary
- buck2/prelude/apple/tools/selective_debugging/test_resources/focused_spec.json +8/−0
- buck2/prelude/apple/tools/selective_debugging/test_resources/focused_spec_regex_all.json +6/−0
- buck2/prelude/apple/tools/selective_debugging/test_resources/focused_spec_regex_none.json +6/−0
- buck2/prelude/apple/tools/selective_debugging/test_resources/focused_targets.json +5/−0
- buck2/prelude/apple/tools/selective_debugging/test_resources/focused_targets_empty.json +4/−0
- buck2/prelude/apple/tools/selective_debugging/utils.py +13/−0
- buck2/prelude/apple/tools/signing_context_tree_postprocessor/BUCK +11/−0
- buck2/prelude/apple/tools/signing_context_tree_postprocessor/main.py +96/−0
- buck2/prelude/apple/tools/split_arch_combine_dsym_bundles_tool.py +63/−0
- buck2/prelude/apple/tools/spm_packager.py +96/−0
- buck2/prelude/apple/tools/static_archive_linker.py +67/−0
- buck2/prelude/apple/tools/swift_exec.py +459/−0
- buck2/prelude/apple/tools/xcframework_maker.py +162/−0
- buck2/prelude/apple/user/apple_ipa_package.bzl +286/−0
- buck2/prelude/apple/user/apple_macos_bundle.bzl +14/−0
- buck2/prelude/apple/user/apple_resource_bundle.bzl +48/−0
- buck2/prelude/apple/user/apple_resource_transition.bzl +41/−0
- buck2/prelude/apple/user/apple_selected_debug_path_file.bzl +11/−0
- buck2/prelude/apple/user/apple_selective_debugging.bzl +350/−0
- buck2/prelude/apple/user/apple_spm_package.bzl +38/−0
- buck2/prelude/apple/user/apple_watchos_bundle.bzl +14/−0
- buck2/prelude/apple/user/apple_xcframework.bzl +201/−0
- buck2/prelude/apple/user/cpu_split_transition.bzl +123/−0
- buck2/prelude/apple/user/enable_testing_transition.bzl +39/−0
- buck2/prelude/apple/user/macos_transition.bzl +76/−0
- buck2/prelude/apple/user/resource_group_map.bzl +91/−0
- buck2/prelude/apple/user/target_sdk_version_transition.bzl +67/−0
- buck2/prelude/apple/user/watch_transition.bzl +84/−0
- buck2/prelude/apple/validation/required_reasons.bzl +103/−0
- buck2/prelude/apple/validation/required_reasons_tools.bzl +31/−0
- buck2/prelude/apple/validation/swiftmodule_change_analysis.bzl +125/−0
- buck2/prelude/apple/versions.bzl +47/−0
- buck2/prelude/apple/xcassets_asset_symbols.bzl +25/−0
- buck2/prelude/apple/xcode.bzl +69/−0
- buck2/prelude/apple/xctest_swift_support.bzl +37/−0
- buck2/prelude/artifact_tset.bzl +114/−0
- buck2/prelude/artifacts.bzl +176/−0
- buck2/prelude/asserts.bzl +34/−0
- buck2/prelude/attributes.bzl +9/−0
- buck2/prelude/attrs_validators.bzl +60/−0
- buck2/prelude/build_mode/BUCK +12/−0
- buck2/prelude/bxl/ensure.bxl +32/−0
- buck2/prelude/bxl/lazy.bxl +206/−0
- buck2/prelude/cache_mode.bzl +11/−0
- buck2/prelude/capabilities/capabilities_registration.bzl +82/−0
- buck2/prelude/cfg/exec_platform/marker.bzl +24/−0
- buck2/prelude/cfg/exec_platform/marker/BUCK +38/−0
- buck2/prelude/cfg/modifier/alias.bzl +29/−0
- buck2/prelude/cfg/modifier/asserts.bzl +32/−0
- buck2/prelude/cfg/modifier/buckconfig_backed_modifiers.bzl +130/−0
- buck2/prelude/cfg/modifier/cfg_constructor.bzl +196/−0
- buck2/prelude/cfg/modifier/common.bzl +310/−0
- buck2/prelude/cfg/modifier/conditional_modifier.bzl +163/−0
- buck2/prelude/cfg/modifier/constraint_modifier_info.bzl +84/−0
- buck2/prelude/cfg/modifier/name.bzl +70/−0
- buck2/prelude/cfg/modifier/set_cfg_modifiers.bzl +66/−0
- buck2/prelude/cfg/modifier/types.bzl +81/−0
- buck2/prelude/command_alias.bzl +262/−0
- buck2/prelude/configurations/constraint_alias.bzl +114/−0
- buck2/prelude/configurations/rules.bzl +211/−0
- buck2/prelude/configurations/util.bzl +43/−0
- buck2/prelude/content_based_dist.bzl +73/−0
- buck2/prelude/cpu/BUCK +53/−0
- buck2/prelude/cpu/constraints/BUCK +30/−0
- buck2/prelude/csharp/csharp.bzl +85/−0
- buck2/prelude/csharp/csharp_providers.bzl +63/−0
- buck2/prelude/csharp/toolchain.bzl +14/−0
- buck2/prelude/cxx/anon_link.bzl +282/−0
- buck2/prelude/cxx/archive.bzl +155/−0
- buck2/prelude/cxx/argsfiles.bzl +50/−0
- buck2/prelude/cxx/attr_selection.bzl +66/−0
- buck2/prelude/cxx/bitcode.bzl +92/−0
- buck2/prelude/cxx/clang_profile_list.bzl +63/−0
- buck2/prelude/cxx/comp_db.bzl +133/−0
- buck2/prelude/cxx/compilation_database_labels.bzl +73/−0
- buck2/prelude/cxx/compile.bzl +2754/−0
- buck2/prelude/cxx/compile_types.bzl +202/−0
- buck2/prelude/cxx/compiler.bzl +87/−0
- buck2/prelude/cxx/cuda.bzl +603/−0
- buck2/prelude/cxx/cxx.bzl +1168/−0
- buck2/prelude/cxx/cxx_apple_linker_flags.bzl +96/−0
- buck2/prelude/cxx/cxx_bolt.bzl +104/−0
- buck2/prelude/cxx/cxx_context.bzl +44/−0
- buck2/prelude/cxx/cxx_error_handler.bzl +201/−0
- buck2/prelude/cxx/cxx_executable.bzl +1262/−0
- buck2/prelude/cxx/cxx_flags.bzl +113/−0
- buck2/prelude/cxx/cxx_instrumentation.bzl +42/−0
- buck2/prelude/cxx/cxx_library.bzl +2566/−0
- buck2/prelude/cxx/cxx_library_utility.bzl +207/−0
- buck2/prelude/cxx/cxx_link_utility.bzl +363/−0
- buck2/prelude/cxx/cxx_sources.bzl +46/−0
- buck2/prelude/cxx/cxx_toolchain.bzl +482/−0
- buck2/prelude/cxx/cxx_toolchain_macro_layer.bzl +33/−0
- buck2/prelude/cxx/cxx_toolchain_types.bzl +531/−0
- buck2/prelude/cxx/cxx_transitive_diagnostics.bzl +37/−0
- buck2/prelude/cxx/cxx_types.bzl +315/−0
- buck2/prelude/cxx/cxx_utility.bzl +41/−0
- buck2/prelude/cxx/debug.bzl +24/−0
- buck2/prelude/cxx/diagnostics.bzl +47/−0
- buck2/prelude/cxx/dist_lto/README.md +323/−0
- buck2/prelude/cxx/dist_lto/darwin/common_types.bzl +53/−0
- buck2/prelude/cxx/dist_lto/darwin/dist_lto.bzl +926/−0
- buck2/prelude/cxx/dist_lto/darwin/thin_link.bzl +108/−0
- buck2/prelude/cxx/dist_lto/darwin/thin_link_record_defs.bzl +24/−0
- buck2/prelude/cxx/dist_lto/dist_lto.bzl +909/−0
- buck2/prelude/cxx/dist_lto/tools.bzl +55/−0
- buck2/prelude/cxx/dist_lto/tools/BUCK +75/−0
- buck2/prelude/cxx/dist_lto/tools/__init__.py +0/−0
- buck2/prelude/cxx/dist_lto/tools/dist_lto_archive_mapper.py +54/−0
- buck2/prelude/cxx/dist_lto/tools/dist_lto_compiler_stats_merger.py +47/−0
- buck2/prelude/cxx/dist_lto/tools/dist_lto_copy.py +26/−0
- buck2/prelude/cxx/dist_lto/tools/dist_lto_opt_darwin.py +124/−0
- buck2/prelude/cxx/dist_lto/tools/dist_lto_opt_gnu.py +323/−0
- buck2/prelude/cxx/dist_lto/tools/dist_lto_planner_darwin.py +331/−0
- buck2/prelude/cxx/dist_lto/tools/dist_lto_planner_gnu.py +600/−0
- buck2/prelude/cxx/dist_lto/tools/dist_lto_prepare_darwin.py +158/−0
- buck2/prelude/cxx/dist_lto/tools/dist_lto_prepare_gnu.py +172/−0
- buck2/prelude/cxx/dist_lto/tools/tests/test_dist_lto_opt.py +325/−0
- buck2/prelude/cxx/dwp.bzl +104/−0
- buck2/prelude/cxx/gcno.bzl +14/−0
- buck2/prelude/cxx/groups.bzl +497/−0
- buck2/prelude/cxx/groups_types.bzl +121/−0
- buck2/prelude/cxx/headers.bzl too large to diff
- buck2/prelude/cxx/hip_debug_extract.bzl too large to diff
- buck2/prelude/cxx/index_store.bzl too large to diff
- buck2/prelude/cxx/link.bzl too large to diff
- buck2/prelude/cxx/link_groups.bzl too large to diff
- buck2/prelude/cxx/link_groups_types.bzl too large to diff
- buck2/prelude/cxx/link_types.bzl too large to diff
- buck2/prelude/cxx/linker.bzl too large to diff
- buck2/prelude/cxx/omnibus.bzl too large to diff
- buck2/prelude/cxx/prebuilt_cxx_library_group.bzl too large to diff
- buck2/prelude/cxx/preprocessor.bzl too large to diff
- buck2/prelude/cxx/shared_library_interface.bzl too large to diff
- buck2/prelude/cxx/symbols.bzl too large to diff
- buck2/prelude/cxx/target_sdk_version.bzl too large to diff
- buck2/prelude/cxx/tools/BUCK too large to diff
- buck2/prelude/cxx/tools/check_nonempty_output.py too large to diff
- buck2/prelude/cxx/tools/clang_tidy_wrapper.py too large to diff
- buck2/prelude/cxx/tools/compilation_database.bxl too large to diff
- buck2/prelude/cxx/tools/concatenate_diagnostics.py too large to diff
- buck2/prelude/cxx/tools/defs.bzl too large to diff
- buck2/prelude/cxx/tools/dep_file_processor.py too large to diff
- buck2/prelude/cxx/tools/dep_file_utils.py too large to diff
- buck2/prelude/cxx/tools/filter_argsfile.py too large to diff
- buck2/prelude/cxx/tools/hmap_wrapper.py too large to diff
- buck2/prelude/cxx/tools/linker_wrapper.py too large to diff
- buck2/prelude/cxx/tools/make_comp_db.py too large to diff
- buck2/prelude/cxx/tools/makefile_to_dep_file.py too large to diff
- buck2/prelude/cxx/tools/remap_cwd.py too large to diff
- buck2/prelude/cxx/tools/serialized_diagnostics_to_json_wrapper.sh too large to diff
- buck2/prelude/cxx/tools/show_headers_to_dep_file.py too large to diff
- buck2/prelude/cxx/tools/show_includes_to_dep_file.py too large to diff
- buck2/prelude/cxx/tools/simple_ar.py too large to diff
- buck2/prelude/cxx/tools/stderr_to_file.py too large to diff
- buck2/prelude/cxx/tools/stub_header_unit.py too large to diff
- buck2/prelude/cxx/transformation_spec.bzl too large to diff
- buck2/prelude/cxx/user/cxx_toolchain_override.bzl too large to diff
- buck2/prelude/cxx/user/link_group_map.bzl too large to diff
- buck2/prelude/cxx/windows_resource.bzl too large to diff
- buck2/prelude/cxx/xcode.bzl too large to diff
- buck2/prelude/debugging/common.bzl too large to diff
- buck2/prelude/debugging/configure_env.bzl too large to diff
- buck2/prelude/debugging/ensure_dwp.bzl too large to diff
- buck2/prelude/debugging/fdb.bxl too large to diff
- buck2/prelude/debugging/inspect_dbg_exec.bzl too large to diff
- buck2/prelude/debugging/inspect_default.bzl too large to diff
- buck2/prelude/debugging/inspect_java.bzl too large to diff
- buck2/prelude/debugging/java/get_jdb_classmap.bxl too large to diff
- buck2/prelude/debugging/labels.bzl too large to diff
- buck2/prelude/debugging/types.bzl too large to diff
- buck2/prelude/decls/android_common.bzl too large to diff
- buck2/prelude/decls/android_rules.bzl too large to diff
- buck2/prelude/decls/common.bzl too large to diff
- buck2/prelude/decls/core_rules.bzl too large to diff
- buck2/prelude/decls/cxx_common.bzl too large to diff
- buck2/prelude/decls/cxx_rules.bzl too large to diff
- buck2/prelude/decls/cython_rules.bzl too large to diff
- buck2/prelude/decls/dotnet_rules.bzl too large to diff
- buck2/prelude/decls/erlang_rules.bzl too large to diff
- buck2/prelude/decls/genrule_common.bzl too large to diff
- buck2/prelude/decls/git_rules.bzl too large to diff
- buck2/prelude/decls/go_common.bzl too large to diff
- buck2/prelude/decls/go_rules.bzl too large to diff
- buck2/prelude/decls/haskell_common.bzl too large to diff
- buck2/prelude/decls/haskell_rules.bzl too large to diff
- buck2/prelude/decls/java_rules.bzl too large to diff
- buck2/prelude/decls/js_rules.bzl too large to diff
- buck2/prelude/decls/jvm_common.bzl too large to diff
- buck2/prelude/decls/kotlin_rules.bzl too large to diff
- buck2/prelude/decls/lua_common.bzl too large to diff
- buck2/prelude/decls/lua_rules.bzl too large to diff
- buck2/prelude/decls/native_common.bzl too large to diff
- buck2/prelude/decls/ocaml_common.bzl too large to diff
- buck2/prelude/decls/ocaml_rules.bzl too large to diff
- buck2/prelude/decls/python_common.bzl too large to diff
- buck2/prelude/decls/python_rules.bzl too large to diff
- buck2/prelude/decls/re_test_common.bzl too large to diff
- buck2/prelude/decls/remote_common.bzl too large to diff
- buck2/prelude/decls/rust_common.bzl too large to diff
- buck2/prelude/decls/rust_rules.bzl too large to diff
- buck2/prelude/decls/shell_rules.bzl too large to diff
- buck2/prelude/decls/test_common.bzl too large to diff
- buck2/prelude/decls/third_party_common.bzl too large to diff
- buck2/prelude/decls/toolchains_common.bzl too large to diff
- buck2/prelude/decls/uncategorized_rules.bzl too large to diff
- buck2/prelude/dist/dist_info.bzl too large to diff
- buck2/prelude/docs/rules.bzl too large to diff
- buck2/prelude/erlang/applications/BUCK too large to diff
- buck2/prelude/erlang/common_test/common/BUCK too large to diff
- buck2/prelude/erlang/common_test/common/include/artifact_annotations.hrl too large to diff
- buck2/prelude/erlang/common_test/common/include/buck_ct_records.hrl too large to diff
- buck2/prelude/erlang/common_test/common/include/tpx_records.hrl too large to diff
- buck2/prelude/erlang/common_test/common/src/artifact_annotations.erl too large to diff
- buck2/prelude/erlang/common_test/common/src/bounded_buffer.erl too large to diff
- buck2/prelude/erlang/common_test/common/src/buck_ct_parser.erl too large to diff
- buck2/prelude/erlang/common_test/common/src/buck_ct_provider.erl too large to diff
- buck2/prelude/erlang/common_test/common/src/common_util.erl too large to diff
- buck2/prelude/erlang/common_test/common/src/ct_error_printer.erl too large to diff
- buck2/prelude/erlang/common_test/common/src/ct_stdout.erl too large to diff
- buck2/prelude/erlang/common_test/common/src/list_test.erl too large to diff
- buck2/prelude/erlang/common_test/common/src/test_artifact_directory.erl too large to diff
- buck2/prelude/erlang/common_test/common/src/test_logger.erl too large to diff
- buck2/prelude/erlang/common_test/common/test/ct_stdout_SUITE.erl too large to diff
- buck2/prelude/erlang/common_test/cth_hooks/BUCK too large to diff
- buck2/prelude/erlang/common_test/cth_hooks/src/cth_skip_cases.erl too large to diff
- buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx.erl too large to diff
- buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx_role.erl too large to diff
- buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx_server.erl too large to diff
- buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx_test_tree.erl too large to diff
- buck2/prelude/erlang/common_test/cth_hooks/src/method_ids.hrl too large to diff
- buck2/prelude/erlang/common_test/test_binary/BUCK too large to diff
- buck2/prelude/erlang/common_test/test_binary/src/json_interfacer.erl too large to diff
- buck2/prelude/erlang/common_test/test_binary/src/listing_interfacer.erl too large to diff
- buck2/prelude/erlang/common_test/test_binary/src/test_binary.erl too large to diff
- buck2/prelude/erlang/common_test/test_binary/src/test_info.erl too large to diff
- buck2/prelude/erlang/common_test/test_binary/src/test_runner.erl too large to diff
- buck2/prelude/erlang/common_test/test_cli_lib/BUCK too large to diff
- buck2/prelude/erlang/common_test/test_cli_lib/src/test.erl too large to diff
- buck2/prelude/erlang/common_test/test_cli_lib/src/test_cli_lib.erl too large to diff
- buck2/prelude/erlang/common_test/test_cli_lib/test/test_cli_e2e_SUITE.erl too large to diff
- buck2/prelude/erlang/common_test/test_cli_lib/test/test_cli_e2e_SUITE_data/test_list_SUITE.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/BUCK too large to diff
- buck2/prelude/erlang/common_test/test_exec/src/ct_daemon.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_capture.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_core.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_hooks.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_logger.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_node.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_printer.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_runner.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/src/ct_executor.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/src/ct_executor_watchdog.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/src/ct_runner.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/src/epmd_manager.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/src/test_exec.app.src too large to diff
- buck2/prelude/erlang/common_test/test_exec/src/test_exec.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/src/test_exec_sup.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/test/ct_daemon_capture_SUITE.erl too large to diff
- buck2/prelude/erlang/common_test/test_exec/test/ct_executor_SUITE.erl too large to diff
- buck2/prelude/erlang/elp.bxl too large to diff
- buck2/prelude/erlang/erlang.bzl too large to diff
- buck2/prelude/erlang/erlang_application.bzl too large to diff
- buck2/prelude/erlang/erlang_application_includes.bzl too large to diff
- buck2/prelude/erlang/erlang_build.bzl too large to diff
- buck2/prelude/erlang/erlang_dependencies.bzl too large to diff
- buck2/prelude/erlang/erlang_error_handler.bzl too large to diff
- buck2/prelude/erlang/erlang_erts.bzl too large to diff
- buck2/prelude/erlang/erlang_escript.bzl too large to diff
- buck2/prelude/erlang/erlang_headers.bzl too large to diff
- buck2/prelude/erlang/erlang_info.bzl too large to diff
- buck2/prelude/erlang/erlang_ls.config too large to diff
- buck2/prelude/erlang/erlang_otp_application.bzl too large to diff
- buck2/prelude/erlang/erlang_paths.bzl too large to diff
- buck2/prelude/erlang/erlang_release.bzl too large to diff
- buck2/prelude/erlang/erlang_shell.bzl too large to diff
- buck2/prelude/erlang/erlang_tests.bzl too large to diff
- buck2/prelude/erlang/erlang_toolchain.bzl too large to diff
- buck2/prelude/erlang/erlang_utils.bzl too large to diff
- buck2/prelude/erlang/erts/BUCK too large to diff
- buck2/prelude/erlang/erts/extract_from_otp.erl too large to diff
- buck2/prelude/erlang/shell/BUCK too large to diff
- buck2/prelude/erlang/shell/shell.bxl too large to diff
- buck2/prelude/erlang/shell/src/shell_buck2_module_search.erl too large to diff
- buck2/prelude/erlang/shell/src/shell_buck2_utils.erl too large to diff
- buck2/prelude/erlang/shell/src/user_default.erl too large to diff
- buck2/prelude/erlang/toolchain/BUCK too large to diff
- buck2/prelude/erlang/toolchain/app_src_builder.erl too large to diff
- buck2/prelude/erlang/toolchain/appup_src_builder.erl too large to diff
- buck2/prelude/erlang/toolchain/boot_script_builder.erl too large to diff
- buck2/prelude/erlang/toolchain/dependency_analyzer.erl too large to diff
- buck2/prelude/erlang/toolchain/dependency_finalizer.erl too large to diff
- buck2/prelude/erlang/toolchain/dependency_merger.erl too large to diff
- buck2/prelude/erlang/toolchain/dependency_utils.erl too large to diff
- buck2/prelude/erlang/toolchain/escript_builder.erl too large to diff
- buck2/prelude/erlang/toolchain/escript_trampoline.sh too large to diff
- buck2/prelude/erlang/toolchain/release_variables_builder.erl too large to diff
- buck2/prelude/erlang/toolchain/transform_project_root.erl too large to diff
- buck2/prelude/error_handler/error_enricher.bzl too large to diff
- buck2/prelude/error_handler/error_enricher_types.bzl too large to diff
- buck2/prelude/export_exe.bzl too large to diff
- buck2/prelude/export_file.bzl too large to diff
- buck2/prelude/filegroup.bzl too large to diff
- buck2/prelude/genrule.bzl too large to diff
- buck2/prelude/genrule_local_labels.bzl too large to diff
- buck2/prelude/genrule_prefer_local_labels.bzl too large to diff
- buck2/prelude/genrule_toolchain.bzl too large to diff
- buck2/prelude/git/git_fetch.bzl too large to diff
- buck2/prelude/git/tools/BUCK too large to diff
- buck2/prelude/git/tools/git_fetch.py too large to diff
- buck2/prelude/go/cgo_builder.bzl too large to diff
- buck2/prelude/go/compile.bzl too large to diff
- buck2/prelude/go/constraints/BUCK too large to diff
- buck2/prelude/go/coverage.bzl too large to diff
- buck2/prelude/go/go_binary.bzl too large to diff
- buck2/prelude/go/go_error_handler.bzl too large to diff
- buck2/prelude/go/go_exported_library.bzl too large to diff
- buck2/prelude/go/go_library.bzl too large to diff
- buck2/prelude/go/go_list.bzl too large to diff
- buck2/prelude/go/go_list_stdlib.bzl too large to diff
- buck2/prelude/go/go_stdlib.bzl too large to diff
- buck2/prelude/go/go_test.bzl too large to diff
- buck2/prelude/go/link.bzl too large to diff
- buck2/prelude/go/package_builder.bzl too large to diff
- buck2/prelude/go/packages.bzl too large to diff
- buck2/prelude/go/tags/constraints/BUCK too large to diff
- buck2/prelude/go/tags/constraints/defs.bzl too large to diff
- buck2/prelude/go/toolchain.bzl too large to diff
- buck2/prelude/go/tools/BUCK too large to diff
- buck2/prelude/go/tools/buildid.go too large to diff
- buck2/prelude/go/tools/buildid_test.go too large to diff
- buck2/prelude/go/tools/copy_goroot.go too large to diff
- buck2/prelude/go/tools/gen_embedcfg.go too large to diff
- buck2/prelude/go/tools/go_wrapper.go too large to diff
- buck2/prelude/go/tools/gobuckify/BUCK too large to diff
- buck2/prelude/go/tools/gobuckify/lib/BUCK too large to diff
- buck2/prelude/go/tools/gobuckify/lib/buck.go too large to diff
- buck2/prelude/go/tools/gobuckify/lib/buck_test.go too large to diff
- buck2/prelude/go/tools/gobuckify/lib/config.go too large to diff
- buck2/prelude/go/tools/gobuckify/lib/golist.go too large to diff
- buck2/prelude/go/tools/gobuckify/lib/render.go too large to diff
- buck2/prelude/go/tools/gobuckify/lib/render_test.go too large to diff
- buck2/prelude/go/tools/gobuckify/lib/set.go too large to diff
- buck2/prelude/go/tools/gobuckify/lib/set_test.go too large to diff
- buck2/prelude/go/tools/gobuckify/main.go too large to diff
- buck2/prelude/go/tools/gopackagesdriver/BUCK too large to diff
- buck2/prelude/go/tools/gopackagesdriver/driver.bxl too large to diff
- buck2/prelude/go/tools/gopackagesdriver/driver/BUCK too large to diff
- buck2/prelude/go/tools/gopackagesdriver/driver/buck.go too large to diff
- buck2/prelude/go/tools/gopackagesdriver/driver/buck_test.go too large to diff
- buck2/prelude/go/tools/gopackagesdriver/driver/driver.go too large to diff
- buck2/prelude/go/tools/gopackagesdriver/driver/gobinary.go too large to diff
- buck2/prelude/go/tools/gopackagesdriver/driver/platform.go too large to diff
- buck2/prelude/go/tools/gopackagesdriver/driver/query_bxl.go too large to diff
- buck2/prelude/go/tools/gopackagesdriver/driver/stdlib.go too large to diff
- buck2/prelude/go/tools/gopackagesdriver/driver/targets.go too large to diff
- buck2/prelude/go/tools/gopackagesdriver/driver/telemetry.go too large to diff
- buck2/prelude/go/tools/gopackagesdriver/main.go too large to diff
- buck2/prelude/go/tools/gopackagesdriver/third-party/BUCK too large to diff
- buck2/prelude/go/tools/list_tests.go too large to diff
- buck2/prelude/go/tools/pkg_analyzer.go too large to diff
- buck2/prelude/go/tools/testmaingen.go too large to diff
- buck2/prelude/go/transitions/defs.bzl too large to diff
- buck2/prelude/go/transitions/tags_helper.bzl too large to diff
- buck2/prelude/go_bootstrap/go_bootstrap.bzl too large to diff
- buck2/prelude/go_bootstrap/tools/BUCK too large to diff
- buck2/prelude/go_bootstrap/tools/go_wrapper.py too large to diff
- buck2/prelude/graphql/graphql.bzl too large to diff
- buck2/prelude/haskell/advice.bxl too large to diff
- buck2/prelude/haskell/compile.bzl too large to diff
- buck2/prelude/haskell/compile_per_module.bzl too large to diff
- buck2/prelude/haskell/ghc_api_tool.bzl too large to diff
- buck2/prelude/haskell/haskell.bzl too large to diff
- buck2/prelude/haskell/haskell_ghci.bzl too large to diff
- buck2/prelude/haskell/haskell_haddock.bzl too large to diff
- buck2/prelude/haskell/haskell_ide.bzl too large to diff
- buck2/prelude/haskell/ide/README.md too large to diff
- buck2/prelude/haskell/ide/hie.yaml too large to diff
- buck2/prelude/haskell/ide/ide.bxl too large to diff
- buck2/prelude/haskell/library_info.bzl too large to diff
- buck2/prelude/haskell/link_info.bzl too large to diff
- buck2/prelude/haskell/per_module_worker.bzl too large to diff
- buck2/prelude/haskell/toolchain.bzl too large to diff
- buck2/prelude/haskell/tools/BUCK too large to diff
- buck2/prelude/haskell/tools/ghc-api/Contract.hs too large to diff
- buck2/prelude/haskell/tools/ghc-api/DepFile.hs too large to diff
- buck2/prelude/haskell/tools/ghc-api/Imports.hs too large to diff
- buck2/prelude/haskell/tools/ghc-api/Interface.hs too large to diff
- buck2/prelude/haskell/tools/ghc-api/Libdir.hs too large to diff
- buck2/prelude/haskell/tools/ghc-api/PerModuleCompile.hs too large to diff
- buck2/prelude/haskell/tools/ghc-api/PerModuleDeps.hs too large to diff
- buck2/prelude/haskell/tools/ghc-api/Pragmas.hs too large to diff
- buck2/prelude/haskell/tools/ghc-api/Request.hs too large to diff
- buck2/prelude/haskell/tools/script_template_processor.py too large to diff
- buck2/prelude/haskell/tools/worker/DESIGN.md too large to diff
- buck2/prelude/haskell/tools/worker/README.md too large to diff
- buck2/prelude/haskell/tools/worker/app/Main.hs too large to diff
- buck2/prelude/haskell/tools/worker/bench/Main.hs too large to diff
- buck2/prelude/haskell/tools/worker/props/Main.hs too large to diff
- buck2/prelude/haskell/tools/worker/src/Compat.hs too large to diff
- buck2/prelude/haskell/tools/worker/src/Contract.hs too large to diff
- buck2/prelude/haskell/tools/worker/src/DepFile.hs too large to diff
- buck2/prelude/haskell/tools/worker/src/Grpc.hs too large to diff
- buck2/prelude/haskell/tools/worker/src/Imports.hs too large to diff
- buck2/prelude/haskell/tools/worker/src/Interface.hs too large to diff
- buck2/prelude/haskell/tools/worker/src/Pragmas.hs too large to diff
- buck2/prelude/haskell/tools/worker/src/Proto.hs too large to diff
- buck2/prelude/haskell/tools/worker/src/Request.hs too large to diff
- buck2/prelude/haskell/tools/worker/src/Session.hs too large to diff
- buck2/prelude/haskell/tools/worker/src/Worker.hs too large to diff
- buck2/prelude/haskell/tools/worker/test/Client.hs too large to diff
- buck2/prelude/haskell/tools/worker/test/Main.hs too large to diff
- buck2/prelude/haskell/util.bzl too large to diff
- buck2/prelude/http_archive/exec_deps.bzl too large to diff
- buck2/prelude/http_archive/extract_archive.bzl too large to diff
- buck2/prelude/http_archive/http_archive.bzl too large to diff
- buck2/prelude/http_archive/tools/BUCK too large to diff
- buck2/prelude/http_archive/unarchive.bzl too large to diff
- buck2/prelude/http_file.bzl too large to diff
- buck2/prelude/ide_integrations/apple/build_index/BUCK too large to diff
- buck2/prelude/ide_integrations/apple/build_index/main.py too large to diff
- buck2/prelude/ide_integrations/apple/build_index/swift_index_store.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/BUCK too large to diff
- buck2/prelude/ide_integrations/visual_studio/README.md too large to diff
- buck2/prelude/ide_integrations/visual_studio/constants.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/flags_parser_utils.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/gen_filters.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/gen_mode_configs.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/gen_sln.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/gen_user_macros.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/gen_vcxproj.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/get_attrs.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/get_compiler_settings.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/get_deps.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/get_linker_settings.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/get_mode_hashes.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/get_vs_settings.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/main.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/msvs/absolutize_path.exe too large to diff
- buck2/prelude/ide_integrations/visual_studio/msvs/vs_buck_build.props too large to diff
- buck2/prelude/ide_integrations/visual_studio/ppflags.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/utils.bxl too large to diff
- buck2/prelude/ide_integrations/visual_studio/vsgo.py too large to diff
- buck2/prelude/ide_integrations/xcode/argsfiles.bzl too large to diff
- buck2/prelude/ide_integrations/xcode/data.bzl too large to diff
- buck2/prelude/ide_integrations/xcode/scheme_settings.bzl too large to diff
- buck2/prelude/ide_integrations/xcode/xcode_files.bzl too large to diff
- buck2/prelude/is_buck2.bzl too large to diff
- buck2/prelude/is_buck2_internal.bzl too large to diff
- buck2/prelude/is_full_meta_repo.bzl too large to diff
- buck2/prelude/java/class_to_srcs.bzl too large to diff
- buck2/prelude/java/dex.bzl too large to diff
- buck2/prelude/java/dex_toolchain.bzl too large to diff
- buck2/prelude/java/gwt_binary.bzl too large to diff
- buck2/prelude/java/jar_genrule.bzl too large to diff
- buck2/prelude/java/java.bzl too large to diff
- buck2/prelude/java/java_binary.bzl too large to diff
- buck2/prelude/java/java_library.bzl too large to diff
- buck2/prelude/java/java_providers.bzl too large to diff
- buck2/prelude/java/java_resources.bzl too large to diff
- buck2/prelude/java/java_test.bzl too large to diff
- buck2/prelude/java/java_toolchain.bzl too large to diff
- buck2/prelude/java/javacd_jar_creator.bzl too large to diff
- buck2/prelude/java/plugins/java_annotation_processor.bzl too large to diff
- buck2/prelude/java/plugins/java_plugin.bzl too large to diff
- buck2/prelude/java/prebuilt_jar.bzl too large to diff
- buck2/prelude/java/proguard.bzl too large to diff
- buck2/prelude/java/tools/BUCK too large to diff
- buck2/prelude/java/tools/compile_and_package.py too large to diff
- buck2/prelude/java/tools/fat_jar.py too large to diff
- buck2/prelude/java/tools/gen_class_to_source_map.py too large to diff
- buck2/prelude/java/tools/list_class_names.py too large to diff
- buck2/prelude/java/tools/merge_class_to_source_maps.py too large to diff
- buck2/prelude/java/tools/run_postprocessor.py too large to diff
- buck2/prelude/java/tools/tests/test_fat_jar.py too large to diff
- buck2/prelude/java/tools/tests/test_gen_class_to_source_map.py too large to diff
- buck2/prelude/java/tools/tests/test_list_class_names.py too large to diff
- buck2/prelude/java/tools/tests/test_merge_class_to_source_maps.py too large to diff
- buck2/prelude/java/tools/utils.py too large to diff
- buck2/prelude/java/utils/java_more_utils.bzl too large to diff
- buck2/prelude/java/utils/java_utils.bzl too large to diff
- buck2/prelude/js/js.bzl too large to diff
- buck2/prelude/js/js_bundle.bzl too large to diff
- buck2/prelude/js/js_bundle_genrule.bzl too large to diff
- buck2/prelude/js/js_library.bzl too large to diff
- buck2/prelude/js/js_providers.bzl too large to diff
- buck2/prelude/js/js_utils.bzl too large to diff
- buck2/prelude/js/worker_runner/BUCK too large to diff
- buck2/prelude/js/worker_runner/worker_tool_runner.py too large to diff
- buck2/prelude/js/worker_tool.bzl too large to diff
- buck2/prelude/julia/julia.bzl too large to diff
- buck2/prelude/julia/julia_binary.bzl too large to diff
- buck2/prelude/julia/julia_info.bzl too large to diff
- buck2/prelude/julia/julia_library.bzl too large to diff
- buck2/prelude/julia/julia_test.bzl too large to diff
- buck2/prelude/julia/julia_toolchain.bzl too large to diff
- buck2/prelude/julia/tools/BUCK too large to diff
- buck2/prelude/julia/tools/parse_julia_cmd.py too large to diff
- buck2/prelude/jvm/cd_jar_creator_util.bzl too large to diff
- buck2/prelude/jvm/nullsafe.bzl too large to diff
- buck2/prelude/kotlin/kotlin.bzl too large to diff
- buck2/prelude/kotlin/kotlin_library.bzl too large to diff
- buck2/prelude/kotlin/kotlin_test.bzl too large to diff
- buck2/prelude/kotlin/kotlin_toolchain.bzl too large to diff
- buck2/prelude/kotlin/kotlin_utils.bzl too large to diff
- buck2/prelude/kotlin/kotlincd_jar_creator.bzl too large to diff
- buck2/prelude/kotlin/tools/compile_kotlin/BUCK too large to diff
- buck2/prelude/kotlin/tools/compile_kotlin/compile_kotlin.py too large to diff
- buck2/prelude/kotlin/tools/defs.bzl too large to diff
- buck2/prelude/kotlin/tools/kapt_base64_encoder/BUCK too large to diff
- buck2/prelude/kotlin/tools/kapt_base64_encoder/com/facebook/kapt/KaptBase64Encoder.java too large to diff
- buck2/prelude/linking/add_elf_sections.bzl too large to diff
- buck2/prelude/linking/execution_preference.bzl too large to diff
- buck2/prelude/linking/generated_build_info.bzl too large to diff
- buck2/prelude/linking/link_groups.bzl too large to diff
- buck2/prelude/linking/link_groups_explained.md too large to diff
- buck2/prelude/linking/link_info.bzl too large to diff
- buck2/prelude/linking/linkable_graph.bzl too large to diff
- buck2/prelude/linking/linkables.bzl too large to diff
- buck2/prelude/linking/lto.bzl too large to diff
- buck2/prelude/linking/shared_libraries.bzl too large to diff
- buck2/prelude/linking/stamp_build_info.bzl too large to diff
- buck2/prelude/linking/strip.bzl too large to diff
- buck2/prelude/linking/types.bzl too large to diff
- buck2/prelude/local_only.bzl too large to diff
- buck2/prelude/lua/cxx_lua_extension.bzl too large to diff
- buck2/prelude/lua/lua_binary.bzl too large to diff
- buck2/prelude/lua/lua_library.bzl too large to diff
- buck2/prelude/matlab/matlab.bzl too large to diff
- buck2/prelude/matlab/matlab_info.bzl too large to diff
- buck2/prelude/matlab/matlab_program.bzl too large to diff
- buck2/prelude/matlab/matlab_toolchain.bzl too large to diff
- buck2/prelude/native.bzl too large to diff
- buck2/prelude/none.bzl too large to diff
- buck2/prelude/ocaml/attrs.bzl too large to diff
- buck2/prelude/ocaml/makefile.bzl too large to diff
- buck2/prelude/ocaml/ocaml.bzl too large to diff
- buck2/prelude/ocaml/ocaml_toolchain_types.bzl too large to diff
- buck2/prelude/os/BUCK too large to diff
- buck2/prelude/os/constraints/BUCK too large to diff
- buck2/prelude/os_lookup/defs.bzl too large to diff
- buck2/prelude/os_lookup/targets/BUCK too large to diff
- buck2/prelude/oss/CHANGELOG.md too large to diff
- buck2/prelude/oss/CODE_OF_CONDUCT.md too large to diff
- buck2/prelude/oss/CONTRIBUTING.md too large to diff
- buck2/prelude/oss/LICENSE-APACHE too large to diff
- buck2/prelude/oss/LICENSE-MIT too large to diff
- buck2/prelude/oss/README.md too large to diff
- buck2/prelude/oss/pull_request_template.md too large to diff
- buck2/prelude/paths.bzl too large to diff
- buck2/prelude/platforms/BUCK too large to diff
- buck2/prelude/platforms/apple/base.bzl too large to diff
- buck2/prelude/platforms/apple/build_mode.bzl too large to diff
- buck2/prelude/platforms/apple/constants.bzl too large to diff
- buck2/prelude/platforms/apple/platforms.bzl too large to diff
- buck2/prelude/platforms/apple/platforms_map.bzl too large to diff
- buck2/prelude/platforms/apple/sdk.bzl too large to diff
- buck2/prelude/platforms/defs.bzl too large to diff
- buck2/prelude/playground/test.bxl too large to diff
- buck2/prelude/prelude.bzl too large to diff
- buck2/prelude/python/compile.bzl too large to diff
- buck2/prelude/python/compute_providers.bzl too large to diff
- buck2/prelude/python/cxx_python_extension.bzl too large to diff
- buck2/prelude/python/cython/cython_compile.bzl too large to diff
- buck2/prelude/python/cython/cython_library.bzl too large to diff
- buck2/prelude/python/cython/cython_providers.bzl too large to diff
- buck2/prelude/python/cython/cython_static_extension.bzl too large to diff
- buck2/prelude/python/cython/cython_toolchain.bzl too large to diff
- buck2/prelude/python/interface.bzl too large to diff
- buck2/prelude/python/internal_tools.bzl too large to diff
- buck2/prelude/python/lazy_imports.bzl too large to diff
- buck2/prelude/python/linking/link_helper.bzl too large to diff
- buck2/prelude/python/linking/native.bzl too large to diff
- buck2/prelude/python/linking/native_python_util.bzl too large to diff
- buck2/prelude/python/linking/omnibus.bzl too large to diff
- buck2/prelude/python/make_py_package.bzl too large to diff
- buck2/prelude/python/manifest.bzl too large to diff
- buck2/prelude/python/needed_coverage.bzl too large to diff
- buck2/prelude/python/prebuilt_python_library.bzl too large to diff
- buck2/prelude/python/python.bzl too large to diff
- buck2/prelude/python/python_binary.bzl too large to diff
- buck2/prelude/python/python_library.bzl too large to diff
- buck2/prelude/python/python_needed_coverage_test.bzl too large to diff
- buck2/prelude/python/python_runtime_bundle.bzl too large to diff
- buck2/prelude/python/python_test.bzl too large to diff
- buck2/prelude/python/python_wheel.bzl too large to diff
- buck2/prelude/python/python_wheel_toolchain.bzl too large to diff
- buck2/prelude/python/runtime/BUCK too large to diff
- buck2/prelude/python/runtime/__par__/bootstrap.py too large to diff
- buck2/prelude/python/source_db.bzl too large to diff
- buck2/prelude/python/sourcedb/build.bxl too large to diff
- buck2/prelude/python/sourcedb/classic.bxl too large to diff
- buck2/prelude/python/sourcedb/code_navigation.bxl too large to diff
- buck2/prelude/python/sourcedb/filter.bxl too large to diff
- buck2/prelude/python/sourcedb/ide.bxl too large to diff
- buck2/prelude/python/sourcedb/merge.bxl too large to diff
- buck2/prelude/python/sourcedb/owners.bxl too large to diff
- buck2/prelude/python/sourcedb/pyrefly.bxl too large to diff
- buck2/prelude/python/sourcedb/pysa_merged_source_db.bxl too large to diff
- buck2/prelude/python/sourcedb/query.bxl too large to diff
- buck2/prelude/python/sourcedb/tests/pyrefly_expected.json too large to diff
- buck2/prelude/python/sourcedb/tests/pyrefly_test.py too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/BUCK too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/alias.py too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/gen.sh too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/lib.py too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/main.py too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/my_extension.cpp too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/my_extension.py too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/my_extension.pyi too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/subdir/__init__.py too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/subdir/__init__.pyi too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/subdir/util.py too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/subdir/util.pyi too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/test_rules.bzl too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/triton_collision/BUCK too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/triton_collision/a/BUCK too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/triton_collision/a/extension.cpp too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/triton_collision/a/kernel.py too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/triton_collision/extension.cpp too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/triton_collision/kernel.py too large to diff
- buck2/prelude/python/sourcedb/tests/test_files/triton_kernel.py too large to diff
- buck2/prelude/python/sourcedb/typing_query.bxl too large to diff
- buck2/prelude/python/toolchain.bzl too large to diff
- buck2/prelude/python/tools/BUCK too large to diff
- buck2/prelude/python/tools/__test_main__.py too large to diff
- buck2/prelude/python/tools/compile.py too large to diff
- buck2/prelude/python/tools/create_link_tree.py too large to diff
- buck2/prelude/python/tools/create_manifest_for_source_dir.py too large to diff
- buck2/prelude/python/tools/discover_python_archives.sh too large to diff
- buck2/prelude/python/tools/embedded_main.cpp too large to diff
- buck2/prelude/python/tools/empty_typing_result.json too large to diff
- buck2/prelude/python/tools/extract.py too large to diff
- buck2/prelude/python/tools/fail_with_message.py too large to diff
- buck2/prelude/python/tools/gather_libpython_symbols.py too large to diff
- buck2/prelude/python/tools/gen_bytecode_bundle.py too large to diff
- buck2/prelude/python/tools/generate_static_extension_info.py too large to diff
- buck2/prelude/python/tools/make_par/BUCK too large to diff
- buck2/prelude/python/tools/make_par/__run_lpar_main__.py too large to diff
- buck2/prelude/python/tools/make_par/_lpar_bootstrap.sh.template too large to diff
- buck2/prelude/python/tools/make_par/gen_lpar_bootstrap.py too large to diff
- buck2/prelude/python/tools/make_par/live_builder.py too large to diff
- buck2/prelude/python/tools/make_par/par_builder.py too large to diff
- buck2/prelude/python/tools/make_par/sitecustomize.py too large to diff
- buck2/prelude/python/tools/make_py_package_inplace.py too large to diff
- buck2/prelude/python/tools/make_py_package_manifest_module.py too large to diff
- buck2/prelude/python/tools/make_py_package_modules.py too large to diff
- buck2/prelude/python/tools/make_source_db.py too large to diff
- buck2/prelude/python/tools/make_source_db_no_deps.py too large to diff
- buck2/prelude/python/tools/patchelf.py too large to diff
- buck2/prelude/python/tools/run_inplace.py.in too large to diff
- buck2/prelude/python/tools/sourcedb_merger/BUCK too large to diff
- buck2/prelude/python/tools/sourcedb_merger/inputs.py too large to diff
- buck2/prelude/python/tools/sourcedb_merger/legacy_merge.py too large to diff
- buck2/prelude/python/tools/sourcedb_merger/legacy_outputs.py too large to diff
- buck2/prelude/python/tools/sourcedb_merger/merge.py too large to diff
- buck2/prelude/python/tools/sourcedb_merger/outputs.py too large to diff
- buck2/prelude/python/tools/sourcedb_merger/tests/__init__.py too large to diff
- buck2/prelude/python/tools/sourcedb_merger/tests/inputs_test.py too large to diff
- buck2/prelude/python/tools/sourcedb_merger/tests/legacy_output_test.py too large to diff
- buck2/prelude/python/tools/sourcedb_merger/tests/main.sh too large to diff
- buck2/prelude/python/tools/sourcedb_merger/tests/outputs_test.py too large to diff
- buck2/prelude/python/tools/static_extension_finder.py too large to diff
- buck2/prelude/python/tools/static_extension_utils.cpp too large to diff
- buck2/prelude/python/tools/tests/gen_bytecode_bundle_test.py too large to diff
- buck2/prelude/python/tools/tests/main.sh too large to diff
- buck2/prelude/python/tools/tests/make_py_package_inplace_test.py too large to diff
- buck2/prelude/python/tools/tests/make_py_package_manifest_module_test.py too large to diff
- buck2/prelude/python/tools/tests/type_check_result_to_validation_test.py too large to diff
- buck2/prelude/python/tools/tests/wheel_test.py too large to diff
- buck2/prelude/python/tools/type_check_result_to_validation.py too large to diff
- buck2/prelude/python/tools/wheel.py too large to diff
- buck2/prelude/python/transitions.bzl too large to diff
- buck2/prelude/python/typecheck/batch.bxl too large to diff
- buck2/prelude/python/typecheck/batch_files.bxl too large to diff
- buck2/prelude/python/typing.bzl too large to diff
- buck2/prelude/python/versions.bzl too large to diff
- buck2/prelude/python_bootstrap/python_bootstrap.bzl too large to diff
- buck2/prelude/remote_file.bzl too large to diff
- buck2/prelude/resources.bzl too large to diff
- buck2/prelude/rules.bzl too large to diff
- buck2/prelude/rules_impl.bzl too large to diff
- buck2/prelude/runtime/BUCK too large to diff
- buck2/prelude/runtime/constraints/BUCK too large to diff
- buck2/prelude/rust/build.bzl too large to diff
- buck2/prelude/rust/build_params.bzl too large to diff
- buck2/prelude/rust/buildscript/BUCK too large to diff
- buck2/prelude/rust/buildscript/buildscript_platform.bzl too large to diff
- buck2/prelude/rust/cargo_buildscript.bzl too large to diff
- buck2/prelude/rust/cargo_package.bzl too large to diff
- buck2/prelude/rust/clippy_configuration.bzl too large to diff
- buck2/prelude/rust/context.bzl too large to diff
- buck2/prelude/rust/crate_name.bzl too large to diff
- buck2/prelude/rust/custom-targets/BUCK too large to diff
- buck2/prelude/rust/custom-targets/targets/riscv64emc-unknown-none-elf.json too large to diff
- buck2/prelude/rust/custom-targets/targets/riscv64imacf-unknown-none-elf.json too large to diff
- buck2/prelude/rust/custom-targets/targets/riscv64imacfv-unknown-none-elf.json too large to diff
- buck2/prelude/rust/dep_context.bzl too large to diff
- buck2/prelude/rust/extern.bzl too large to diff
- buck2/prelude/rust/failure_filter.bzl too large to diff
- buck2/prelude/rust/link_info.bzl too large to diff
- buck2/prelude/rust/linkable_symbol.bzl too large to diff
- buck2/prelude/rust/named_deps.bzl too large to diff
- buck2/prelude/rust/outputs.bzl too large to diff
- buck2/prelude/rust/proc_macro_alias.bzl too large to diff
- buck2/prelude/rust/profile.bzl too large to diff
- buck2/prelude/rust/resources.bzl too large to diff
- buck2/prelude/rust/rust-analyzer/check.bxl too large to diff
- buck2/prelude/rust/rust-analyzer/provider.bzl too large to diff
- buck2/prelude/rust/rust-analyzer/resolve_deps.bxl too large to diff
- buck2/prelude/rust/rust_binary.bzl too large to diff
- buck2/prelude/rust/rust_common.bzl too large to diff
- buck2/prelude/rust/rust_library.bzl too large to diff
- buck2/prelude/rust/rust_toolchain.bzl too large to diff
- buck2/prelude/rust/sources.bzl too large to diff
- buck2/prelude/rust/targets.bzl too large to diff
- buck2/prelude/rust/tools/BUCK too large to diff
- buck2/prelude/rust/tools/attrs.bzl too large to diff
- buck2/prelude/rust/tools/buildscript_run.py too large to diff
- buck2/prelude/rust/tools/cd_run.py too large to diff
- buck2/prelude/rust/tools/extract_link_action.py too large to diff
- buck2/prelude/rust/tools/failure_filter_action.py too large to diff
- buck2/prelude/rust/tools/from_any_dir.py too large to diff
- buck2/prelude/rust/tools/linkable_symbol.rs too large to diff
- buck2/prelude/rust/tools/redirect_stdout.py too large to diff
- buck2/prelude/rust/tools/rustc_action.py too large to diff
- buck2/prelude/rust/tools/rustdoc_coverage.py too large to diff
- buck2/prelude/rust/tools/rustdoc_test_with_resources.py too large to diff
- buck2/prelude/rust/tools/shared_libraries_symlink_tree.py too large to diff
- buck2/prelude/rust/tools/symlink_only_dir_entry.py too large to diff
- buck2/prelude/rust/tools/tool_rules.bzl too large to diff
- buck2/prelude/rust/tools/transitive_dependency_symlinks.py too large to diff
- buck2/prelude/rust/with_workspace.bzl too large to diff
- buck2/prelude/sh_binary.bzl too large to diff
- buck2/prelude/sh_test.bzl too large to diff
- buck2/prelude/target_stats/target_stats.bzl too large to diff
- buck2/prelude/target_stats/target_stats_config.bzl too large to diff
- buck2/prelude/target_stats/target_stats_tools.bzl too large to diff
- buck2/prelude/target_stats/target_stats_types.bzl too large to diff
- buck2/prelude/test/inject_test_run_info.bzl too large to diff
- buck2/prelude/test/tools/BUCK too large to diff
- buck2/prelude/test/tools/inject_test_env.py too large to diff
- buck2/prelude/test_suite.bzl too large to diff
- buck2/prelude/tests/re_utils.bzl too large to diff
- buck2/prelude/tests/remote_test_execution_toolchain.bzl too large to diff
- buck2/prelude/tests/test_listing.bzl too large to diff
- buck2/prelude/tests/test_toolchain.bzl too large to diff
- buck2/prelude/third-party/build.bzl too large to diff
- buck2/prelude/third-party/hmaptool/BUCK too large to diff
- buck2/prelude/third-party/hmaptool/METADATA.bzl too large to diff
- buck2/prelude/third-party/hmaptool/README.md too large to diff
- buck2/prelude/third-party/hmaptool/hmaptool too large to diff
- buck2/prelude/third-party/pkgconfig.bzl too large to diff
- buck2/prelude/third-party/providers.bzl too large to diff
- buck2/prelude/third-party/tools/BUCK too large to diff
- buck2/prelude/third-party/tools/create_build.py too large to diff
- buck2/prelude/toolchains/android.bzl too large to diff
- buck2/prelude/toolchains/android/BUCK too large to diff
- buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ApplicationLike.java too large to diff
- buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/BUCK too large to diff
- buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/DefaultApplicationLike.java too large to diff
- buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ExopackageApplication.java too large to diff
- buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ExopackageDexLoader.java too large to diff
- buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ExopackageSoLoader.java too large to diff
- buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/Reflect.java too large to diff
- buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ResourcesLoader.java too large to diff
- buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/SystemClassLoaderAdder.java too large to diff
- buck2/prelude/toolchains/android/config/BUCK too large to diff
- buck2/prelude/toolchains/android/config/oss_toolchains.bzl too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/AdbExecutionContext.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/AdbHelper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/AdbOptions.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/AndroidInstallPrinter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/AndroidManifestReader.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/AndroidManifestReaderExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/DefaultAndroidManifestReader.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/IsolatedApkInfo.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/FakeRDotTxtEntry.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MergeAndroidResourceSourcesExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MergeAndroidResourceSourcesUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MiniAapt.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MiniAaptExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/RDotTxtEntry.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/ResourceSourceMapExecutableMain.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/ResourceSourceMapFormat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/aar/AarBuilderExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/aar/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apex/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apex/apex_manifest.proto too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/ApkBuilderExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/ApkBuilderUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/ApkSignerUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/KeystoreProperties.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/ApkBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/ApkCreationException.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/ApkJarBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/DuplicateFileException.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/IArchiveBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/SealedApkException.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModule.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModuleGraph.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModuleGraphExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModuleMetadataUtil.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/ExternalTargetGraph.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/HasBuildTargetAndBuildDeps.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/TargetGraphInterface.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/BuildConfigFields.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/BuildConfigs.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/GenerateBuildConfigExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/buildinfo/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/buildinfo/BuildInfoGeneratorExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/AndroidBundleApksBuilderExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/AndroidBundleBuilderExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/AndroidBundleUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/device/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/device/TargetDevice.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/device/TargetDeviceOptions.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/CanaryUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/ClassNameFilter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8ExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8Options.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8Output.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8OutputOption.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8Utils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/JarSplitterExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/MultiDexExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/SecondaryDexCompressionExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AdbUtils.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDevice.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDeviceImpl.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDeviceInfo.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDevicesHelper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidIntent.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/DexExoHelper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExoHelper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExopackageInstaller.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExopackageMode.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExopackageUtil.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/InstallTimings.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/IsolatedExopackageInfo.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/NativeExoHelper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/PackageInfo.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ResourcesExoHelper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/GenerateManifest.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/GenerateManifestExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/PreprocessLogger.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/ReplaceApplicationIdPlaceholdersExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/proguard/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/proguard/ProguardMapping.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/proguard/ProguardTranslatorFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/BringToFrontMapper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ExoResourcesRewriter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ExoResourcesRewriterExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAndroidResources.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAndroidResourcesExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAssetsExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAssetsUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ReferenceMapper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResChunk.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResTablePackage.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResTableType.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResTableTypeSpec.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResourceTable.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResourcesXml.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResourcesZipBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/StringPool.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/UsedResourcesFinder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/DrawableFinder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/FilterResourcesExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/FilteredDirectoryCopier.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/FilteringPredicate.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/GetStringsFiles.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/ResourceFilters.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/ThrowingRunnable.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/CompileStrings.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/CopyStringResourcesExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/PackageStringsAsAssetsExecutableMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/StringResources.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/StringResourcesUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/zipalign/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/android/zipalign/ZipAlign.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/common.proto too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/javacd.proto too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/kotlincd.proto too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/ClassLoaderBootstrapper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/ClassLoaderBootstrapperUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/ClassLoaderFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/build/execution/context/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/build/execution/context/IsolatedExecutionContext.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/AbsPath.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/AbsPathImpl.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/PathWrapper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/PathWrapperImpl.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/RelPath.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/RelPathImpl.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/AbstractBreadthFirstThrowingTraversal.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/AbstractBreadthFirstTraversal.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/DirectedAcyclicGraph.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/MutableDirectedGraph.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/TraversableGraph.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/TraversableGraphs.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/Logger.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/appendablelogrecord/AppendableLogRecord.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/appendablelogrecord/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/features/zip/rules/utils/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/features/zip/rules/utils/ZipMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/features/zip/rules/utils/ZipUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallCommand.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallError.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallErrorCategory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallErrorTag.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallId.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallResult.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallerServer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallerService.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AdbHelperFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidArtifacts.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidCommandLineOptions.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstall.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallApkOptions.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallErrorClassifier.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallErrorTag.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallException.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallerMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallerManager.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/InstallMetrics.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/InstallState.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/IsolatedAndroidInstallerPrinter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/StreamedPushes.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/common/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/common/ConsumeAllOptionsHandler.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/proto/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/installer/proto/install.proto too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/FileExtensionMatcher.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/GlobPatternMatcher.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/MorePaths.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/MorePosixFilePermissions.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/MostFiles.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/PathListing.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/PathMatcher.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/CopySourceMode.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/impl/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/impl/ProjectFilesystemUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/pathformat/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/pathformat/PathFormatter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/windowsfs/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/windowsfs/WindowsFS.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/io/windowsfs/WindowsFSLibrary.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/AbiDirWriter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/AbiStepsBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/BuildCommandStepsBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompileStepsBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompileStepsBuilderFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompilerDaemonLoggerUtil.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompilerDaemonRunner.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultAbiStepsBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultCompileStepsBuilderBase.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultCompileStepsBuilderFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultLibraryStepsBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DepFileUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/ErrorInterceptor.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/JavaLibraryRules.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/JvmCDCommand.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/LibraryStepsBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/BaseJarCommand.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/BuildMode.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/PostBuildParams.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/java/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/java/BuildJavaCommand.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/BuildKotlinCommand.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/KotlinExtraParams.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/LanguageVersion.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/AbsPathSerializer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/PathSerializer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/RelPathSerializer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/SerializationUtil.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/BuildTargetValueSerializer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/CompilerOutputPathsSerializer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/CompilerOutputPathsValueSerializer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/JarParametersSerializer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/JavacLanguageLevelOptionsSerializer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/JavacPluginParamsSerializer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/RemoveClassesPatternsMatcherSerializer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/ResolvedJavacOptionsSerializer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/ResolvedJavacPluginPropertiesSerializer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/ActionMetadataSerializer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/DigestSerializer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/KotlinExtraParamsSerializer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/MainUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc/WorkerGrpcServer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc/WorkerGrpcService.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/core/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/core/BuildTargetValue.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/core/BuildTargetValueExtraParams.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ActionMetadata.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/AnnotationProcessorFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/BaseCompileToJarStepFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/BaseJavacToJarStepFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CalculateClassAbiStep.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClassUsageFileWriter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClassUsageTracker.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClassUsageURIParser.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClasspathChecker.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompileToJarStepFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompilerOutputPaths.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompilerOutputPathsValue.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompilerParameters.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CopyResourcesStep.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DaemonJavacToJarStepFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DefaultClassUsageFileWriter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DefaultSourceOnlyAbiRuleInfo.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DefaultSourceOnlyAbiRuleInfoFactory.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DiagnosticCleaner.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DiagnosticPrettyPrinter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DowngradeMissingAnnotationErrorMessager.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/FileManagerListener.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ForwardingStandardJavaFileManager.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarDiffer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarDumper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarFileObject.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarParameters.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaExtraParams.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaInMemoryFileManager.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaInMemoryFileObject.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaNoOpFileObject.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaPaths.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaStepsBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacExecutionContext.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacLanguageLevelOptions.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacPipelineState.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacPluginParams.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacStep.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacVersion.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JdkProvidedInMemoryJavac.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/Jsr199Javac.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/Jsr199JavacInvocation.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ListenableFileManager.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/OptionsConsumer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/PluginFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/PluginLoaderJavaFileManager.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/RemoveClassesPatternsMatcher.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ResolvedJavac.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ResolvedJavacOptions.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ResolvedJavacPluginProperties.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ZipEntryJavaFileObject.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/AbiFilteringClassVisitor.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/AbiGenerationModeUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/AccessFlags.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ApiStubber.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ClassReferenceTracker.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ClassVisitorDriverFromElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/DescriptorFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/DirectoryReader.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ElementsReader.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/FilesystemStubJarWriter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/InnerClassesTable.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/JarBuilderStubJarWriter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/JarReader.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/LibraryReader.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SignatureFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SignatureVisitorWrapper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SourceAbiCompatibleSignatureVisitor.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SourceAbiCompatibleVisitor.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SourceBasedAbiStubber.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubClassFileWriter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubGenerator.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJar.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarClassEntry.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarEntry.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarExistingEntry.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarResourceEntry.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarWriter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/TypeScanner8.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/java17/SourceVersionUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/java21/SourceVersionUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/InlineFunctionScope.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/KotlinMetadataReader.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/kotlin-1.4.2/KotlinMetadataReader.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialAnnotatedConstruct.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialAnnotationMirror.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialAnnotationValue.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialExecutableElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialPackageElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialParameterizable.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialQualifiedNameable.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialTypeElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialTypeParameterElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialVariableElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompilerErrorException.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompilerTypeResolutionSimulator.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompletedTypeKind.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompletionSimulator.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ElementTreeFinder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/EnteringPlugin.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/FileManagerSimulator.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/FrontendOnlyJavacTask.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/FrontendOnlyJavacTaskProxyImpl.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ImportsTracker.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredDeclaredType.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredPackageElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredTypeElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InterfaceScanner.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InterfaceValidator.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/PostEnterCanonicalizer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ResolvedType.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ResolvedTypeKind.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneArrayType.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneDeclaredType.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneExecutableType.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneIntersectionType.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandalonePackageType.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneTypeMirror.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneTypeVariable.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneWildcardType.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotatedConstruct.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotationFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotationMirror.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotationValue.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedElements.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedEnter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedExecutableElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedFiler.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedMessager.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedPackageElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedParameterizable.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedProcessingEnvironment.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedProcessorWrapper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedRoundEnvironment.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTrees.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypeElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypeParameterElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypeResolutionSimulator.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypes.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedVariableElement.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeContextScanner.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreePathScannerForTypeResolution.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ValidatingTaskListener.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/CannotInferException.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/ErrorSuppressingDiagnosticListener.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/FrontendOnlyJavacTaskProxy.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/SourceCodeWillNotCompileException.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/SourceOnlyAbiRuleInfoFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/StopCompilation.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/package-info.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/AbstractFileLike.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/ClasspathTraversal.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/ClasspathTraverser.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/DefaultClasspathTraverser.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/FileLike.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/FileLikeCharSource.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/FileLikes.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/fatjar/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/fatjar/FatJarMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/fatjar/WindowsCreateProcessEscape.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/javax/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/javax/SynchronizedToolProvider.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/extra/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/extra/MoreTypeAnnotations.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/AnnotationValueScanner8.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/BridgeMethod.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/ElementsExtended.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/MoreAnnotations.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/MoreElements.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/PluginLoader.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BridgeMethods.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacPlugin.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacTask.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacTaskListenerProxy.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacTaskProxyImpl.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/CompilationUnitTreeProxyImpl.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/DelegatingElements.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/ElementsExtendedImpl.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/JavacTaskWrapper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/MultiplexingTaskListener.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/PostEnterTaskListener.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/TaskListenerProxy.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/TaskListenerWrapper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/TreesMessager.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/BuckJavacTaskListener.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/BuckJavacTaskProxy.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/CompilationUnitTreeProxy.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/PluginClassLoader.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/PluginClassLoaderFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/TaskEventMirror.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/javac-plugin.jar too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/runner/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/runner/FileClassPathRunner.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/JavaCDCommand.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/JavaCDGrpcWorkerToolMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/JavaCDMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/worker/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/version/utils/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/version/utils/JavaVersionUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/AnnotationProcessorUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ClassUsageFileWriterFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ClasspathChangesFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ClasspathUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/CompilerPluginUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/DaemonKotlincToJarStepFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/IncrementalCompilationValidator.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/JarsActionMetadata.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/JavacStepsBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KaptStep.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KaptStepsBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiConfig.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiPluginOptions.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiStubgenStep.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiStubgenStepsBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinCDLoggingContextFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinCDModelHelper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinCStepsBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinClassUsageHelper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinSourceChangesFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinStepsBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlincFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlincModeFactory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlincStep.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/Ksp2ModeFactory.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KspStepsBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/SnapshotsActionMetadata.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/SourceFilesActionMetadata.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ExperimentConfig.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ExperimentConfigService.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ksic/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ksic/KsicExperimentConstants.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/NoopExperimentConfig.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/NoopExperimentConfigService.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/resources/META-INF/services/com.facebook.buck.jvm.kotlin.abtesting.ExperimentConfigService too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/BuckKotlinLogger.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/BuildToolsKotlinc.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/ExitCode.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/JvmCompilationConfigurationFactory.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/KotlinCompilationService.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/SharedApiClassesClassLoaderProvider.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/SourceChangesExtensions.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/ClasspathSnapshotGenerator.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/Main.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/SnapshotGranularity.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/KotlinCDAnalytics.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/KotlinCDLoggingContext.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/KotlinCDLoggingParams.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/SourceTokenCounter.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/KotlinCDLogger.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/KotlinCDLoggerAnalytics.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/model/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/model/KotlinCDLogEntry.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/noop/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/noop/KotlinCDNoopLogger.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/noop/resources/META-INF/services/com.facebook.buck.jvm.kotlin.cd.analytics.logger.KotlinCDLogger too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/worker/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/KotlinCDCommand.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/KotlinCDGrpcWorkerToolMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/KotlinCDMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/ClassAbiWriter.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/PreviousStateWriter.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/SkippedCompilationTracker.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/File.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/FileChecks.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/StubUtils.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/Types.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/Common.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/FullTypeQualifier.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/KosabiLogger.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/NonConventionalImports.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/FakeKtFile.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KArrayType.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KClassType.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KFunStub.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KPropertyStub.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KStub.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KType.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KWildcardType.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/Type.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/render/StubBytecodeRender.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/render/StubRender.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/BytecodeTransformer.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiCommandLineProcessor.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiComponentRegistrar.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiConfigurationKeys.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiFirAnalysisHandlerExtension.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/KosabiClassUsageCollector.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/common/Types.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/DependencyListCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirCollectionLiteralCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirDefaultVisitorVoidCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirJvmSessionFactoryCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirNamedFunctionCopyCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirResultCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirSourceModuleDataCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FrontendPipelineCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/IrNonAbiStripper.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/IrVisitorCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/MetadataVersionCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/OptInAnnotationsCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/PipelineCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/DependencyListCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirCollectionLiteralCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirDefaultVisitorVoidCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirNamedFunctionCopyCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirResultCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirSourceModuleDataCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FrontendPipelineCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/IrNonAbiStripper.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/IrVisitorCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/MetadataVersionCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/OptInAnnotationsCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/PipelineCompat.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ClassStabilityTransformer.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposableTypeRewriter.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposeAbiEmulationExtension.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposeAbiEmulationStage.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposerParamInjector.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/parcelize/ParcelableCreatorEmulator.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/parcelize/ParcelizeAbiEmulationExtension.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenContext.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenPipeline.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenRepairLog.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenStage.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/cli/Main.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/cli/StubsGenCli.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/cli/StubsGenParseOnlyEnvironment.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/AnnotationStubsGenerator.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/ClassLevelFunctionStubsGenerator.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/CtorStubsGenerator.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/FullQualifiedClassStubsGenerator.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/GenerationContext.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/GenericStubsGenerator.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/InnerClassStubsGenerator.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/InterfaceStubsGenerator.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/PrimitiveStubsGenerator.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/SamePackageClassStubsGenerator.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/StubsGenAPI.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/StubsGenerator.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/StubsCodegenCommandLineProcessor.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/StubsCodegenCompilerPluginRegistrar.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/StubsCodegenK2FirAnalysisHandlerExtension.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/stub/container/StubsContainer.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/stub/container/StubsContainerImpl.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/FTQCollection.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/JavaLangTypes.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KTBuiltInTypes.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KTJavaTypeAlias.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KTStdlibTypes.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtClassLiteralExpressionExt.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtFileExt.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtImportDirectiveExt.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtUserTypeExt.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/PrimitiveTypeUtil.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/UserTypeUtil.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/usedclasses/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/usedclasses/ClassUsageMerger.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/Kotlinc.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/ClasspathChanges.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/KotlinSourceChanges.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/KotlincMode.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/RebuildReason.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/BuckKsp2Logger.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/Factory.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/FilteringClassLoader.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/Ksp2NoOpDetector.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/Ksp2Step.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/incremental/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/incremental/Ksp2Mode.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/incremental/ReprocessReason.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/plugin/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/plugin/PluginLoader.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/plugin/dep-tracker.jar too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/util/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/util/KotlinUnarchiver.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/StepExecutionResult.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/StepExecutionResults.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/IsolatedStep.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/IsolatedStepsRunner.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/StepFailedException.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/AbstractIsolatedExecutionStep.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/CopyIsolatedStep.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/MakeCleanDirectoryIsolatedStep.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/MkdirIsolatedStep.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/RmIsolatedStep.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/SymlinkIsolatedStep.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/ZipIsolatedStep.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/java/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/java/JarDirectoryStep.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/java/MakeMissingOutputsStep.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/test/result/type/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/test/result/type/ResultType.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/Nullable.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/PatternTestSelector.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/SimpleTestSelector.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestDescription.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestSelector.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestSelectorList.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestSelectorParseException.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testresultsoutput/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testresultsoutput/TestResultsOutputEvent.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testresultsoutput/TestResultsOutputSender.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BasePerTestCoverageRunListener.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BaseRunner.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BuckBlockJUnit4ClassRunner.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BuckXmlTestRunListener.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/CheckDependency.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/CrashAnalyzer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/CrashCapturer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/DeviceRunner.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationMainForClout.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTestRunner.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTestRunnerForClout.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTimeoutEnforcingRunListener.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTpxStandardOutputTestListener.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitOptions.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitRunner.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitSupport.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitTpxStandardOutputListener.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JavaUtilLoggingHelper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JulLogFormatter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JupiterMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JupiterRunner.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/META-INF/services/org.junit.jupiter.api.extension.Extension too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/PerTestCoverageExtension.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/PerTestCoverageExtensionManager.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/PerTestJUnitCoverageRunListener.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/RobolectricTimeoutEnforcingRunListener.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/RunShellCommand.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/SameThreadFailOnTimeout.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/SkipTestCondition.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/StandardOutputRecorder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestNGMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestNGRunner.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestRecorder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestResult.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestXmlEscaper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/ThreadDumpUtils.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TpxStandardOutputTestListener.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TpxTimeoutBufferManager.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/LogExtractorReportLayer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/PerfettoReportLayer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/ReportLayer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/TombstonesReportLayer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/VideoRecordingReportLayer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/AbstractMemoizer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/BuckConstant.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/CapturingPrintStream.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/ClassLoaderCache.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/Console.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/Escaper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/ExitCode.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/Memoizer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/MoreSuppliers.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/NamedTemporaryFile.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/PatternsMatcher.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/Threads.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/ThrowingPrintWriter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/Verbosity.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/ZipFileTraversal.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/EnvVariablesProvider.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/Platform.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/PlatformType.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/BashEscaper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/EscaperUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/Quoter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/function/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/function/ThrowingSupplier.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/io/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/io/IoUtil.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/json/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/json/ObjectMappers.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/liteinfersupport/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/liteinfersupport/Nullable.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/liteinfersupport/PropagatesNullable.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/ByteBufferUnmapper.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/LargeByteBuffer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/MappableByteBufferHolder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/perf/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/perf/PerfStatsTracking.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/relativepathmap/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/relativepathmap/RelativePathMapUtils.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/unarchive/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/unarchive/DirectoryCreator.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/unarchive/Unzip.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/unit/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/unit/SizeUnit.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/xml/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/xml/XmlDomParser.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/AppendableCentralDirectory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/AppendingZipOutputStreamImpl.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/BestCompressionGZIPOutputStream.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ByteIo.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectory.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectoryFileHeader.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectoryHeader.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectoryReader.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ConcatJarBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ConcatenateJars.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomJarOutputStream.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomZipEntry.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomZipEntryWithPath.kt too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomZipOutputStream.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DeterministicManifest.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DeterministicZipBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DirectoryJarBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DirectoryJarEntryContainer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/EntryAccounting.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/IncrementalJarOutputStreamImpl.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarBuilderMain.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarDiff.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarEntryContainer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarEntrySupplier.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarManifestMerger.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ManifestAttributeMerger.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/OverwritingZipOutputStreamImpl.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/RepackZipEntries.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/SimpleZipOutputStreamImpl.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/Zip.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipCompressionLevel.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipConstants.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipFileJarEntryContainer.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipOutputStreams.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipScrubber.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/FileZipEntrySource.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/OnDuplicateEntry.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySource.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceCollection.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceCollectionBuilder.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceCollectionWriter.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceFromZip.java too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/workertool/resources/proto/BUCK too large to diff
- buck2/prelude/toolchains/android/src/com/facebook/buck/workertool/resources/proto/worker.proto too large to diff
- buck2/prelude/toolchains/android/third-party/BUCK too large to diff
- buck2/prelude/toolchains/android/third-party/aosp/BUCK too large to diff
- buck2/prelude/toolchains/android/tools/build_rules.bzl too large to diff
- buck2/prelude/toolchains/android/tools/build_rules/fb_native.bzl too large to diff
- buck2/prelude/toolchains/android/tools/build_rules/utils.bzl too large to diff
- buck2/prelude/toolchains/android/tools/build_rules/worker.bzl too large to diff
- buck2/prelude/toolchains/android/tools/protobuf.bzl too large to diff
- buck2/prelude/toolchains/android/tools/protobuf/BUCK too large to diff
- buck2/prelude/toolchains/apple/xcode_version_checker/BUCK too large to diff
- buck2/prelude/toolchains/apple/xcode_version_checker/Makefile too large to diff
- buck2/prelude/toolchains/apple/xcode_version_checker/README too large to diff
- buck2/prelude/toolchains/apple/xcode_version_checker/defs.bzl too large to diff
- buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_exec_tester.m too large to diff
- buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_checker.m too large to diff
- buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_checks.h too large to diff
- buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_checks.m too large to diff
- buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_tester.m too large to diff
- buck2/prelude/toolchains/apple/xcode_version_checker/test/Xcode_14.2.0_14C18_fb_version.plist too large to diff
- buck2/prelude/toolchains/apple/xcode_version_checker/xcode_version_checker too large to diff
- buck2/prelude/toolchains/conan/BUCK too large to diff
- buck2/prelude/toolchains/conan/buckler/conanfile.py too large to diff
- buck2/prelude/toolchains/conan/conan_common.py too large to diff
- buck2/prelude/toolchains/conan/conan_generate.py too large to diff
- buck2/prelude/toolchains/conan/conan_init.py too large to diff
- buck2/prelude/toolchains/conan/conan_lock.py too large to diff
- buck2/prelude/toolchains/conan/conan_package.py too large to diff
- buck2/prelude/toolchains/conan/conan_package_extract.py too large to diff
- buck2/prelude/toolchains/conan/conan_update.py too large to diff
- buck2/prelude/toolchains/conan/defs.bzl too large to diff
- buck2/prelude/toolchains/conan/lock_generate.py too large to diff
- buck2/prelude/toolchains/csharp.bzl too large to diff
- buck2/prelude/toolchains/cxx.bzl too large to diff
- buck2/prelude/toolchains/cxx/clang/BUCK too large to diff
- buck2/prelude/toolchains/cxx/clang/tools.bzl too large to diff
- buck2/prelude/toolchains/cxx/zig/defs.bzl too large to diff
- buck2/prelude/toolchains/cxx/zig/releases.bzl too large to diff
- buck2/prelude/toolchains/demo.bzl too large to diff
- buck2/prelude/toolchains/dex.bzl too large to diff
- buck2/prelude/toolchains/erlang.bzl too large to diff
- buck2/prelude/toolchains/execution_host.bzl too large to diff
- buck2/prelude/toolchains/genrule.bzl too large to diff
- buck2/prelude/toolchains/go.bzl too large to diff
- buck2/prelude/toolchains/go/go_bootstrap_toolchain.bzl too large to diff
- buck2/prelude/toolchains/go/go_toolchain.bzl too large to diff
- buck2/prelude/toolchains/go/system_go_bootstrap_toolchain.bzl too large to diff
- buck2/prelude/toolchains/go/system_go_toolchain.bzl too large to diff
- buck2/prelude/toolchains/haskell.bzl too large to diff
- buck2/prelude/toolchains/java.bzl too large to diff
- buck2/prelude/toolchains/kotlin.bzl too large to diff
- buck2/prelude/toolchains/msvc/BUCK too large to diff
- buck2/prelude/toolchains/msvc/run_msvc_tool.py too large to diff
- buck2/prelude/toolchains/msvc/tools.bzl too large to diff
- buck2/prelude/toolchains/msvc/vswhere.py too large to diff
- buck2/prelude/toolchains/no_toolchain.bzl too large to diff
- buck2/prelude/toolchains/ocaml.bzl too large to diff
- buck2/prelude/toolchains/python.bzl too large to diff
- buck2/prelude/toolchains/remote_test_execution.bzl too large to diff
- buck2/prelude/toolchains/rust.bzl too large to diff
- buck2/prelude/toolchains/zip_file.bzl too large to diff
- buck2/prelude/tools/audit_providers_universe.bxl too large to diff
- buck2/prelude/transitions/constraint_override_registry.bzl too large to diff
- buck2/prelude/transitions/constraint_overrides.bzl too large to diff
- buck2/prelude/transitions/utils.bzl too large to diff
- buck2/prelude/unix/providers.bzl too large to diff
- buck2/prelude/user/all.bzl too large to diff
- buck2/prelude/user/cxx_headers_bundle.bzl too large to diff
- buck2/prelude/user/rule_spec.bzl too large to diff
- buck2/prelude/user/write_file.bzl too large to diff
- buck2/prelude/utils/actions.bzl too large to diff
- buck2/prelude/utils/argfile.bzl too large to diff
- buck2/prelude/utils/arglike.bzl too large to diff
- buck2/prelude/utils/buckconfig.bzl too large to diff
- buck2/prelude/utils/build_graph_pattern.bzl too large to diff
- buck2/prelude/utils/build_target_pattern.bzl too large to diff
- buck2/prelude/utils/clear_platform.bzl too large to diff
- buck2/prelude/utils/cmd_script.bzl too large to diff
- buck2/prelude/utils/dicts.bzl too large to diff
- buck2/prelude/utils/directory_fold.bzl too large to diff
- buck2/prelude/utils/expect.bzl too large to diff
- buck2/prelude/utils/glob_defs.bzl too large to diff
- buck2/prelude/utils/graph_utils.bzl too large to diff
- buck2/prelude/utils/host.bzl too large to diff
- buck2/prelude/utils/label_provider.bzl too large to diff
- buck2/prelude/utils/lazy.bzl too large to diff
- buck2/prelude/utils/materialization_test.bzl too large to diff
- buck2/prelude/utils/pick.bzl too large to diff
- buck2/prelude/utils/selects.bzl too large to diff
- buck2/prelude/utils/set.bzl too large to diff
- buck2/prelude/utils/source_listing.bzl too large to diff
- buck2/prelude/utils/source_listing_impl.bzl too large to diff
- buck2/prelude/utils/strings.bzl too large to diff
- buck2/prelude/utils/type_defs.bzl too large to diff
- buck2/prelude/utils/utils.bzl too large to diff
- buck2/prelude/validation/audit_results.bxl too large to diff
- buck2/prelude/validation_deps.bzl too large to diff
- buck2/prelude/windows/tools/BUCK too large to diff
- buck2/prelude/windows/tools/msvc_hermetic_exec.bat too large to diff
- buck2/prelude/xplugins/attrs.bzl too large to diff
- buck2/prelude/xplugins/debug_artifacts.bzl too large to diff
- buck2/prelude/xplugins/types.bzl too large to diff
- buck2/prelude/xplugins/utils.bzl too large to diff
- buck2/prelude/zip_file/tools/BUCK too large to diff
- buck2/prelude/zip_file/tools/unzip.py too large to diff
- buck2/prelude/zip_file/zip_file.bzl too large to diff
- buck2/prelude/zip_file/zip_file_toolchain.bzl too large to diff
- buck2/run_test.sh too large to diff
- buck2/template/.buckconfig too large to diff
- buck2/template/PACKAGE too large to diff
- buck2/thrift.bzl too large to diff
- buck2/toolchains/BUCK too large to diff
- buck2/toolchains/defaults.bzl too large to diff
- buck2/toolchains/haskell.bzl too large to diff
- buck2/variant.bzl too large to diff
- buck2/version.bzl too large to diff
- cabal-buck2.cabal too large to diff
- changelog.md too large to diff
- src/Distribution/Client/Buck2/Cache.hs too large to diff
- src/Distribution/Client/Buck2/Configure.hs too large to diff
- src/Distribution/Client/Buck2/Fingerprint.hs too large to diff
- src/Distribution/Client/Buck2/Flags.hs too large to diff
- src/Distribution/Client/Buck2/Generate.hs too large to diff
- src/Distribution/Client/Buck2/LocalPackages.hs too large to diff
- src/Distribution/Client/Buck2/Prebuilt.hs too large to diff
- src/Distribution/Client/Buck2/Setup.hs too large to diff
- src/Distribution/Client/Buck2/Spec.hs too large to diff
- src/Distribution/Client/Buck2/Toolchain.hs too large to diff
- src/Distribution/Client/Buck2/Unpack.hs too large to diff
- src/Distribution/Client/Buck2/Write.hs too large to diff
- src/Distribution/Client/CmdBuck2.hs too large to diff
- test/Main.hs too large to diff
- test/fixtures/custom-setup/dep/custom-dep-0.1/Setup.hs too large to diff
- test/fixtures/custom-setup/dep/custom-dep-0.1/custom-dep.cabal too large to diff
- test/fixtures/install-includes/.buckconfig too large to diff
- test/fixtures/install-includes/PACKAGE too large to diff
- test/fixtures/install-includes/buck2/.gitkeep too large to diff
- test/fixtures/install-includes/cabal.project too large to diff
- test/fixtures/install-includes/lib/L.hs too large to diff
- test/fixtures/install-includes/lib/include/inc.h too large to diff
- test/fixtures/install-includes/lib/include/sub/nested.h too large to diff
- test/fixtures/install-includes/lib/include/top.h too large to diff
- test/fixtures/install-includes/lib/lib.cabal too large to diff
- test/fixtures/install-includes/lib/top.h too large to diff
@@ -19,17 +19,9 @@ Then in the root of your project or package: ```-git clone https://github.com/simonmar/haskell-buck2.git buck2 -b <version> cabal buck2 --enable-tests ``` -Where `<version>` is the version of `cabal-buck`,-e.g. `0.2.0.0`. Checking out the branch ensures that you get a-compatible copy of the Buck2 support code. `cabal buck2` checks that-`buck2/` is for its release (the `CABAL_BUCK2_VERSION` in-`buck2/version.bzl`), and so does buck2 when it reads the files that-`cabal buck2` generated, and the error says which branch to switch to.- Then you can use `buck2` as the build tool, e.g. ```@@ -47,7 +39,7 @@ Note that you need to re-run `cabal buck2 --enable-tests` if you modify the `cabal.project` or any of the `.cabal` files. -Not all Cabal features are supported - see [limitations](#limitations).+Most Cabal features are supported but not all - see [limitations](#limitations). # Why? @@ -57,9 +49,9 @@ just using `cabal`? Well, first off let me be clear that you *still need Cabal*, because the Buck2 support doesn't know how to solve package dependencies or build them. So the workflow consists of first-running `cabal buck2` to solve and build the dependencies, but once you've-done that you can switch to `buck2` for building. The idea is that-`buck2` is a more pleasant experience because:+running `cabal buck2` to solve and build the dependencies, but once+you've done that you can switch to `buck2` for building and running+tests. The idea is that `buck2` is a more pleasant experience because: * It's [faster than Cabal, particularly for rebuilds](#performance). @@ -67,20 +59,24 @@ build in `dev` mode (unoptimised with dynamic linking) but adding `-m opt` gives you optimisation and static linking. Note that Cabal doesn't have a purely dynamic build mode: it always uses `-dynamic-too`- for libraries, which has a significant built-time performance cost.+ for libraries, which has a significant build-time performance cost. +* It works a lot better than Cabal when you have non-Haskell code (e.g. C/C++ or Rust) in your project, because+ * Buck2 understands dependencies between C/C++ source files and header files (Cabal doesn't: [issue #4306](https://github.com/haskell/cabal/issues/4306)), so when you modify a C/C++ header the correct things are rebuilt.+ * Buck2 builds C/C++ files in parallel, while Cabal doesn't ([issue #7127](https://github.com/haskell/cabal/issues/7127))++* There is support for using a build cache; see [Sharing build results+ (a build cache)](#sharing-build-results-a-build-cache). A build+ cache means that if you need to quickly create a new worktree to+ work on a new feature or bugfix, for example, the build in the new+ worktree is mostly fetched from the cache instead of being rebuilt.+ * The Buck2 build is extensible. If you have anything that needs to be generated as part of your build, or any non-standard tooling, then hooking that up using Buck2 is far easier than Cabal. Furthermore Buck2 knows how to rebuild things correctly when either the build system or the code generator components change. -* It works a lot better than Cabal when you have non-Haskell code (e.g. C/C++ or Rust) in your project, because- * Buck2 understands dependencies between C/C++ source files and header files (Cabal doesn't: [issue #4306](https://github.com/haskell/cabal/issues/4306)), so when you modify a C/C++ header the correct things are rebuilt.- * Buck2 builds C/C++ files in parallel, while Cabal doesn't ([issue #7127](https://github.com/haskell/cabal/issues/7127))--* You can use [remote execution and caching](https://buck2.build/docs/users/remote_execution/). There is built-in support for using a build cache, see [Sharing build results (a build cache)](#sharing-build-results-a-build-cache) below.- Finally, if you have an existing codebase using Buck2 then this is the basis of something that could "buckify" Cabal packages to integrate into your build system. It needs a bit of work to be suitable for that@@ -91,11 +87,11 @@ # How complete is it? -I've used it to build a few large projects, in particular the Cabal-project itself which consists of about 16 packages and a few hundred-source files. It can also build [Glean](https://glean.software), which-has some complex build requirements including custom codegen, FFI &-hsc2hs.+We've used it to build a few large projects, for instance the Cabal+project itself, the Haskell Language Server, and+[Amazonka](https://github.com/brendanhay/amazonka). It can also+build [Glean](https://glean.software), which has some complex build+requirements including custom codegen, FFI & hsc2hs. There are a few [limitations](#limitations), however. @@ -110,32 +106,45 @@ 2. Generates some files, notably: + * The `buck2/` directory containing the Buck2 support code;++ * `.buckconfig`, containing build-wide configuration options, and+ `PACKAGE`, which sets the default build mode. `cabal buck2` only+ creates these two files if they don't exist, so you can edit+ them;++ * `.buckconfig.local`, if you use a [build+ cache](#sharing-build-results-a-build-cache);+ * `BUCK` and `BUCK.cabal.bzl` in each package, these are the Buck2- build targets+ build targets; * `cabal-buck2/autogen` in each package, this is where we put the files that Cabal autogenerates, such as `cabal_macros.h` and- `Paths_<pkg>.hs`.+ `Paths_<pkg>.hs`; * `cabal-buck2/packages.bzl` in the root of the project, which says- where each of your packages is. Nothing in a package's- `BUCK.cabal.bzl` says where it is or where the packages it depends- on are, so moving a package, or building it as part of a bigger- project, only changes this file. (All the packages have to be in- the one Buck2 cell, the root.)+ where each of your packages is. The `BUCK.cabal.bzl` files don't+ say where any package is, so moving a package, or building it as+ part of a bigger project, only changes this file. (All the+ packages have to be in the one Buck2 cell, the root.) * `third-party/haskell`: tells Buck2 about all the prebuilt package- dependencies, either in the Cabal store or in GHC's package- DB (unless you build the dependencies from source, see below). In here we also record the GHC version you're using, and the- paths to any tool dependencies.+ dependencies, either in GHC's package DB or the Cabal store+ (unless you [build the dependencies from+ source](#building-the-dependencies-with-buck2)). In here we also+ record the GHC version you're using, and the paths to any tool+ dependencies. A component that can't be built with buck2 (e.g. `build-type: Custom`) is an error: `cabal buck2` lists them and aborts, unless you give the `--keep-going` flag in which case it will translate everything it can and warn about the missing components. -# Buck2 quick start+# Using Buck2 +## Quick start+ To build your code: ```@@ -143,20 +152,115 @@ ``` The `//...` is Buck2's syntax for "all targets recursively below the-current directory". You can also build specific target(s), for example+root of the project". You can also build specific target(s), for example `buck2 build cabal-install:cabal` would build the `cabal` target in the `cabal-install` package. For more details see [Target Pattern](https://buck2.build/docs/concepts/target_pattern/) in the Buck2 docs. +To see the targets that a package has, run:++```+buck2 targets //<package>/...+```+ Next you can run your tests: ``` buck2 test //... ``` +## Build modes++The Buck2 build system has the following build mode options, which can+be selected using `-m` on the Buck2 command line (e.g. `-m opt`)++ * Optimisation:+ * `dev`: (default) no optimisation, `-g` for C/C++.+ * `opt`: adds `-O` for Haskell, `-O3 -DNDEBUG` for C/C++, and also enables+ `static` unless overridden by `shared`.+ * Linking:+ * `shared`: (default) shared libraries, dynamic linking+ * `static`: static linking, but also builds shared libraries using+ `-dynamic-too` because those are required for Template Haskell.+ * Profiling:+ * `prof`: enables Haskell profiling; also forces `static`.++To use any of these modes, add them using `-m` on the command line:++```+buck2 build my-package:my-program -m opt+```++# Buck2-specific features in `.cabal`++`cabal buck2` recognises some extra fields in your `.cabal` file which affect how Buck2 builds the package; these are described in the sections below.++## Runtime tool dependencies++Cabal provides a way to indicate build-time tool dependencies with+`build-tool-depends`, but it also treats these as _runtime_ tool dependencies+(i.e. it puts them on the `PATH` for test runs and `cabal run`s of executables).++If we don't distinguish these, then all `build-tool-depends` must be+built in both the build and target configurations, which means they+will be built twice.++For this reason we provide a way to fill in the "missing" Cabal `run-tool-depends` +field (proposed in [haskell/cabal#5411](https://github.com/haskell/cabal/issues/5411)).++This works as follows:++```+test-suite tests+ -- So `cabal test` continues to work.+ build-tool-depends: my-package:my-exe+ -- Not truly needed to _build_ the test-suite...+ x-buck2-ignore-build-tool-depends: my-package:my-exe+ -- Needed when the test suite runs + x-buck2-run-tool-depends: my-package:my-exe+```++If `x-buck2-run-tool-depends` is present, we assume that it is accurate, and +so do not consider `build-tool-depends` to be runtime dependencies. If +`x-buck2-run-tool-depends` is not present, we assume that we have to mimic +Cabal's behaviour, and so `build-tool-depends` will also be considered runtime dependencies.++## Splice dependencies++With [Per-module compilation](#using-per-module-compilation), modules using Template Haskell+can only compile once the libraries that they use are linked.+Cabal's `build-depends` doesn't say which libraries are actually used in TH,+so by default a Template Haskell module has to wait for all of them.++A component can list the libraries whose code its splices run in+`x-buck2-splice-depends`. This fills in a "missing" Cabal field, proposed in+[haskell/cabal#12583](https://github.com/haskell/cabal/issues/12583).++```+library+ build-depends: base, aeson, my-codegen+ -- Only my-codegen's code runs in the splices.+ x-buck2-splice-depends: my-codegen+```++The libraries must also be in `build-depends` so that cabal can link them.++If `x-buck2-splice-depends` is present, we assume that it is+accurate. If the field is not present, we are pessimistic and assume that+a Template Haskell module may use any of the component's libraries.++ # Customising the build +`cabal buck2` sets up the project so that Buck2 will build it exactly as Cabal would. However, it also provides various hooks that let you modify and customise the build, and these hooks are designed to survive re-running `cabal buck2` so you can have permanent Buck2-specific customisations in your project if you want.++## Configuring the build++The `.buckconfig` file has the build-wide configuration settings. Some of these are specific to Haskell targets; see the comments in the file for details. Typically this file will be checked-in and contain options that everyone building the project with Buck2 needs, so to set options for your local build only you can use `.buckconfig.local`. ++## Customising the rules+ `cabal buck2` will generate all the `BUCK` files if they don't exist, but you can also write your own if you want (`cabal buck2` won't overwrite them).@@ -182,8 +286,30 @@ } ``` -Re-run `cabal buck2` after adding or removing `cabal-buck2.bzl`.+`cabal-buck2.bzl` can also give defaults for the generated targets,+for every package (`"*"`) or for one package. Each package's defaults+are keyed by the kind of target (`"library"`, `"executable"`,+`"test-suite"` or `"benchmark"`), or by `"*"` for every kind. For+example, to compile every target of the project module by module: +```+DEFAULTS = {+ # package name or "*" -> kind or "*" -> extra attributes+ "*": {+ "*": {"per_module": True},+ },+}+```++The attributes are merged into the generated ones: lists are appended+to, dicts are merged, and anything else is replaced. The overrides of+a component win over all of the defaults, and the defaults for a+package win over the defaults for every package. See+`cabal_targets()` in `buck2/cabal.bzl` for the details.++Re-run `cabal buck2` after adding or removing `cabal-buck2.bzl`, or+adding or removing its `OVERRIDES` or `DEFAULTS`.+ You can also completely override the generated targets and write a `BUCK` file with your own rules, while still making use of the pre-built dependencies that `cabal buck2` produces. For example, the@@ -227,28 +353,78 @@ You can find docs on how to write `BUCK` files in the Buck2 docs, e.g. [haskell_library](https://buck2.build/docs/prelude/rules/haskell/haskell_library/). -# Build modes+## Modifying the support code under `buck2/` -The Buck2 build system has the following build mode options, which can-be selected using `-m` on the Buck2 command line (e.g. `-m opt`)+If you want to change the support code, or use a version of it that+isn't released yet, you can use a git checkout of the corresponding+branch of [haskell-buck2](https://github.com/simonmar/haskell-buck2)+instead: - * Optimisation:- * `dev`: (default) no optimisation, `-g` for C/C++.- * `opt`: adds `-O` for Haskell, `-O3 -DNDEBUG` for C/C++, and also enables- `static` unless overridden by `shared`.- * Linking:- * `shared`: (default) shared libraries, dynamic linking- * `static`: static linking, but also builds shared libraries using- `-dynamic-too` because those are required for Template Haskell.- * Profiling:- * `prof`: enables Haskell profiling; also forces `static`.+```+git clone https://github.com/simonmar/haskell-buck2.git buck2 -b <version>+``` -To use any of these modes, add them using `-m` on the command line:+Where `<version>` is the version of `cabal-buck2`, e.g. `0.6.0.0`.+`cabal buck2` never replaces a `buck2/` that it didn't create+itself. Instead it checks that `buck2/` is for its release (the+`CABAL_BUCK2_VERSION` in `buck2/version.bzl`), and so does buck2 when+it reads the files that `cabal buck2` generated. If they don't match,+the error says which branch to switch to. +## The compilers++Buck2 builds with the tools that `cabal buck2` found when it last ran, not+with whatever is on the `PATH` of the shell you run `buck2` in. So after+changing your tools (a different GHC, or a different Nix shell), re-run+`cabal buck2`; restarting buck2 isn't needed. (`cabal buck2` puts a symlink to+each of them in `third-party/haskell/toolchain`.)++* GHC is the one that `cabal` uses (`-w` chooses another), and `ghc-pkg`,+ `hsc2hs` and `haddock` are those that `cabal` finds (normally next to+ GHC; use `--with-hsc2hs` and so on choose different ones).+* The C and C++ compilers, for your packages' C and C++ sources, are:+ * the C compiler you give `cabal` for `gcc`, with `--with-gcc`, or in+ `cabal.project` (or `cabal.project.local`):+ ```+ program-locations+ gcc-location: clang+ ```+ and the C++ compiler of the same name next to it (`clang++` for `clang`,+ `g++` for `gcc`, `clang++-18` for `clang-18`...). `cabal` uses the C+ compiler for the C of the packages it builds too.+ * otherwise GHC's, if it has an absolute path for "C compiler+ command" in `ghc --info` (as a GHC built by Nix+ does);+ * otherwise `clang` and `clang++`, linking with `g++`. These are the+ Buck2 toolchain defaults.++# Using per-module compilation++By default Buck2 builds each library and executable using a single `ghc --make`, just as Cabal does. However, it can also compile each module separately which has significant advantages:++* The build can use more parallelism (Buck2 doesn't currently use `--make -j` and it doesn't use GHC's `-jsem`; while it would be easy to support `--make -j` there's no easy way to integrate `-jsem` with Buck2 so each compile would consume a fixed number of cores regardless of how many it actually needed.)+* Module dependencies ignore package boundaries, so a module's compile can begin as soon as the modules it depends on have been built. This can significantly increase the available parallelism beyond what `--make` could do.+* Incremental compiles are typically much faster, because a `--make` compile has to re-read interfaces for the whole library.+* We provide a persistent GHC worker to improve the performance of module-by-module compilation compared with using bare `ghc -c`. This is built automatically by Buck2 and used for per-module compilation unless you say otherwise in `.buckconfig`.++We currently consider per-module compilation as experimental so it has to be enabled explicitly: in your `.buckconfig` add+ ```-buck2 build my-package:my-program -m opt+[haskell]+ compile_granularity = module ``` +to enable per-module compilation for every target. It can also be enabled on a target-by-target basis using `cabal-buck2.bzl`: see [Customising the rules](#customising-the-rules).++The worker is built and used automatically; to disable it, add this to `.buckconfig`:++```+[haskell]+ per_module_worker = none+```++For more details, see [Per-module compilation](https://github.com/simonmar/haskell-buck2/tree/0.6.0.0#per-module-compilation-experimental) in the `haskell-buck2` docs.+ # Sharing build results (a build cache) By default buck2 keeps nothing between runs of its daemon, nor between@@ -263,9 +439,12 @@ cabal buck2 --cache=grpc://127.0.0.1:9092 ``` -`--cache` adds a block to `.buckconfig` (between `# >>> cabal buck2: cache`-and `# <<< cabal buck2: cache <<<`; anything else in the file is left alone),-which later runs keep. `cabal buck2 --no-cache` removes it. **Run+`--cache` adds a block to `.buckconfig.local` (between+`# >>> cabal buck2: cache` and `# <<< cabal buck2: cache <<<`; anything else in+the file is left alone), which later runs keep. `cabal buck2 --no-cache` removes+it. `.buckconfig.local` is for the settings of one checkout and isn't usually+committed (add it to `.gitignore`); a project that wants everyone to use the+same cache can copy the block into `.buckconfig` instead. **Run `buck2 kill` after changing it**: buck2 reads the cache's address when its daemon starts, and a daemon that was already running keeps the old settings. @@ -329,56 +508,128 @@ # Performance -I ran some experiments building the Cabal project itself - 16 packages-and 641 source files (one package, `hackage-security`, is not part of-the project but has to be built locally nonetheless because it depends-on `Cabal-syntax` which *is* part of the project).+We compared cabal and buck2 on three open-source projects: -Buck2 shines when it comes to rebuilds: the dependency graph is cached-in memory, and it knows when build steps can be omitted because the-inputs haven't changed.+* **The [Cabal](https://github.com/haskell/cabal) project** itself+ (without `cabal-testsuite`, which has `build-type: Custom`).+* **[haskell-language-server](https://github.com/haskell/haskell-language-server)**,+ with about 240 library modules in some 35 libraries. It is a chain of+ libraries from `hls-graph` through `ghcide` to `hls-plugin-api`, and+ then a library for each plugin.+* **A subset of [amazonka](https://github.com/brendanhay/amazonka)**+ with about 4,500 modules. It is `amazonka-core`, `amazonka`, the SSO+ and STS services that `amazonka` needs, and five of the largest+ generated services: EC2, SageMaker, QuickSight, S3 and DynamoDB. -+Each project was built in four ways, all without optimisation and with 8+jobs at once: -**Caveats**+* **cabal**: `cabal build`, with GHC's `-jsem` semaphore, so that the+ modules of a package compile in parallel too.+* **buck2, per component**: buck2 compiling each component with one+ `ghc --make`, which is the default.+* **buck2, per module**: buck2 compiling each module in a build step of+ its own, in the persistent worker.+* **cabal repl**: `cabal repl --enable-multi-repl` of the project's+ components, with `:reload` after each edit. A repl loads bytecode and+ links nothing, so it does less work than the other three. It is here+ to show how buck2 compares with an edit-and-reload loop. -* Results tend to be +/- a few seconds from run to run-* I didn't dig into the results in any detail-* It's just one set of data points. Different projects and different choices of edits could give different results. However, I did perform a similar-experiment with the [persistent](https://github.com/yesodweb/persistent)-project, and got similar results.+For each way, the benchmark timed these builds: -## Raw results and details+* **clean**: a build from nothing. For buck2, this doesn't include+ `cabal buck2`, which took about 3 to 15 seconds.+* **noop**: building again with nothing changed.+* **hub-comment**: a comment added to a module that most of the project+ imports. Nothing that imports it should have to compile again.+* **hub-abi**: a new export added to the same module. Everything that+ imports it compiles again.+* **leaf**: a new definition added to a module that nothing imports. -### Clean build+ -* Optimised:- * Default Cabal build: **280s**- * `cabal build all --enable-tests --enable-benchmarks -j`- * Buck2 build (opt mode, including `cabal buck2`): **259s**- * `cabal buck2 --enable-tests --enable-benchmarks && buck2 build //... -m opt`- * Not much difference here, as we expect.+ -* Unoptimised / dynamic:- * Cabal build with -O0 -dynamic: **136s**- * `cabal build all --enable-tests --enable-benchmarks -j --disable-optimisation --enable-executable-dynamic`- * Buck2 build (dev mode, including `cabal buck2`): **78s**- * `cabal buck2 --enable-tests --enable-benchmarks && buck2 build //... -m dev`- * Cabal is using `-dynamic-too` for libraries, while Buck2 is building everything purely dynamic.+ -### Edit + rebuild+What the results show: -Next I made a single edit (added an extension to-`Language.Haskell.Extension`) and rebuilt everything:+* Per-module buck2 is the fastest of the three ways that build+ everything, in every scenario but one. The exception is the Cabal+ project's leaf edit, where both buck2 builds take a fraction of a+ second. Per-module buck2 does best on haskell-language-server,+ whose long chain of libraries is where compiling module by module lets+ a library start before the libraries it depends on are finished.+* amazonka is buck2's worst case. It has a few large packages, and cabal+ already compiles the modules of each package in parallel with `-jsem`.+ Per-module buck2 does about the same work as cabal there, but keeps+ more CPUs busy, so it is ahead by 10-15% on clean and hub-abi.+ Per-component buck2 is slower than cabal on amazonka's clean build,+ because `ghc --make` compiles a component's modules one at a time.+* cabal's noop and hub-comment times on haskell-language-server are+ mostly its fixed cost for each of the project's ~70 components, since+ only one module changes. -* Optimised:- * Cabal: **197s**- * Buck2: **179s**+Details of the measurements: -* Unoptimised / dynamic:- * Cabal: **85s**- * Buck2: **55s**+* They were made on a laptop with an 8-core AMD Ryzen 7 7840U and 60 GB+ of memory, with GHC 9.12.4, cabal-install 3.18.1.0, buck2 2026-10-14+ and an earlier version of the 0.6.0.0 support code. The projects'+ `.cabal` files were patched to use `x-buck2-run-tool-depends` and+ `x-buck2-splice-depends` (see [Customising the+ build](#customising-the-build)) where appropriate.+* The dependencies of each project were built first and shared by all+ the ways, so their build isn't timed.+* The scenarios that take seconds (noop, hub-comment and leaf) ran three+ times, and the charts show the median. clean and hub-abi ran once,+ since they vary by only a few percent from run to run. The exception+ is amazonka's hub-abi, which varied a lot with the laptop's clock speed:+ cabal took between 167s and 246s for the same work. Its cabal and+ per-module times are the mean of two runs of each.+* The repl times for haskell-language-server and the Cabal project come+ from a later run. Five of haskell-language-server's 74 components are+ left out of its repl, because they run an executable of the project as+ a build tool, and a multi-repl can't build that executable while it+ loads the executable's library. +<details>+<summary>The results as tables (wall-clock seconds)</summary>++The Cabal project:++| | cabal | buck2, per component | buck2, per module | cabal repl |+|---|---|---|---|---|+| `cabal buck2` | | 4.5 | 2.7 | |+| clean | 108.6 | 90.9 | 70.0 | 39.7 |+| noop | 2.8 | 0.0 | 0.0 | 0.9 |+| hub-comment | 22.7 | 7.0 | 2.4 | 1.7 |+| hub-abi | 47.3 | 30.5 | 20.2 | 5.7 |+| leaf | 5.9 | 0.2 | 0.3 | 0.9 |++haskell-language-server:++| | cabal | buck2, per component | buck2, per module | cabal repl |+|---|---|---|---|---|+| `cabal buck2` | | 14.9 | 15.2 | |+| clean | 255.4 | 95.3 | 71.3 | 73.5 |+| noop | 16.1 | 0.0 | 0.0 | 3.6 |+| hub-comment | 116.4 | 13.1 | 3.1 | 4.6 |+| hub-abi | 212.8 | 62.9 | 45.6 | 8.0 |+| leaf | 23.0 | 2.8 | 1.1 | 3.5 |++amazonka:++| | cabal | buck2, per component | buck2, per module | cabal repl |+|---|---|---|---|---|+| `cabal buck2` | | 5.7 | 5.6 | |+| clean | 139.5 | 182.2 | 118.0 | 89.6 |+| noop | 3.3 | 0.0 | 0.0 | 1.6 |+| hub-comment | 17.9 | 9.4 | 2.4 | 1.7 |+| hub-abi | 246.0 | 238.6 | 217.5 | 69.7 |+| leaf | 6.9 | 0.5 | 0.4 | 1.6 |++</details>+ # Limitations ## It's an external command, not builtin to `cabal-install`@@ -393,15 +644,6 @@ `cabal-install` library that `cabal-buck2` was built against. Try to make sure they match, or confusion will undoubtedly ensue. -## Builds currently use `--make`--The current Buck2 prelude uses `ghc --make` to build each component-(library, executable). Ideally we should expose the full per-module-dependencies to Buck2 so that it can exploit parallelism across-packages for faster builds/rebuilds. It's entirely possible to do-this, indeed the functionality already exists in [Tweag's Haskell/Buck2-integration](https://github.com/tweag/buck2-haskell).- ## Custom build type Build-type `Custom` isn't supported, and can't be in general, so@@ -477,10 +719,12 @@ # Acknowledgments +Thanks to [Michael Peyton-Lebed](https://github.com/michaelpj) who added support for per-module compilation and the worker, and many other improvements.+ Most of the code and modifications to the standard Buck2 prelude were-developed with the help of Claude Code using Claude Sonnet 5/5.5.+developed with the help of Claude Code. -The Haskell support already in the Buck2 prelude was developed by Meta+The Haskell support in the Buck2 prelude was originally developed by Meta and is in production use internally for building [Glean](https://glean.software). This project just fixes a few things and adds some functionality needed to support building Cabal projects.
@@ -0,0 +1,10 @@+# Shared helpers used by rules in haskell.bzl - kept in their own BUCK+# file (rather than folded into an existing one) since they're not+# specific to any one package, just infrastructure haskell_test() itself+# depends on.++sh_binary(+ name = "run_test",+ main = "run_test.sh",+ visibility = ["PUBLIC"],+)
@@ -0,0 +1,30 @@+Copyright (c) 2026, Simon Marlow++All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above+ copyright notice, this list of conditions and the following+ disclaimer in the documentation and/or other materials provided+ with the distribution.++ * Neither the name of Simon Marlow nor the names of other+ contributors may be used to endorse or promote products derived+ from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,229 @@+# Buck2 prelude for Haskell projects++This is a version of the [Buck2+prelude](https://github.com/facebook/buck2/tree/main/prelude) with a+few tweaks (that will hopefully be upstreamed at some point) and some+support code for building Haskell projects.++You probably don't want this by itself---instead take a look at+[cabal-buck2](https://hackage.haskell.org/package/cabal-buck2) which+extends `cabal` with a `buck2` command so that you can use Buck2 as+the build tool for your Cabal project.++# Build modes++The Buck2 build system has two build modes:++ * `dev`: the default, builds everything with `-O0` and dynamic linking. This is intended to give you the quickest edit-compile-test turnaround.+ * `opt`: enable `-O` and link statically. This takes longer but the code runs faster.++To build with `opt`, use `-m opt`, e.g.++```+buck2 build my-package:my-program -m opt+```++There are other build options that can be selected in a similar way, such as `-m prof` to enable profiling. See `constraints/BUCK` for details.++# Checking without linking++`buck2 build my-package:my-program[interfaces]` compiles a target without+linking it, which is enough to see its type errors.++# Documentation++`haskell_haddock` builds the haddock for libraries libraries. A library compiled +with `-haddock` (in its `compiler_flags` or the toolchain's) will build the documentation +from the interfaces on GHC 9.12+, which is more efficient.++# Warnings++buck2 shows warnings only when it runs a compilation action, and not+when it finds the result in a cache. `buck2 build+my-package:my-program[diagnostics.txt] --out -` prints all the diagnostics +from compiling a target's modules, whether they were compiled in this build or not. ++Only targets compiled with `compile_granularity = "module"` have+`[diagnostics.txt]`. A target compiled with `--make` compiles only the+modules that changed, so its diagnostics would be incomplete, and in no+fixed order.++# Splice dependencies++A Template Haskell splice, quasiquote or `ANN` pragma needs the linked libraries+of dependencies that it uses. A target must list the local dependencies that it uses +in this way in `splice_depends`. The default, an empty list, means that they use none. +A splice that runs code of the target's own modules also uses the libraries that+those modules use, so they must be listed too.++# Per-module compilation (experimental)++By default each `haskell_library()`/`haskell_binary()` is compiled by one+`ghc --make` action. With `compile_granularity = "module"`, each module is+compiled by an action of its own. That means that `buck2` can compile a target's+modules in parallel with everything else it has to do, and rebuilds can+be more minimal. Notably the dependency graph is cross-package, so modules+in later packages can start compiling as soon as the specific modules they+depend on are done, without having to wait for the full package.++To change the default granulariy, set `compile_granularity` in the `[haskell]` +section of the buckconfig. This can still be overridden by each target.++Per-module compilation is only tested on Linux.++The main thing that still leads to suboptimal dependency graphs is Template+Haskell. A module that runs Template Haskell waits for the libraries that+its target lists in `splice_depends` (see above) to be linked.+The target's other modules don't wait for them. A splice that runs code of+a local library that isn't listed fails to compile, saying so. (The+persistent worker doesn't always catch it. See "Known issues" in+`prelude/haskell/tools/worker/README.md`.)++On GHC 9.14, a module that uses `ExplicitLevelImports` narrows its target's+list further, to the dependencies that its `import splice`s come through.++`per_module` is often much faster at rebuilds:++- With `--make`, an edit to any module rebuilds its whole target from+ scratch, and then the targets that depend on it, since even a comment+ changes the target's interfaces.+- With `per_module`, buck2 compiles the edited module, and then only the+ modules whose imports' ABI changed. After a comment, that's just the+ edited module. After a new definition, it's that module and the modules+ that import it.++How much this saves depends on the module structure. It saves the most for+edits low in the module graph, in large targets, or in targets that much+else depends on, and the least for edits to a small target that nothing+depends on. On the worker's bench, rebuilds after such edits took 0.7-1.2s+with `per_module` and the worker, against 2-9s with `--make` per target+(see `prelude/haskell/tools/worker/DESIGN.md`).++The main cost of `per_module` is CPU on clean builds. Without the+persistent worker (below), each module's compile starts a GHC and reads the+interfaces of its imports, which `--make` does once per target, so a clean+build takes several times as long. Rebuilds pay that cost only for the+modules they compile, so they are mostly faster than with `--make` even+without the worker.++The persistent worker in `prelude/haskell/tools/worker` removes most of that cost by+sending the compiles to a long-running process that keeps what it has+read, so a module's imports are read once rather than once per module.+With it, clean builds on the bench were as fast as with a `--make` per+target or faster, and much faster where `--make` per target can't use all+the cores, as in a chain of libraries that each depend on the one before.++`per_module_worker` in the `[haskell]` section of the buckconfig says+whether to use the worker:++- `builtin`, the default: the toolchain builds the worker with the+ project's GHC.+- `none`: no worker.++The worker compiles every module except those that may run one of their+target's build tools, which are compiled by their own `ghc -c`. Those are+the modules that GHC runs a build tool for, such as a preprocessor named+by `-F -pgmF`, and, in a target with build tools, the modules that run+Template Haskell.++The same section has options for the worker that the targets share:++- `per_module_worker_rts_options`: its RTS options (`-A64m -n4m -qn8 -I5`+ by default, see the worker's README).+- `per_module_worker_sessions`: the most sessions it keeps. This bounds its+ memory only with `make` sessions (see the worker's README).+- `per_module_worker_session_mode`: how its sessions compile. `auto` is the+ default, and `make` turns off sharing interfaces between targets (see+ `prelude/haskell/per_module_worker.bzl`).++The recompilation check used by `per_module` is also currently slightly coarser+than GHC's, in that GHC also looks at which definitions from a dependency are+used by a module. We don't do this currently but we could do in future.++With `per_module`, `[interfaces]` (above) doesn't link the target's+dependencies either, because a module's compile needs only the interfaces of+its imports.++# Advice++The rules can spot some ways of declaring a target that+build correctly but slowly, and can report them as advice. +To see what there is to act on, run:++```+cat $(buck2 bxl prelude//haskell/advice.bxl:main -- --targets //...)+```++The report has a section for each check that found something: what the+check looks for and what to do about it, then a line for each target that+it found something in. Checks and targets with nothing to report are left+out. The report is made from the checks' results alone, so any validation+whose result has `findings` gets a section too. For example:++```+haskell_modules_outside_worker (1 target)+ Modules that compile without the persistent worker, which is slower. A module compiles outside it if it may run build tools (tools), or if its splices may read data files (data_dirs). A module that runs Template Haskell (template_haskell) is assumed to run any of its target's build tools.+ root//build-tools:own: BT.Own (runs bt-own); BT.OwnSplice (may run bt-own)++haskell_unused_build_tools (2 targets)+ Build tools that no module's compile runs, though where the target has Template Haskell splices (splices), a splice might. Remove them from build_tool_depends, or, for a program that runs them, move them to run_tool_depends.+ root//build-tools:unused: bt-copy+ root//build-tools:unused-splice: bt-copy (unless a splice runs them)+```++The script builds the targets first if they haven't been built.++For tools, the prelude's `validation/audit_results.bxl` gives the path of+each check's result, a JSON file whose `data` has a list of `findings`, a+`message` that sums them up, and an `explanation` of what the check looks+for and what the findings' fields mean (`buck2 bxl prelude//validation/audit_results.bxl:main --+--targets //...`; `--take NAME` picks out one check). The checks are:++- `haskell_unused_build_tools`: build tools that are not used by any module's + compilation. If the program uses them at runtime, they belong in+ `run_tool_depends`; otherwise they can go.+- `haskell_template_haskell_from_flags`: the target's flags turn on+ `TemplateHaskell` or `QuasiQuotes`, so every module must be compiled as+ if it used Template Haskell.+- `haskell_ann_pragmas`: modules that must be compiled as if they used+ Template Haskell only because of `ANN` pragmas.+- `haskell_modules_outside_worker`: modules which must be compiled outside the+ persistent worker, and an explanation for why.++# Compiler and linker flags from the environment++buck2 runs every build action with a clean environment, so directories that+a shell makes visible to the compiler and linker through variables such as+`LIBRARY_PATH` or `CPATH` (a Nix or Homebrew shell, say) are not seen by GHC.+Give them to the Haskell toolchain through the project's buckconfig instead,+normally in a `.buckconfig.local` next to the `.buckconfig` at the root of+the project (it is read in addition to `.buckconfig`, and is for files that+don't belong in version control):++```+[haskell]+ compiler_flags = -I/opt/homebrew/include+ linker_flags = -L/opt/homebrew/lib -L/opt/zlib/lib+```++Both are space-separated lists of flags for every GHC invocation;+`compiler_flags` go to each compile and `linker_flags` to each link.++# Testing this repo++This is the Buck2 support code for+[cabal-buck2](https://github.com/simonmar/cabal-buck2), which includes it as a+submodule (`buck2/`) and tests it, with an example project (`example/`:+Template Haskell, hsc2hs, C++ via FFI and a Hackage dependency) and with its+own build. Update the submodule there to test a change here.++Some of the rules also have tests of their own, which don't rely+on cabal-buck2 or Hackage: `tests/rules/run.sh GHC_BIN_DIR`, with `buck2` on+`PATH`. See [tests/rules/README.md](tests/rules/README.md).++With Nix, `nix flake check -L` runs those and the persistent worker's tests+(`prelude/haskell/tools/worker`) with each GHC the worker supports, in parallel, and+`nix develop .#ghc9141` (say) gives a shell with that GHC and cabal.++`template/` has the `.buckconfig` and `PACKAGE` that `cabal buck2` copies to a+project that doesn't have them.
@@ -0,0 +1,51 @@+# Rules for running alex and happy.+#+# Unlike hsc2hs, alex/happy don't ship with GHC - they're separate Hackage+# packages. buck2/gen-haskell-prebuilt.py asks Cabal where it put them+# (`cabal list-bin alex`/`happy`) and freezes the answer in+# third-party/haskell/tools.bzl, the same "Cabal identifies/builds it,+# buck2 just references the frozen result" approach third-party/haskell/BUCK+# uses for library packages. Re-run that script to pick up a version bump.++load("@third-party-haskell//:tools.bzl", "ALEX", "ALEX_DATA", "ALEX_DATA_ENV", "ALEX_TARGET", "HAPPY", "HAPPY_DATA", "HAPPY_DATA_ENV", "HAPPY_TARGET")++# Either `tool`, a path to an executable that is installed, or `tool_dep`, an+# executable that buck2 builds (when `cabal buck2 --source-deps` builds the+# dependencies); then `data_dep` is where the tool finds its templates, which+# it is told by an environment variable, `data_env`.+def _run_tool_impl(ctx: AnalysisContext) -> list[Provider]:+ out = ctx.actions.declare_output(ctx.attrs.out)+ tool = ctx.attrs.tool_dep[RunInfo] if ctx.attrs.tool_dep else ctx.attrs.tool+ env = {}+ if ctx.attrs.data_dep:+ env[ctx.attrs.data_env] = ctx.attrs.data_dep[DefaultInfo].default_outputs[0]+ ctx.actions.run(+ cmd_args(tool, ctx.attrs.flags, ctx.attrs.src, "-o", out.as_output()),+ category = ctx.attrs.category,+ env = env,+ )+ return [DefaultInfo(default_output = out)]++_run_tool = rule(+ impl = _run_tool_impl,+ attrs = {+ "category": attrs.string(),+ "data_dep": attrs.option(attrs.dep(), default = None),+ "data_env": attrs.option(attrs.string(), default = None),+ "flags": attrs.list(attrs.string(), default = []),+ "out": attrs.string(),+ "src": attrs.source(),+ "tool": attrs.string(),+ "tool_dep": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ },+)++# What Cabal passes for GHC: generate code that uses GHC's primitives.+_ALEX_FLAGS = ["-g"]+_HAPPY_FLAGS = ["-agc"]++def alex(name, src, out, **kwargs):+ _run_tool(name = name, src = src, out = out, tool = ALEX, tool_dep = ALEX_TARGET, data_dep = ALEX_DATA, data_env = ALEX_DATA_ENV, category = "alex", flags = _ALEX_FLAGS, **kwargs)++def happy(name, src, out, **kwargs):+ _run_tool(name = name, src = src, out = out, tool = HAPPY, tool_dep = HAPPY_TARGET, data_dep = HAPPY_DATA, data_env = HAPPY_DATA_ENV, category = "happy", flags = _HAPPY_FLAGS, **kwargs)
@@ -0,0 +1,748 @@+# Creates the buck2 rules for one Cabal package from a "build spec": a plain+# dict describing the package's components as Cabal sees them, rather than as+# buck2 rules. `cabal buck2` writes the spec (into the package's+# BUCK.cabal.bzl); this file turns it into haskell_library()/haskell_binary()/+# haskell_test() (and, for components with C/C++ sources, cxx_library() and+# external_pkgconfig_library()) targets, so all of the buck2-specific+# decisions - target labels, flag assembly, which wrapper to use - live here+# and can be customised from a BUCK file (see cabal_targets()).+#+# Spec schema. Optional keys are omitted when empty.+#+# {+# "cabal_buck2": str, # the release of cabal-buck2 that wrote this; see version.bzl+# "package": {"name": str, "version": str}, # where it lives: see PACKAGES, below+# "ghc_options": [str], # supplied by the project, not the .cabal file+# "data": {"dir": str, "files": [str]}, # the package's data-dir and data-files (patterns)+# "extra_source_files": [str], # the package's extra-source-files (patterns)+# "components": [+# {+# "kind": "library" | "executable" | "test-suite" | "benchmark",+# "name": str, # also the buck2 target name+# "exe_name": str, # executables only: the file name, if not the target name+# "srcs": {module: src}, # src: package-relative path | {"autogen": name} | {"provided": True}+# "boot_srcs": {module: str}, # the .hs-boot file of each module that has one (package-relative)+# "main_is": src, # not for libraries; module "Main", or C/C++ (see _foreign_main)+# "ghc_options": [str], "cpp_options": [str],+# "language": str, "extensions": [str],+# "extra_libraries": [str],+# "ld_options": [str], # ld-options as configured, so with pkgconfig-depends' other linker flags (-Wl,-rpath, say)+# "extra_lib_dirs": [str], # where to find them: extra-lib-dirs as configured, so with pkgconfig-depends' directories+# "deps": [dep], # see below+# "reexports": [{"module": str, "original": str, "from": dep}], # libraries only; no "from" for a module of the library itself+# "hidden_modules": [str], # libraries only: the modules the package doesn't expose (other-modules)+# "build_tools": [tool], # the tools needed to build it+# "run_tools": [tool], # the tools it needs on PATH when it runs (not for libraries)+# "splice_depends": [dep], # the libraries whose code its splices run, if known (see haskell_library's splice_depends); otherwise all of its deps+# "c_sources": [str], "cc_options": [str],+# "cxx_sources": [str], "cxx_options": [str],+# "cmm_sources": [str],+# "asm_sources": [str], "asm_options": [str],+# "include_dirs": [str], "pkgconfig": [str],+# "hsc_options": [str], # defines for hsc2hs's C compiler (the platform)+# "install_includes": [install_include], # libraries only: the headers that what is compiled against the library sees+# "exposed": bool, # False: the library's package isn't exposed (a library's)+# "generated_include_dirs": [str], # headers that `./configure` generated (relative to the project root)+# "test_args": [str], # test-suites only+# },+# ],+# }+#+# An install_include is {"path": str, "src": str} for a header at that path+# in the library's include directory, whose file in the package is "src".+# One without "src" isn't in the package's sources. It is presumably among+# the headers that `./configure` generated, which what is compiled against+# the library finds in its generated_include_dirs.+#+# A tool is {"exe": str, "package": str} for an executable built by this+# project, or {"exe": str, "external": True} for an installed one.+#+# An "autogen" src names a file generated next to the sources, in the+# package's cabal-buck2/autogen directory. A dep is {"package": str} for a+# package's main library, {"package": str, "library": str} for a named+# sub-library.+#+# The spec says nothing about where packages are: that is in PACKAGES, which+# `cabal buck2` writes for the whole project into cabal-buck2/packages.bzl at+# the project root, and which maps the name of each package that the project+# builds to its directory (relative to the root, "." for the root itself). A+# dependency on one of those is a dependency on a target of this project,+# anything else is a prebuilt package from @third-party-haskell. So a+# package's spec is the same wherever in the project the package is, and in+# whichever project: moving a package only changes packages.bzl. (All of the+# packages are in the root cell.)+#+# DATA_PACKAGES, also in packages.bzl, says which data-files each package+# needs. It maps the name of a package to the packages that have data-files,+# out of that package itself and everything it depends on (directly or+# indirectly) that the project builds. Each of those has a Paths_<pkg> module+# that must be told where its data-files are (see _data_dirs).+#+# A project can customise the generated targets of its packages in a+# cabal-buck2.bzl at its root, rather than in each package's BUCK file. This is+# useful when a package's BUCK file isn't the project's to change (when the+# package is a git submodule, for example). cabal-buck2.bzl can define either+# or both of these, and packages.bzl passes them on:+#+# - OVERRIDES maps the name of a package to the overrides of its components,+# in the form that cabal_targets() takes them.+# - DEFAULTS maps the name of a package, or "*" for every package, to defaults+# for its targets, in the form that cabal_targets() takes them. For example,+# this compiles every target of the project module by module:+#+# DEFAULTS = {"*": {"*": {"compile_granularity": "module"}}}++# This load has to come before the others: they load more from tools.bzl (the+# fingerprints, the alex and happy targets...), which a tools.bzl written by+# another release of cabal-buck2 doesn't have, and then all that buck2 says is+# that a symbol is missing. This one is in every tools.bzl since 0.3.0.0, so+# a tools.bzl from an earlier release fails here, on a symbol that says what+# it is about, and an incompatible one is reported just below.+load("@third-party-haskell//:tools.bzl", TOOLS_CABAL_BUCK2_VERSION = "CABAL_BUCK2_VERSION")+load("//buck2:version.bzl", "CABAL_BUCK2_VERSION")+load("//buck2:cmm.bzl", "cmm_library")+load("//buck2:cxx.bzl", "cxx_binary", "cxx_library")+load("//buck2:headers.bzl", "headers_of", "install_include_dir")+load("//buck2:haskell.bzl", "haskell_binary", "haskell_library", "haskell_test")+load("//buck2:variant.bzl", "variant")+load("//cabal-buck2:packages.bzl", "DATA_PACKAGES", "DEFAULTS", "OVERRIDES", "PACKAGES")+load("@prelude//paths.bzl", "paths")+load("@prelude//third-party:pkgconfig.bzl", "external_pkgconfig_library")++if TOOLS_CABAL_BUCK2_VERSION != CABAL_BUCK2_VERSION:+ fail("\n".join([+ "third-party/haskell was generated by cabal-buck2 {}, but buck2/ is for cabal-buck2 {}.".format(TOOLS_CABAL_BUCK2_VERSION, CABAL_BUCK2_VERSION),+ "Re-run `cabal buck2` with cabal-buck2 {}, or switch buck2/ to the {} branch of".format(CABAL_BUCK2_VERSION, TOOLS_CABAL_BUCK2_VERSION),+ "https://github.com/simonmar/haskell-buck2.",+ ]))++_DEFAULT_RULES = {+ "library": haskell_library,+ "executable": haskell_binary,+ "benchmark": haskell_binary,+ "test-suite": haskell_test,+}++def _nub(xs):+ seen = {}+ out = []+ for x in xs:+ if x not in seen:+ seen[x] = True+ out.append(x)+ return out++def _label(dir, name):+ return "//" + ("" if dir == "." else dir) + ":" + name++def _this_dir(spec):+ # The directory of the package being generated. The BUCK file calling+ # cabal_targets() has to be in it: if it isn't, packages.bzl is out of+ # date (or this BUCK file was copied from elsewhere).+ name = spec["package"]["name"]+ dir = PACKAGES.get(name)+ if dir == None:+ fail("package {} isn't in cabal-buck2/packages.bzl (at the root of the project): re-run `cabal buck2`".format(name))+ here = native.package_name()+ if here != ("" if dir == "." else dir):+ fail("package {} is in {} according to cabal-buck2/packages.bzl, but its BUCK file is in {}: re-run `cabal buck2`".format(name, dir, here or "."))+ return dir++def _third_party_label(name):+ return "third-party-haskell//:" + name++def _src(pkg_dir, src):+ if type(src) == type({}):+ autogen_dir = "cabal-buck2/autogen" if pkg_dir == "." else pkg_dir + "/cabal-buck2/autogen"+ return _label(autogen_dir, src["autogen"])+ return src++def _provided(src):+ return type(src) == type({}) and src.get("provided", False)++# If the Cabal file has `main-is: foo.hs` and `ghc-options: -main-is+# Foo`, then the only way we can know the module of `foo.hs` is by+# groveling around in `ghc-options` looking for `-main-is`.+# This is fragile, but I don't see a better way to do it.+def _main_module(c):+ # Note that we have to support `-main-is Mod`, `-main-is Mod.fn` and+ # `-main-is fn` (the latter is ignored)+ opts = c.get("ghc_options", [])+ for i in range(len(opts) - 1):+ if opts[i] == "-main-is" and opts[i + 1][0].isupper():+ mod, _, last = opts[i + 1].rpartition(".")+ return mod if mod and last[0].islower() else opts[i + 1]+ return "Main"++def _srcs(c, pkg_dir):+ srcs = {}+ if "main_is" in c:+ srcs[_main_module(c)] = _src(pkg_dir, c["main_is"])+ for module, src in c.get("srcs", {}).items():+ if not _provided(src):+ srcs[module] = _src(pkg_dir, src)+ return srcs++def _check_provided(spec, c, srcs):+ # A "provided" module is one that the package's Setup.hs would have+ # generated (`cabal buck2 --enable-custom-setup` doesn't run it), whose+ # source the project gives instead, in the component's overrides.+ missing = [m for m, src in c.get("srcs", {}).items() if _provided(src) and m not in srcs]+ if missing:+ fail("{}: the Setup.hs of package {} would generate {}, but it isn't run (--enable-custom-setup): give their sources in the component's overrides, e.g. overrides = {{\"{}\": {{\"srcs\": {{\"{}\": ...}}}}}}".format(+ c["name"],+ spec["package"]["name"],+ ", ".join(missing),+ c["name"],+ missing[0],+ ))++def _include_flags(c, pkg_dir):+ # The -I flags of the component's include directories (see+ # _include_dirs()), which cabal_targets() made once for the component.+ return c["_include_flags"]++# The files in an include directory that a C preprocessor may include.+_HEADER_PATTERNS = ["**/*.h", "**/*.hh", "**/*.hpp", "**/*.hxx", "**/*.inc"]++def _include_dirs(c, pkg_dir):+ # Returns the -I flags for the component's include directories, and for+ # where a configure script put the headers it generated. GHC needs them+ # for CPP and for the C stubs of foreign imports, and the component's C+ # needs them too. They are only for the component's own compiles. What+ # is compiled against a library sees its install-includes instead (see+ # _install_include_dir()).+ #+ # Each include directory inside the package's directory becomes a+ # filegroup of its headers, and its flag names the filegroup's directory+ # with $(location). So the headers are inputs of every compile that has+ # the flag, and buck2 compiles it again when one of them changes. The+ # compiler also sees only those headers, so a compile that includes a+ # file the filegroup doesn't have fails here, and not only on a remote+ # executor.+ #+ # buck2 can only list the files of a package from its BUCK file, so an+ # include directory elsewhere in the project (`../include`, say) and the+ # directories of generated headers (in the build directory) are named by+ # their paths from the project root, which is where the compilers run.+ # Their headers aren't inputs. A directory outside the project+ # (`/usr/include`, say) is the system's.+ flags = []+ for i, d in enumerate(c.get("include_dirs", [])):+ d = paths.normalize(d)+ if d.startswith("/"):+ flags.append("-I" + d)+ continue+ if d == ".." or d.startswith("../"):+ flags.append("-I" + paths.normalize(paths.join(pkg_dir, d)))+ continue+ prefix = "" if d == "." else d + "/"+ name = "{}-include-{}".format(c["name"], i)+ # The filegroup holds symlinks to the headers, not copies. A compile+ # can reach a header both through the filegroup and by its path in+ # the source tree: a C file includes a header next to it with+ # `#include "foo.h"`, say. A header with `#pragma once` is skipped the+ # second time only if both paths lead to the same file.+ native.filegroup(+ name = name,+ srcs = {f[len(prefix):]: f for f in native.glob([prefix + p for p in _HEADER_PATTERNS])},+ copy = False,+ visibility = ["PUBLIC"],+ )+ flags.append("-I$(location :{})".format(name))+ return _nub(flags + ["-I" + d for d in c.get("generated_include_dirs", [])])++def _install_include_dir(c):+ # Makes the library's include directory as Cabal installs it, with only+ # its install-includes (see install_include_dir()), and returns its+ # label. Returns None for a component without install-includes.+ #+ # The library depends on this target, which exports the directory to+ # what is compiled against the library. So that code sees only the+ # headers that the package installs, as it would see an installed+ # package, and not the package's private headers. The library's own+ # compiles have all of its include directories (see _include_dirs()).+ install = c.get("install_includes", [])+ if not install:+ return None+ name = c["name"] + "-install-include"+ generated = [h for h in install if "src" not in h]+ install_include_dir(+ name = name,+ srcs = {h["path"]: h["src"] for h in install if "src" in h},+ exported_include_dirs = c.get("generated_include_dirs", []) if generated else [],+ visibility = ["PUBLIC"],+ )+ return ":" + name++def _this_unit_id(flags):+ # The unit id that a package's options give its library, as those of a+ # package that GHC knows by its unit id do (rts, ghc-internal).+ unit_id = None+ for i, flag in enumerate(flags):+ if flag == "-this-unit-id" and i + 1 < len(flags):+ unit_id = flags[i + 1]+ return unit_id++def _unit_id(spec, c, name):+ """+ The unit id of the library component `c` (named `name`) in the given+ package spec.++ The unit id is given by a `-this-unit-id` flag if there is one, or+ otherwise the default Cabal unit id:+ <package>-<version>-inplace[-<component>]+ """+ unit_id = _this_unit_id(list(c.get("ghc_options", [])) + list(spec.get("ghc_options", [])))+ if unit_id:+ return unit_id+ package = spec["package"]+ unit_id = package["name"] + ("-" + package["version"] if "version" in package else "") + "-inplace"+ return unit_id if name == package["name"] else unit_id + "-" + name++def cabal_unit_id(spec, name):+ """+ The unit id of the component `name` in the given package `spec`+ """+ c = [c for c in spec["components"] if c["kind"] == "library" and c["name"] == name][0]+ return _unit_id(spec, c, name)++def _lib_dir_flags(c, pkg_dir):+ # Where the linker looks for the component's extra_libraries: its+ # extra-lib-dirs, which Cabal has already extended with the directories+ # of its pkgconfig-depends at configure time. Package-relative, like+ # include_dirs, so made relative to the root of the project the same way.+ dirs = [d if pkg_dir == "." or d.startswith("/") else pkg_dir + "/" + d for d in c.get("extra_lib_dirs", [])]+ return _nub(["-L" + d for d in dirs])++def _ld_flags(c):+ # ld-options are for the linker itself: they reach it from GHC's command+ # line with -optl.+ return _nub(["-optl" + f for f in c.get("ld_options", [])])++def _haskell_flags(c, pkg_dir, project_ghc_options):+ # default-language isn't just documentation: GHC2021/GHC2024 each imply a+ # bundle of extensions, so leaving it out would silently fall back to+ # GHC's own default (Haskell2010). Project-supplied options come last, as+ # in Cabal, so that they can override the component's own.+ own = list(c.get("ghc_options", [])) + list(c.get("cpp_options", []))+ if "language" in c:+ own.append("-X" + c["language"])+ own += ["-X" + e for e in c.get("extensions", [])]+ own += _include_flags(c, pkg_dir)+ return _nub(own) + project_ghc_options++def _linker_flags(c, pkg_dir, project_ghc_options):+ # haskell_binary and haskell_test pass compiler_flags to each module's+ # compile step only, not to the final link, whereas Cabal gives a+ # component's whole ghc-options to every ghc invocation. So anything+ # link-relevant there (-threaded, -rtsopts) has to reach linker_flags+ # too; compile-only flags like -Wall are ignored by ghc when linking.+ own = _lib_dir_flags(c, pkg_dir) + ["-l" + l for l in c.get("extra_libraries", [])] + _ld_flags(c) + list(c.get("ghc_options", []))+ return _nub(own) + project_ghc_options++def _dep_label(d):+ # A dependency's target: a library of this project, or an external+ # package's main library or sub-library.+ if d["package"] in PACKAGES:+ return _label(PACKAGES[d["package"]], d.get("library", d["package"]))+ if "library" in d:+ # Libraries of different packages have the same names.+ return _third_party_label(d["package"] + "--" + d["library"])+ return _third_party_label(d["package"])++def _classify_deps(deps):+ # `packages` only ever resolves an external package's main library;+ # everything else (local libraries, external sub-libraries) is a target+ # label in `deps`.+ packages = []+ local = []+ external_sublibs = []+ for d in deps:+ if d["package"] in PACKAGES:+ local.append(_dep_label(d))+ elif "library" in d:+ external_sublibs.append(_dep_label(d))+ else:+ packages.append(d["package"])+ return _nub(packages), _nub(local + external_sublibs)++def _build_tool_depends(build_tools):+ # Each tool becomes a real dependency that is put on PATH for this rule's+ # compile actions and, for a test-suite, when the test runs.+ labels = []+ for t in build_tools:+ if "package" in t:+ labels.append(_label(PACKAGES[t["package"]], t["exe"]))+ else:+ labels.append(_third_party_label(t["exe"] + "-exe"))+ return _nub(labels)++def _pkgconfig_deps(c, pkgconfig_seen):+ # The targets of the component's pkgconfig-depends, created by the first+ # component of the package that has them.+ pkgconfig = _nub(c.get("pkgconfig", []))+ for p in pkgconfig:+ if p not in pkgconfig_seen:+ pkgconfig_seen[p] = True+ external_pkgconfig_library(name = "pkgconfig-" + p, package = p, visibility = ["PUBLIC"])+ return [":pkgconfig-" + p for p in pkgconfig]++def _cxx_kwargs(c, pkgconfig_seen, srcs):+ # The attributes of a C/C++ rule that compiles `srcs` with the+ # component's options.+ pkgconfig = _pkgconfig_deps(c, pkgconfig_seen)++ kwargs = {"srcs": srcs, "visibility": ["PUBLIC"]}++ # cc-options are for C and assembler (which GHC also gets the C compiler+ # to preprocess), cxx-options for C++.+ cc_options = _nub(c.get("cc_options", []))+ lang_flags = {+ "assembler_with_cpp": cc_options + _nub(c.get("asm_options", [])),+ "c": cc_options,+ "cxx": _nub(c.get("cxx_options", [])),+ }+ kwargs["lang_compiler_flags"] = {lang: flags for lang, flags in lang_flags.items() if flags}++ kwargs["deps"] = pkgconfig++ return kwargs++_PROFILING_DEFINES = select({+ "root//buck2/constraints:prof": ["-DPROFILING"],+ "DEFAULT": [],+})++# To match GHC, we explicitly disable PIC for C compiles (except on+# MacOS and Windows), in case gcc has it enabled by default. See GHC's+# picCCOpts. When linking dynamically, the later -fPIC will override+# this.+_NO_PIC = select({+ "config//os:macos": [],+ "config//os:windows": [],+ "DEFAULT": ["-fno-PIC"],+})++def _cxx_library(c, pkg_dir, pkgconfig_seen):+ # Returns the labels the Haskell rule must additionally depend on.+ srcs = list(c.get("c_sources", [])) + list(c.get("cxx_sources", [])) + list(c.get("asm_sources", []))+ if not srcs:+ return []+ kwargs = _cxx_kwargs(c, pkgconfig_seen, srcs)+ name = c["name"] + "-cxx"++ # The C of a Haskell component is compiled as GHC would compile it,+ # which includes its version header (defining __GLASGOW_HASKELL__) and+ # makes available its own headers (HsFFI.h) and those of the packages+ # the component depends on (HsUnixConfig.h, say), and defines PROFILING+ # when it is profiled.+ kwargs["compiler_flags"] = ["-include", "ghcversion.h"] + _PROFILING_DEFINES + _NO_PIC+ packages, labels = _classify_deps(c.get("deps", []))+ headers = name + "-headers"+ headers_of(name = headers, deps = _nub([_third_party_label(p) for p in ["rts"] + packages] + labels))+ kwargs["deps"] = [":" + headers] + kwargs["deps"]++ # The component's include directories are for its own C. What depends on+ # a library sees its install-includes.+ include_flags = _include_flags(c, pkg_dir)+ if include_flags:+ kwargs["preprocessor_flags"] = include_flags+ # Like the C of a Cabal package, it is all part of the library of the+ # component's Haskell code (see `internal_deps` of haskell_library()):+ # the RTS's C, say, calls hidden functions of its Cmm, which only resolve+ # within one shared library.+ kwargs["preferred_linkage"] = "static"+ kwargs["link_whole"] = True+ kwargs["use_archive"] = False+ cxx_library(name = name, **kwargs)+ return [":" + name]++# The extensions by which Cabal recognises a C or C++ main-is.+_FOREIGN_MAIN_EXTENSIONS = [".c", ".cpp", ".cxx", ".c++"]++def _foreign_main(c):+ main = c.get("main_is")+ return type(main) == type("") and paths.split_extension(main)[1] in _FOREIGN_MAIN_EXTENSIONS++def _cxx_binary(c, pkg_dir, pkgconfig_seen, overrides):+ # A component whose main-is is C/C++ (as some of GHC's own tools are) is+ # built as a plain C/C++ program. Cabal would compile it with GHC, which+ # makes GHC's headers and those of the component's Haskell dependencies+ # available, and link it with GHC, which links in the RTS. Neither is of+ # any use to a program without Haskell code in it (which isn't supported+ # here), so its dependencies on external Haskell packages (base, say)+ # are ignored.+ unsupported = []+ if c["kind"] not in ("executable", "benchmark"):+ unsupported.append("a " + c["kind"])+ if c.get("srcs"):+ unsupported.append("Haskell modules")+ if c.get("cmm_sources"):+ unsupported.append("Cmm sources")+ _, local_deps = _classify_deps(c.get("deps", []))+ if local_deps:+ unsupported.append("dependencies on Haskell libraries")+ if unsupported:+ fail("{}: a C/C++ main-is ({}) is only supported in an executable without {}".format(+ c["name"],+ c["main_is"],+ " or ".join(unsupported),+ ))+ srcs = [c["main_is"]] + list(c.get("c_sources", [])) + list(c.get("cxx_sources", [])) + list(c.get("asm_sources", []))+ kwargs = _cxx_kwargs(c, pkgconfig_seen, srcs)+ kwargs["name"] = c["name"]+ if "exe_name" in c:+ kwargs["executable_name"] = c["exe_name"]+ include_flags = _include_flags(c, pkg_dir)+ if include_flags:+ kwargs["preprocessor_flags"] = include_flags+ linker_flags = _lib_dir_flags(c, pkg_dir) + ["-l" + l for l in c.get("extra_libraries", [])] + c.get("ld_options", [])+ if linker_flags:+ kwargs["linker_flags"] = _nub(linker_flags)+ cxx_binary(**_merge(kwargs, overrides))++def _cmm_library(c, spec):+ # GHC compiles Cmm, given the component's options as for Haskell.+ if not c.get("cmm_sources"):+ return []+ pkg_dir = _this_dir(spec)+ name = c["name"] + "-cmm"+ cmm_library(+ name = name,+ srcs = list(c["cmm_sources"]),+ flags = _haskell_flags(c, pkg_dir, list(spec.get("ghc_options", []))),+ visibility = ["PUBLIC"],+ )+ return [":" + name]++def _profiled(label):+ # `label` (a target of this package) built for profiling.+ name = label.removeprefix(":") + "-prof"+ variant(name = name, actual = label, transition = "root//buck2/constraints:to-prof", visibility = ["PUBLIC"])+ return ":" + name++def _data_dirs(c, spec):+ # The data_dirs of a component: for each package whose data-files its code+ # may read, the <pkg>_datadir environment variable that the package's+ # Paths_<pkg> module looks at, mapped to the package's -data target. This+ # is what `cabal build` and `cabal run` do too.+ #+ # Only packages that the project builds are included. A prebuilt package+ # from the store has its data-files installed where its Paths_<pkg> module+ # already expects to find them.+ #+ # The data-files of the component's build tools (alex and happy read their+ # templates this way) are included too. The compile runs a build tool's+ # binary directly, not through the wrapper script that a haskell_binary+ # with data_dirs gets for `buck2 run`, so the compile has to set the tool's+ # variables itself.+ packages = DATA_PACKAGES.get(spec["package"]["name"], [])+ for tool in c.get("build_tools", []):+ if "package" in tool:+ packages = packages + DATA_PACKAGES.get(tool["package"], [])+ return {p.replace("-", "_") + "_datadir": _label(PACKAGES[p], p + "-data") for p in packages}++def _haskell_kwargs(c, spec, helpers):+ # `helpers` are the rules of the component's C/C++/Cmm code.+ pkg_dir = _this_dir(spec)+ project_ghc_options = list(spec.get("ghc_options", []))+ kind = c["kind"]+ packages, deps = _classify_deps(c.get("deps", []))+ kwargs = {+ "name": c["name"],+ "srcs": _srcs(c, pkg_dir),+ "boot_srcs": dict(c.get("boot_srcs", {})),+ "cabal_component": (pkg_dir, c["name"]),+ }+ if "exe_name" in c:+ kwargs["exe_name"] = c["exe_name"]+ data_dirs = _data_dirs(c, spec)+ if data_dirs:+ kwargs["data_dirs"] = data_dirs+ if kind == "test-suite":+ kwargs["cwd"] = pkg_dir+ if c.get("test_args"):+ kwargs["test_args"] = list(c["test_args"])+ compiler_flags = _haskell_flags(c, pkg_dir, project_ghc_options)+ hsc_flags = ["--cflag=" + f for f in c.get("hsc_options", []) + c.get("cc_options", []) + _include_flags(c, pkg_dir)]+ if hsc_flags:+ kwargs["hsc_flags"] = hsc_flags++ # hsc2hs compiles C, as in Cabal, unless there is C++ in the component.+ kwargs["hsc_cxx"] = bool(c.get("cxx_sources") or c.get("cxx_options"))+ if compiler_flags:+ kwargs["compiler_flags"] = compiler_flags+ if kind == "library":+ kwargs["package_name"] = spec["package"]["name"]+ if "version" in spec["package"]:+ kwargs["package_version"] = spec["package"]["version"]+ kwargs["unit_id"] = _unit_id(spec, c, c["name"])+ # The code of the helpers is part of the library, as in Cabal, which+ # compiles it for each way: for the profiled library, as built for+ # profiling.+ if helpers:+ kwargs["internal_deps"] = helpers+ kwargs["prof_internal_deps"] = [_profiled(h) for h in helpers]+ kwargs["exposed"] = c.get("exposed", True)+ if c.get("hidden_modules"):+ kwargs["hidden_modules"] = list(c["hidden_modules"])+ if c.get("_install_include_dir"):+ deps = deps + [c["_install_include_dir"]]+ if c.get("reexports"):+ kwargs["reexported_modules"] = {r["module"]: (_dep_label(r["from"]) if "from" in r else None, r["original"]) for r in c["reexports"]}+ lib_dirs = _lib_dir_flags(c, pkg_dir)+ # Raw flags: the link of whatever depends on the library hands these+ # to the linker itself (as -optl) already.+ exported = _nub(lib_dirs + ["-l" + l for l in c.get("extra_libraries", [])] + c.get("ld_options", []))+ if exported:+ kwargs["exported_linker_flags"] = exported+ # The library's own shared object must link against them too, not+ # only whatever finally links the library in: GHC loads the .so to+ # run Template Haskell splices in dependents, and that fails on any+ # symbol it leaves unresolved. (ld_options reach GHC's command line+ # with -optl here, unlike the raw flags that dependents are given.)+ own_link = lib_dirs + ["-l" + l for l in c.get("extra_libraries", [])] + _ld_flags(c)+ if own_link:+ kwargs["linker_flags"] = _nub(own_link)+ else:+ deps = deps + helpers+ linker_flags = _linker_flags(c, pkg_dir, project_ghc_options)+ if linker_flags:+ kwargs["linker_flags"] = linker_flags+ if packages:+ kwargs["packages"] = packages+ if deps:+ kwargs["deps"] = deps+ build_tool_depends = _build_tool_depends(c.get("build_tools", []))+ if build_tool_depends:+ kwargs["build_tool_depends"] = build_tool_depends++ run_tool_depends = _build_tool_depends(c.get("run_tools", []))+ if run_tool_depends:+ kwargs["run_tool_depends"] = run_tool_depends++ # Cabal lets a component's splices run code from any of its+ # build-depends. So if the spec doesn't give the list, every dependency+ # is listed. A list in the spec, even an empty one, is used as it is.+ th_deps = c["splice_depends"] if "splice_depends" in c else c.get("deps", [])+ kwargs["splice_depends"] = [_dep_label(d) for d in th_deps]+ if kind != "test-suite":+ kwargs["visibility"] = ["PUBLIC"]+ return kwargs++_LIST_TYPES = (type([]), type(select({"DEFAULT": []})))++def _merge(base, extra):+ # Lists (or selects of them) are appended to, dicts are merged, anything+ # else is replaced.+ out = dict(base)+ for k, v in extra.items():+ cur = out.get(k)+ if type(v) in _LIST_TYPES and type(cur) in _LIST_TYPES:+ out[k] = cur + v+ elif type(v) == type({}) and type(cur) == type({}):+ merged = dict(cur)+ merged.update(v)+ out[k] = merged+ else:+ out[k] = v+ return out++def cabal_targets(spec, defaults = {}, overrides = {}, transform = None, rules = {}):+ """Create the targets described by a build spec.++ Args:+ spec: the package's build spec (see the top of this file).+ defaults: extra attributes for every target of a kind, keyed by kind+ ("library", "executable", "test-suite", "benchmark"), or "*" for all+ of them. The project's own defaults (DEFAULTS["*"] and+ DEFAULTS[package] in its cabal-buck2.bzl, if it has one) come+ before these.+ overrides: extra attributes for individual components, keyed by+ component name. The project's own overrides of the package's+ components (OVERRIDES[package] in its cabal-buck2.bzl, if it has+ one) come before these.+ transform: if given, called as transform(kind, component, attrs) with+ each target's final attributes (the Haskell rule's, not the C/C+++ helper's), and returns the attributes to use instead - or None to+ not create the target at all.+ rules: replacement rule functions to call instead of the defaults,+ keyed by kind.++ Extra attributes are merged into the generated ones: lists are appended+ to, dicts merged, anything else replaced. Later sources win. The order is:+ the project's defaults for every package, then its defaults for this+ package, then `defaults`, then the project's overrides of the component,+ then `overrides`, then transform. Within each set of defaults, those for+ "*" come before those for the kind.+ An executable whose main-is is C/C++ is a cxx_binary() (see+ _cxx_binary()), to which only its overrides apply: defaults, transform+ and rules are for the Haskell rules.+ """+ generated_by = spec.get("cabal_buck2")+ if generated_by != CABAL_BUCK2_VERSION:+ generator = "cabal-buck2 " + generated_by if generated_by else "an earlier release of cabal-buck2 (0.1.0.0)"+ fail("\n".join([+ "This was generated by {}, but buck2/ is for cabal-buck2 {}.".format(generator, CABAL_BUCK2_VERSION),+ "Re-run `cabal buck2` with cabal-buck2 {}, or switch buck2/ to the {} branch of".format(CABAL_BUCK2_VERSION, generated_by or "0.1.0.0"),+ "https://github.com/simonmar/haskell-buck2.",+ ]))+ pkg_dir = _this_dir(spec)+ project_overrides = OVERRIDES.get(spec["package"]["name"], {})+ all_defaults = [DEFAULTS.get("*", {}), DEFAULTS.get(spec["package"]["name"], {}), defaults]+ pkgconfig_seen = {}+ for c in spec["components"]:+ c = dict(c, _include_flags = _include_dirs(c, pkg_dir), _install_include_dir = _install_include_dir(c))+ if _foreign_main(c):+ _cxx_binary(c, pkg_dir, pkgconfig_seen, _merge(project_overrides.get(c["name"], {}), overrides.get(c["name"], {})))+ continue+ kind = c["kind"]+ helpers = _cxx_library(c, pkg_dir, pkgconfig_seen) + _cmm_library(c, spec)+ kwargs = _haskell_kwargs(c, spec, helpers)++ # The helpers' own dependencies are linked with the component's.+ kwargs["deps"] = kwargs.get("deps", []) + _pkgconfig_deps(c, pkgconfig_seen)+ for d in all_defaults:+ kwargs = _merge(kwargs, d.get("*", {}))+ kwargs = _merge(kwargs, d.get(kind, {}))+ kwargs = _merge(kwargs, project_overrides.get(c["name"], {}))+ kwargs = _merge(kwargs, overrides.get(c["name"], {}))+ if transform:+ kwargs = transform(kind, c, kwargs)+ if kwargs == None:+ continue+ _check_provided(spec, c, kwargs.get("srcs", {}))+ rules.get(kind, _DEFAULT_RULES[kind])(**kwargs)+ _data_files(spec, pkg_dir)+ _extra_source_files(spec)++def _data_files(spec, pkg_dir):+ # A target <package>-data for the package's data-files: a directory laid+ # out like the package's data-dir, so that a file is at the same relative+ # path as in the package's source. The package's code finds the directory+ # through its <package>_datadir environment variable, whether it reads the+ # files at build time or when it runs (see _data_dirs).+ data = spec.get("data")+ if not data:+ return+ prefix = "" if data["dir"] in ("", ".") else data["dir"].rstrip("/") + "/"+ files = native.glob([prefix + pattern for pattern in data["files"]])+ native.filegroup(+ name = spec["package"]["name"] + "-data",+ srcs = {f[len(prefix):]: f for f in files},+ visibility = ["PUBLIC"],+ )++def _extra_source_files(spec):+ # The package's extra-source-files, as a directory laid out like the+ # package, for whatever else in the project needs them: a generator of+ # its sources, say.+ patterns = spec.get("extra_source_files")+ if not patterns:+ return+ native.filegroup(+ name = spec["package"]["name"] + "-extra-source-files",+ srcs = native.glob(patterns),+ visibility = ["PUBLIC"],+ )
@@ -0,0 +1,67 @@+# A PACKAGE file (unlike a BUCK/.bzl file) can only contain a flat+# sequence of top-level calls - no `if`/`def` allowed directly in it+# ("if cannot be used outside def", then "def is not allowed in this+# dialect" once wrapped - both confirmed directly). The conditional logic+# hsthrift/PACKAGE needs (call set_cfg_constructor() only when this+# checkout is genuinely standalone - see that file's own comment) has to+# live in a real .bzl file instead, called as a single top-level+# statement from the PACKAGE file itself.+#+# set_cfg_modifiers() itself can't be wrapped the same way, though -+# unlike set_cfg_constructor() (a builtin, no such restriction), it's a+# plain prelude .bzl function that inspects its *immediate* caller's own+# module path (_is_buck_tree_file(), buck2/prelude/cfg/modifier/+# set_cfg_modifiers.bzl) and requires it to literally end in "/PACKAGE" -+# confirmed directly (its own docstring claims "or a bzl file+# transitively loaded by a PACKAGE file" is also fine, but that isn't+# what the check actually does). Calling it from inside this file's own+# cfg_constructor_if_standalone() - one frame removed from PACKAGE -+# fails that check even though PACKAGE is what ultimately triggered it.+# So PACKAGE has to call set_cfg_modifiers() itself, directly - the+# standalone-or-not decision instead has to be *returned* from a helper+# here (dev_modifiers_if_standalone(), below) rather than guarding the+# call itself.+load(+ "@prelude//cfg/modifier/cfg_constructor.bzl",+ "cfg_constructor_post_constraint_analysis",+ "cfg_constructor_pre_constraint_analysis",+)+load("@prelude//cfg/modifier/common.bzl", "MODIFIER_METADATA_KEY")++def cfg_constructor_if_standalone():+ # get_base_path() gives the directory of *this* PACKAGE file, relative+ # to the root - "" when this is the project's own root PACKAGE file+ # (genuinely standalone), or e.g. "hsthrift" when this checkout is a+ # subdirectory of another project.+ if get_base_path() != "":+ return++ set_cfg_constructor(+ stage0 = cfg_constructor_pre_constraint_analysis,+ stage1 = cfg_constructor_post_constraint_analysis,+ key = MODIFIER_METADATA_KEY,+ aliases = struct(+ dev = "root//buck2/constraints:dev",+ opt = "root//buck2/constraints:opt",+ prof = "root//buck2/constraints:prof",+ static = "root//buck2/constraints:static",+ shared = "root//buck2/constraints:shared",+ all_ways = "root//buck2/constraints:all_ways",+ ),+ extra_data = struct(),+ )++# `dev` is the default build mode when no -m flag is given, and `clang`+# is defaulted on too (see the root PACKAGE file's own comment - every+# machine building this project today lands on clang via+# system_cxx_toolchain()'s $PATH auto-detection, so this is just always+# true rather than a per-environment override) - but only when standalone+# (same reasoning as cfg_constructor_if_standalone() above); when nested,+# an empty list is the no-op equivalent of "don't call this at all",+# since set_cfg_modifiers() itself has no comparable once-per-project+# restriction (it's package-scoped, not project-wide) - unlike+# set_cfg_constructor(), calling it with `[]` when nested is harmless.+def dev_modifiers_if_standalone():+ if get_base_path() != "":+ return []+ return ["root//buck2/constraints:dev", "root//buck2/constraints:clang"]
@@ -0,0 +1,142 @@+# Compiling Cmm (the `cmm-sources` of a Cabal component) into a library that+# Haskell libraries can depend on.+#+# GHC compiles .cmm files itself, so this runs it on each of them, once for+# each kind of object that a link needs: ordinary ones for static linking and+# position-independent ones for shared libraries (dynamic ones, in GHC's+# terms). The library is the objects themselves, to be linked (all of them)+# into the library of the component's Haskell code, as in Cabal: see+# `internal_deps` of haskell_library().++load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")+load("@prelude//cxx:preprocessor.bzl", "cxx_inherited_preprocessor_infos", "cxx_merge_cpreprocessors")+load("@prelude//haskell:library_info.bzl", "HaskellLibraryInfoTSet")+load("@prelude//haskell:link_info.bzl", "HaskellLinkInfo")+load(+ "@prelude//linking:link_info.bzl",+ "LibOutputStyle",+ "LinkInfo",+ "LinkInfos",+ "LinkStyle",+ "ObjectsLinkable",+ "create_merged_link_info",+)+load("@prelude//linking:types.bzl", "Linkage")+load("@prelude//linking:linkable_graph.bzl", "create_linkable_graph", "create_linkable_graph_node", "create_linkable_node")+load("@prelude//linking:shared_libraries.bzl", "EMPTY_SHARED_LIBRARY_INFO")+load("@prelude//decls/toolchains_common.bzl", "toolchains_common")+load("@prelude//haskell:toolchain.bzl", "HaskellToolchainInfo")+load("@third-party-haskell//:tools.bzl", "CC_FINGERPRINT", "GHC_FINGERPRINT")++def _package_db_args(ctx: AnalysisContext, link_style: LinkStyle) -> cmd_args:+ # The package databases of the Haskell libraries among the deps, and of+ # their own dependencies. GHC needs them because it reads the platform+ # constants from the rts package. If a library isn't built in this link+ # style (it is only built shared, say), its packages for another style+ # are used instead, since they have the same rts.+ children = []+ for dep in ctx.attrs.deps:+ info = dep.get(HaskellLinkInfo)+ if info:+ infos = info.prof_info if ctx.attrs.profiling else info.info+ children.append(infos[link_style] if link_style in infos else infos.values()[0])+ libs = list(ctx.actions.tset(HaskellLibraryInfoTSet, children = children).traverse())+ dbs = {lib.db: None for lib in libs}+ return cmd_args([cmd_args("-package-db", db) for db in dbs])++def _cmm_library_impl(ctx: AnalysisContext) -> list[Provider]:+ ghc = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]+ linker_type = get_cxx_toolchain_info(ctx).linker_info.type+ pre = cxx_merge_cpreprocessors(ctx.actions, [], cxx_inherited_preprocessor_infos(ctx.attrs.deps))+ pre_args = cmd_args(pre.set.project_as_args("args"), format = "-optCmmP={}")+ link_infos = {}+ for output_style, link_style, flags in (+ (LibOutputStyle("archive"), LinkStyle("static"), []),+ (LibOutputStyle("pic_archive"), LinkStyle("shared"), ["-dynamic", "-fPIC"]),+ ):+ variant = link_style.value+ package_db_args = _package_db_args(ctx, link_style)+ objects = []+ for entry in ctx.attrs.srcs:+ src, src_flags = entry if type(entry) == type(()) else (entry, [])+ obj = ctx.actions.declare_output(variant, src.short_path + ".o")+ cmd = cmd_args(+ ghc.compiler,+ ghc.compiler_flags,+ ["-prof"] if ctx.attrs.profiling else [],+ flags,+ ctx.attrs.flags,+ package_db_args,+ pre_args,+ src_flags,+ "-c",+ src,+ "-o",+ obj.as_output(),+ )++ # The fingerprints are not read: they make the GHC installation and+ # the C toolchain part of the action's cache key (see toolchains/BUCK).+ ctx.actions.run(+ cmd,+ category = "ghc_cmm",+ identifier = variant + "/" + src.short_path,+ env = {"CABAL_BUCK2_GHC": GHC_FINGERPRINT, "CABAL_BUCK2_CC": CC_FINGERPRINT},+ )+ objects.append(obj)++ # The Cmm code is only reached from Haskell code, by symbol, so every+ # object has to be kept.+ link_infos[output_style] = LinkInfos(default = LinkInfo(+ name = ctx.label.name,+ linkables = [ObjectsLinkable(objects = objects, linker_type = linker_type, link_whole = True)],+ ))++ return [+ DefaultInfo(),+ create_merged_link_info(ctx, get_cxx_toolchain_info(ctx).pic_behavior, link_infos, preferred_linkage = Linkage("static")),+ EMPTY_SHARED_LIBRARY_INFO,+ create_linkable_graph(+ ctx,+ node = create_linkable_graph_node(+ ctx,+ linkable_node = create_linkable_node(+ ctx = ctx,+ default_soname = None,+ preferred_linkage = Linkage("static"),+ link_infos = link_infos,+ ),+ ),+ ),+ ]++_cmm_library = rule(+ impl = _cmm_library_impl,+ attrs = {+ "deps": attrs.list(attrs.dep(), default = []),+ "flags": attrs.list(attrs.arg(), default = []),+ "labels": attrs.list(attrs.string(), default = []),+ "profiling": attrs.bool(default = False),+ "srcs": attrs.list(attrs.one_of(attrs.source(), attrs.tuple(attrs.source(), attrs.list(attrs.arg())))),+ "_cxx_toolchain": toolchains_common.cxx(),+ "_haskell_toolchain": toolchains_common.haskell(),+ },+)++_PROFILING = select({+ "root//buck2/constraints:prof": True,+ "DEFAULT": False,+})++def cmm_library(name, srcs, flags = [], deps = [], **kwargs):+ """A library of Cmm code, to depend on from haskell_library() (as one+ of its `internal_deps`).++ Args:+ name: the target name.+ srcs: the .cmm files, each alone or paired with flags of its own.+ flags: options for GHC when it compiles them.+ deps: the libraries whose headers they include: C libraries, and the+ Haskell libraries of the packages the code depends on.+ """+ _cmm_library(name = name, srcs = srcs, flags = flags, deps = deps, profiling = _PROFILING, **kwargs)
@@ -0,0 +1,126 @@+load("@prelude//transitions:utils.bzl", "transition_utils")++# Build configuration. These options are normally set on the command+# line via -m, e.g.+#+# buck2 build //some/target -m buck2//constraint:asan+#+# Aliases for constraints can be configured in the PACKAGE file.+# Checking configuration settings is done using select().++# build_mode: selects between+# - dev (the default; faster rebuild, more runtime checks, slower execution)+# - opt (slower rebuild, fewer runtime checks, faster execution)+#+# Usually these are aliased to simply dev/opt, so you can say+#+# buck2 build //some/target -m opt+#+# to build with optimisation.+constraint_setting(+ name = "build_mode",+ visibility = ["PUBLIC"],+)++# build_mode dev: typically+# - no optimisation+# - assertions enabled+# - debug logging enabled+# - shared libraries for faster linking+constraint_value(+ name = "dev",+ constraint_setting = ":build_mode",+ visibility = ["PUBLIC"],+)++# build_mode opt: typically+# - full optimisation+# - assertions disabled+# - debug logging disabled+# - static linking+constraint_value(+ name = "opt",+ constraint_setting = ":build_mode",+ visibility = ["PUBLIC"],+)++# Enable address sanitiser (-fsanitize=address) for C/C++ code+constraint_setting(+ name = "sanitizer",+ visibility = ["PUBLIC"],+)++constraint_value(+ name = "asan",+ constraint_setting = ":sanitizer",+ visibility = ["PUBLIC"],+)++# The C compiler flavour, used to select flags+constraint_setting(+ name = "compiler",+ visibility = ["PUBLIC"],+)++constraint_value(+ name = "clang",+ constraint_setting = ":compiler",+ visibility = ["PUBLIC"],+)++# Enable Haskell profiling. Requires all the Cabal package+# dependencies to be built for profiling too.+constraint_setting(+ name = "profiling",+ visibility = ["PUBLIC"],+)++constraint_value(+ name = "prof",+ constraint_setting = ":profiling",+ visibility = ["PUBLIC"],+)++# To profiling (for the C and Cmm of a profiled library, say).+transition_utils.modify_constraints_transition(+ name = "to-prof",+ add = [":prof"],+ visibility = ["PUBLIC"],+)++# linking: how executables are linked against their Haskell libraries, when+# it isn't the build mode's default (shared for dev, static for opt and prof).+# Profiling can't be linked shared.+constraint_setting(+ name = "linking",+ visibility = ["PUBLIC"],+)++constraint_value(+ name = "static",+ constraint_setting = ":linking",+ visibility = ["PUBLIC"],+)++constraint_value(+ name = "shared",+ constraint_setting = ":linking",+ visibility = ["PUBLIC"],+)++# libraries: with all_ways, libraries are built both static and shared,+# whatever the linking of executables. This can be used when building+# libraries to be installed. A library that is built both ways is compiled+# once, with -dynamic-too. Profiled libraries don't need a constraint,+# because a library's profiled variants are built whenever something asks+# for them.+constraint_setting(+ name = "libraries",+ visibility = ["PUBLIC"],+)++constraint_value(+ name = "all_ways",+ constraint_setting = ":libraries",+ visibility = ["PUBLIC"],+)
@@ -0,0 +1,54 @@+_ASAN_CXX_FLAGS = select({+ "root//buck2/constraints:asan": ["-fsanitize=address"],+ "DEFAULT": [],+})++_BUILD_MODE_CXX_FLAGS = select({+ "root//buck2/constraints:opt": select({+ "root//buck2/constraints:asan": ["-g"],+ "DEFAULT": ["-O3", "-DNDEBUG"],+ }),+ "DEFAULT": ["-g"],+})++# Whether actions upload their results to the remote action cache, if there+# is one, when they say nothing about it (see `cabal buck2 --cache`).+_DEFAULT_ALLOW_CACHE_UPLOAD = read_root_config("buck2", "default_allow_cache_upload", "false").lower() == "true"++_COMMON_CXX_FLAGS = ["-fno-omit-frame-pointer"] + _ASAN_CXX_FLAGS + _BUILD_MODE_CXX_FLAGS++# The languages of lang_compiler_flags (by their sources' kind).+_LANGUAGES = ["c", "cxx", "objc", "objcxx", "assembler_with_cpp", "cuda", "hip", "asm_with_cpp"]++def _lang_compiler_flags(lang_compiler_flags):+ # The build mode's flags come first, so that a target's own win (-Og, or+ # -fomit-frame-pointer, say): its lang_compiler_flags (a Cabal package's+ # cc-options), and then its compiler_flags.+ flags = dict(lang_compiler_flags)+ for lang in _LANGUAGES:+ flags[lang] = _COMMON_CXX_FLAGS + flags.get(lang, [])+ return flags++def cxx_library(name, lang_compiler_flags = {}, linker_flags = [], **kwargs):+ # A library's shared-library link doesn't leave uploading to+ # `buck2.default_allow_cache_upload` either, but uploads only if the target+ # says so. Its result depends on the system linker and libraries, which+ # buck2 doesn't track, but with a cache the C toolchain's fingerprint is+ # part of the link's command, and so of its key (see `_run_info` in+ # prelude/toolchains/cxx.bzl).+ kwargs.setdefault("allow_cache_upload", _DEFAULT_ALLOW_CACHE_UPLOAD)+ native.cxx_library(+ name = name,+ lang_compiler_flags = _lang_compiler_flags(lang_compiler_flags),+ # -fsanitize=address has to reach the *linker* too+ linker_flags = _ASAN_CXX_FLAGS + linker_flags,+ **kwargs+ )++def cxx_binary(name, lang_compiler_flags = {}, linker_flags = [], **kwargs):+ native.cxx_binary(+ name = name,+ lang_compiler_flags = _lang_compiler_flags(lang_compiler_flags),+ linker_flags = _ASAN_CXX_FLAGS + linker_flags,+ **kwargs+ )
@@ -0,0 +1,249 @@+# Wrappers around the native haskell_library()/haskell_binary() rules, and+# a haskell_test() rule.+#+# These handle:+# - build modes: e.g. `-m opt` selects optimisation + static linking+# - package deps: `packages = ["text", ...]` instead of explicit+# `"@third-party-haskell//:text"` entries in `deps`.+# - a standard set of packages (rts) added to every target. A target can+# give its own set with `auto_packages`.+# - hsc2hs: any `.hsc` file in `srcs` is automatically preprocessed, with+# include paths derived from `deps` (see buck2/hsc2hs.bzl) - so a `.hsc`+# file that needs a C++ dependency's headers just needs that dependency+# listed in `deps`, same as any other buck2 target.+# - alex/happy: any `.x`/`.y`/`.ly` file in `srcs` is automatically run through+# the corresponding tool (see buck2/alex_happy.bzl).+# - boot files: `boot_srcs = {module: file}` gives the .hs-boot file of each+# module (of `srcs`, by module name) that has one. That of a generated+# module (from a .hsc/.x/.y file) is put next to the generated source,+# which is where GHC looks for it.+# - support for build rules generated from Cabal packages:+# - `cabal_component = (pkg, component)` causes this component's+# `cabal_macros.h` file to be included when `{-# LANGUAGE CPP #-}`+# is on.++load("//buck2:alex_happy.bzl", "alex", "happy")+load("//buck2:hsc2hs.bzl", "hsc2hs")+load("@prelude//paths.bzl", "paths")++# Packages implicitly needed by every Haskell target.+AUTO_PACKAGES = ["rts"]++def _package_deps(packages, auto_packages):+ all_pkgs = {p: None for p in (auto_packages + packages)}+ return [("@third-party-haskell//:" + p) for p in sorted(all_pkgs.keys())]++def _cabal_macros_include_flags(cabal_component):+ if cabal_component == None:+ return []+ pkg, component = cabal_component+ autogen_dir = "cabal-buck2/autogen" if pkg == "." else pkg + "/cabal-buck2/autogen"+ label = "//" + autogen_dir + ":" + component + "-cabal-macros"+ return ["-optP-include", "-optP$(location " + label + ")"]++def _cabal_macros_hsc_flags(cabal_component):+ # hsc2hs wants the package's macros too (MIN_VERSION_base, say).+ flags = _cabal_macros_include_flags(cabal_component)+ return ["--cflag=-include", "--cflag=" + flags[1][len("-optP"):]] if flags else []++# Link style for executables: the linking constraint's (static or shared), or+# else dynamic, but static for opt, and for prof, which must be static: GHC+# doesn't support prof/dynamic.+_BUILD_MODE_LINK_STYLE = select({+ "root//buck2/constraints:static": "static",+ "root//buck2/constraints:shared": "shared",+ "DEFAULT": select({+ "root//buck2/constraints:prof": "static",+ "DEFAULT": select({+ "root//buck2/constraints:opt": "static",+ "DEFAULT": "shared",+ }),+ }),+})++# Compiler flags are passed in this order: mode flags, target-specific flags+# The principle is that more specific flags should be able to override less+# specific, so the build-wide flags come first.+_BUILD_MODE_HASKELL_FLAGS = select({+ "root//buck2/constraints:opt": ["-O"],+ "DEFAULT": [],+})++# Libraries are built shared when executables are linked shared, and static+# and shared otherwise (Template Haskell needs a library shared, for a GHC+# that is itself linked shared). With all_ways, libraries are built both+# static and shared, whatever the linking of executables.+#+# Profiling doesn't change this. A library always has profiled variants,+# which are only built when a profiled link or compile asks for them.+_BUILD_MODE_PREFERRED_LINKAGE = select({+ "root//buck2/constraints:all_ways": "any",+ "DEFAULT": select({+ "root//buck2/constraints:static": "any",+ "root//buck2/constraints:shared": "shared",+ "DEFAULT": select({+ "root//buck2/constraints:opt": "any",+ "DEFAULT": "shared",+ }),+ }),+})++_PROF_ENABLED = select({+ "root//buck2/constraints:prof": True,+ "DEFAULT": False,+})++# Linker flags enabled when building with ASAN+_ASAN_LINKER_FLAGS = select({+ "root//buck2/constraints:asan": ["-optc-fsanitize=address", "-optl-fsanitize=address"],+ "DEFAULT": [],+})++def hs_module_path(path):+ for ext in (".hsc", ".x", ".y", ".ly"):+ if path.endswith(ext):+ return path[:-len(ext)] + ".hs"+ return path++def _resolve_src(name, src, deps, hsc_flags, hsc_cxx, common):+ out = paths.replace_extension(src, ".hs")+ if src.endswith(".hsc"):+ rule_name = name + "-hsc-" + out.replace("/", "_")+ hsc2hs(name = rule_name, hsc_file = src, out = out, deps = deps, extra_flags = hsc_flags, cxx = hsc_cxx, **common)+ return ":" + rule_name+ elif src.endswith(".x"):+ rule_name = name + "-alex-" + out.replace("/", "_")+ alex(name = rule_name, src = src, out = out, **common)+ return ":" + rule_name+ elif src.endswith(".y") or src.endswith(".ly"):+ rule_name = name + "-happy-" + out.replace("/", "_")+ happy(name = rule_name, src = src, out = out, **common)+ return ":" + rule_name+ else:+ return src++def _with_boot_impl(ctx: AnalysisContext) -> list[Provider]:+ boot_path = paths.split_extension(ctx.attrs.path)[0] + paths.split_extension(ctx.attrs.boot.short_path)[1]+ srcs = ctx.actions.symlinked_dir("srcs", {ctx.attrs.path: ctx.attrs.src, boot_path: ctx.attrs.boot}, has_content_based_path = False)+ return [DefaultInfo(sub_targets = {+ "boot": [DefaultInfo(default_output = srcs.project(boot_path))],+ "src": [DefaultInfo(default_output = srcs.project(ctx.attrs.path))],+ })]++# A generated source of a module (`path` is where it would be in the package),+# with the module's boot file next to it, which is where GHC looks for it.+_with_boot = rule(+ impl = _with_boot_impl,+ attrs = {+ "boot": attrs.source(),+ "path": attrs.string(),+ "src": attrs.source(),+ },+)++def _resolve_srcs(name, srcs, boot_srcs, deps, hsc_flags, hsc_cxx, kwargs):+ # The rules that preprocess sources are compatible with the same+ # configurations as the rule whose sources they are.+ common = {"target_compatible_with": kwargs["target_compatible_with"]} if "target_compatible_with" in kwargs else {}+ if type(srcs) != type({}):+ if boot_srcs:+ fail("{}: boot_srcs needs srcs to be a dict, by module name".format(name))+ return [ _resolve_src(name, src, deps, hsc_flags, hsc_cxx, common) for src in srcs ]+ unknown = [modl for modl in boot_srcs if modl not in srcs]+ if unknown:+ fail("{}: boot_srcs for modules not in srcs: {}".format(name, ", ".join(unknown)))+ resolved = {}+ for modl, src in srcs.items():+ resolved_src = _resolve_src(name, src, deps, hsc_flags, hsc_cxx, common)+ boot = boot_srcs.get(modl)+ if boot == None:+ resolved[modl] = resolved_src+ elif resolved_src == src:+ resolved[modl] = src+ resolved[modl + "-boot"] = boot+ else:+ rule_name = name + "-boot-" + modl+ _with_boot(name = rule_name, src = resolved_src, boot = boot, path = paths.replace_extension(src, ".hs"), **common)+ resolved[modl] = ":" + rule_name + "[src]"+ resolved[modl + "-boot"] = ":" + rule_name + "[boot]"+ return resolved++def haskell_library(+ name,+ srcs = [],+ packages = [],+ deps = [],+ compiler_flags = [],+ hsc_flags = [],+ hsc_cxx = True,+ cabal_component = None,+ boot_srcs = {},+ auto_packages = AUTO_PACKAGES,+ internal_deps = [],+ **kwargs):+ all_deps = deps + _package_deps(packages, auto_packages)+ kwargs.setdefault("preferred_linkage", _BUILD_MODE_PREFERRED_LINKAGE)+ native.haskell_library(+ name = name,+ srcs = _resolve_srcs(name, srcs, boot_srcs, all_deps + internal_deps, hsc_flags + _cabal_macros_hsc_flags(cabal_component), hsc_cxx, kwargs),+ compiler_flags = _BUILD_MODE_HASKELL_FLAGS + compiler_flags + _cabal_macros_include_flags(cabal_component),+ deps = all_deps,+ internal_deps = internal_deps,+ **kwargs+ )++def haskell_binary(+ name,+ srcs = [],+ packages = [],+ deps = [],+ compiler_flags = [],+ hsc_flags = [],+ hsc_cxx = True,+ linker_flags = [],+ cabal_component = None, # see haskell_library()+ boot_srcs = {}, # see haskell_library()+ auto_packages = AUTO_PACKAGES, # see haskell_library()+ **kwargs):+ all_deps = deps + _package_deps(packages, auto_packages)+ kwargs.setdefault("link_style", _BUILD_MODE_LINK_STYLE)+ kwargs.setdefault("enable_profiling", _PROF_ENABLED)+ native.haskell_binary(+ name = name,+ srcs = _resolve_srcs(name, srcs, boot_srcs, all_deps, hsc_flags + _cabal_macros_hsc_flags(cabal_component), hsc_cxx, kwargs),+ compiler_flags = _BUILD_MODE_HASKELL_FLAGS + compiler_flags + _ASAN_LINKER_FLAGS + _cabal_macros_include_flags(cabal_component),+ deps = all_deps,+ linker_flags = _ASAN_LINKER_FLAGS + linker_flags,+ **kwargs+ )++# `labels` are the test's rather than its binary's, so that `buck2 test+# --exclude <label>` can leave a test out.+def haskell_test(name, test_args = [], test_env = {}, cwd = None, labels = [], **kwargs):+ bin = name + "-bin"+ haskell_binary(name = bin, **kwargs)+ test_target = ":" + bin+ args = test_args++ # This doesn't need to put the test's tools on PATH. The binary's RunInfo+ # already does that for its run_tool_depends.+ if cwd != None:+ test_target = "//buck2:run_test"+ args = [cwd, "$(exe_target :" + bin + ")"] + test_args++ native.sh_test(+ name = name,+ test = test_target,+ args = args,+ env = {"LANG": "C.UTF-8"} | test_env,+ # `LANG` defaults to a UTF-8 locale: unlike `buck2 run` (which+ # inherits the caller's shell environment, `LANG` included),+ # `buck2 test` runs actions in a sanitized environment with no+ # `LANG` at all - so GHC's `hGetContents`/`readFile` fall back+ # to the POSIX/ASCII encoding and choke on any non-ASCII byte+ # in a test fixture.+ labels = labels,+ )+++
@@ -0,0 +1,48 @@+# The headers of other targets, without their libraries: for C code that+# GHC would have given the include directories of the packages it depends on.+# Depending on the packages themselves would link them in as well, and in a+# profiling build, with the wrong libraries.++load("@prelude//cxx:preprocessor.bzl", "CPreprocessor", "CPreprocessorArgs", "cxx_inherited_preprocessor_infos", "cxx_merge_cpreprocessors")++def _headers_of_impl(ctx: AnalysisContext) -> list[Provider]:+ return [+ DefaultInfo(),+ cxx_merge_cpreprocessors(ctx.actions, [], cxx_inherited_preprocessor_infos(ctx.attrs.deps)),+ ]++headers_of = rule(+ impl = _headers_of_impl,+ attrs = {"deps": attrs.list(attrs.dep(), default = [])},+)++# A library's include directory as Cabal installs it, with each of its+# install-includes at its path in the directory. `srcs` maps those paths to+# the files of the package.+#+# What is compiled against the library sees the directory, through the+# preprocessor flags that this target exports, and also sees+# `exported_include_dirs`. Those are directories that the build doesn't+# track, such as the one where the package's configure script generated+# headers.+#+# The directory holds symlinks to the headers, not copies. A compile can+# reach a header both through this directory and by another path: the+# library's own C, say, includes a header next to it by its path in the+# source tree. A header with `#pragma once` is skipped the second time only+# if both paths lead to the same file.+def _install_include_dir_impl(ctx: AnalysisContext) -> list[Provider]:+ include = ctx.actions.symlinked_dir("include", ctx.attrs.srcs)+ flags = [cmd_args(include, format = "-I{}")] + ["-I" + d for d in ctx.attrs.exported_include_dirs]+ return [+ DefaultInfo(default_output = include),+ cxx_merge_cpreprocessors(ctx.actions, [CPreprocessor(args = CPreprocessorArgs(args = flags))], []),+ ]++install_include_dir = rule(+ impl = _install_include_dir_impl,+ attrs = {+ "exported_include_dirs": attrs.list(attrs.string(), default = []),+ "srcs": attrs.dict(attrs.string(), attrs.source(), default = {}),+ },+)
@@ -0,0 +1,71 @@+# A rule for running hsc2hs.+#+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")+load("@prelude//cxx:preprocessor.bzl", "cxx_inherited_preprocessor_infos", "cxx_merge_cpreprocessors")+load("@prelude//decls/toolchains_common.bzl", "toolchains_common")+load("@prelude//haskell:toolchain.bzl", "HaskellToolchainInfo")+load("@third-party-haskell//:tools.bzl", "CC_FINGERPRINT", "GHC_FINGERPRINT")++def _hsc2hs_include_args(pp_info):+ return [+ cmd_args(pp_info.set.project_as_args("include_dirs"), format = "--cflag={}"),+ cmd_args(pp_info.set.project_as_args("args"), format = "--cflag={}"),+ ]++def _hsc2hs_impl(ctx: AnalysisContext) -> list[Provider]:+ out = ctx.actions.declare_output(ctx.attrs.out)++ pp_infos = cxx_inherited_preprocessor_infos(ctx.attrs.deps)+ merged = cxx_merge_cpreprocessors(ctx.actions, [], pp_infos)++ hsc2hs_tool = ctx.attrs._haskell_toolchain[HaskellToolchainInfo].hsc2hs++ # C++, unless told otherwise: some of the .hsc files need the headers of+ # C++ code. A package that is only C (Cabal's way) must not be compiled as+ # C++, which doesn't accept what hsc2hs generates for #alignment.+ cxx_toolchain = get_cxx_toolchain_info(ctx)+ compiler_info = cxx_toolchain.cxx_compiler_info if ctx.attrs.cxx else cxx_toolchain.c_compiler_info+ compiler = compiler_info.compiler++ # hsc2hs wants a single program, but the compiler is a command (with the+ # cache, it is `env` setting a fingerprint, then the compiler).+ cc, cc_hidden = ctx.actions.write("cc.sh", ["#!/bin/sh", cmd_args("exec", compiler, '"$@"', delimiter = " ")], is_executable = True, allow_args = True)++ cmd = cmd_args(+ hsc2hs_tool,+ cmd_args("--cc=", cmd_args(cc, hidden = cc_hidden), delimiter = ""),+ # The project's flags for the language (see default_toolchains()).+ cmd_args(compiler_info.compiler_flags, format = "--cflag={}"),+ "-C",+ "-D__HSC2HS__=1",+ ctx.attrs.extra_flags,+ # The hsc file's own package dir, so `#include "foo.h"`/`<foo.h>`+ # against a local (non-exported) header resolves, same as it would+ # when compiling a sibling cxx_library() source in this package.+ "-I" + ("." if ctx.label.package == "" else ctx.label.package),+ _hsc2hs_include_args(merged),+ "-o",+ out.as_output(),+ ctx.attrs.hsc_file,+ )+ # The fingerprints are not read by hsc2hs: they make the GHC installation+ # and the C toolchain part of the action's cache key (see toolchains/BUCK).+ ctx.actions.run(cmd, category = "hsc2hs", env = {"CABAL_BUCK2_GHC": GHC_FINGERPRINT, "CABAL_BUCK2_CC": CC_FINGERPRINT})++ return [DefaultInfo(default_output = out)]++# Runs hsc2hs on `hsc_file`, producing `out`. `deps` is used purely to+# collect C/C++ include paths (via CPreprocessorInfo); it doesn't need to be+# (and usually isn't) the same as the consuming haskell_library()'s deps.+hsc2hs = rule(+ impl = _hsc2hs_impl,+ attrs = {+ "cxx": attrs.bool(default = True),+ "deps": attrs.list(attrs.dep(), default = []),+ "extra_flags": attrs.list(attrs.arg(), default = []),+ "hsc_file": attrs.source(),+ "out": attrs.string(),+ "_cxx_toolchain": toolchains_common.cxx(),+ "_haskell_toolchain": toolchains_common.haskell(),+ },+)
@@ -0,0 +1,44 @@+# Discovers this system's LLVM/Clang installation via `llvm-config-+# <version>`, the same way `buck2/prelude/third-party/pkgconfig.bzl`'s+# external_pkgconfig_library() discovers a pkg-config-described system+# library: a couple of genrule()s shelling out to the real tool at build+# time (its output describes *this machine's* install - absolute paths+# under e.g. /usr/lib/llvm-15 - not something safe to bake into checked-+# in BUCK text or share across machines via remote execution, same+# reasoning pkgconfig.bzl's own comment gives for `remote = False`+# there), wrapped in a prebuilt_cxx_library() so a consumer just adds it+# to its own `deps` like any other library, instead of hand-rolling+# `-I`/`-L`/`-l` flags itself.+#+# llvm-config's own `--cxxflags` bundles its include path and defines+# together with `-std=c++14 -fno-exceptions` - dropped here by keeping+# only the `-I`/`-D` tokens from that output, not passed through whole+# (see glean/lang/clang/BUCK's own comment on why: that package's+# sources need >= C++17 and don't build with exceptions disabled, so+# whatever it links against can't be pinned to llvm-config's own+# defaults for those two).+def external_llvm_config_library(name, version, visibility = ["PUBLIC"]):+ llvm_config = "llvm-config-{}".format(version)++ cflags = name + "__llvm_config_cflags"+ native.genrule(+ name = cflags,+ out = "out",+ cmd = "{ll} --cxxflags | tr ' ' '\\n' | grep -E '^-[ID]' | tr '\\n' ' ' > $OUT".format(ll = llvm_config),+ remote = False,+ )++ libs = name + "__llvm_config_libs"+ native.genrule(+ name = libs,+ out = "out",+ cmd = "{ll} --ldflags > $OUT; {ll} --libs >> $OUT; {ll} --system-libs >> $OUT".format(ll = llvm_config),+ remote = False,+ )++ native.prebuilt_cxx_library(+ name = name,+ visibility = visibility,+ exported_preprocessor_flags = ["@$(location :{})".format(cflags)],+ exported_linker_flags = ["@$(location :{})".format(libs)],+ )
@@ -0,0 +1,103 @@+load(":defs.bzl", "execution_platform_with_constraints", "execution_platforms")++# Any exec_dep/`$(exe ...)` edge (a build-time tool dependency) gets+# reconfigured to match whichever execution platform is chosen for it,+# straight from that platform's own `constraint_values` - it does *not*+# go through the project's root PACKAGE-level `set_cfg_modifiers()` at+# all, since that machinery only drives ordinary target-platform+# configuration. `prelude//platforms:default` (the vendored prelude+# target every exec_dep falls back to unless it specifically requires+# `:opt` below) carries none of this project's own constraint values, so+# without a project-specific default platform of our own, every such+# edge - and everything it transitively pulls in, e.g. clang-index,+# hie-indexer, or any Haskell tool linking against glean/rts,+# glean/rocksdb, hsthrift's folly-clib, ... - silently fell back to the+# DEFAULT (GCC-flavored) arm of buck2/cxx.bzl's `_COROUTINES_FLAGS`+# select and re-added `-fcoroutines` to those specific exec-configured+# copies. Invisible on a dev machine with a newer clang that tolerates+# the unrecognised flag, but a hard `clang: error: unknown argument:+# '-fcoroutines'` on CI's older clang. Confirmed by diffing+# `.cpp.target_cxx_args` across configurations: building+# `root//glean/rts:rts` by its own label (plain target-platform+# resolution, no exec_dep edge involved) came out clean, but the *same*+# target reappeared with `-fcoroutines` under a second, exec-configured+# configuration as soon as anything reached it via an exec_dep edge -+# i.e. the full `//glean/...` CI invocation, not a single-target build -+# and adding `clang` to `:exec-opt` alone (the first fix attempted here)+# didn't fully clear it, because most of those edges resolve to the+# *plain* default execution platform, not `:exec-opt` specifically.+#+# So `:exec-default` exists purely to be "prelude//platforms:default+# plus this project's own clang constraint value, plus `dev`" - the+# actual default every exec_dep edge without a further requirement+# resolves to. `dev` here isn't load-bearing for the coroutines fix+# above (absence of `opt`/`prof` already falls through to the same+# `DEFAULT` arm every `_BUILD_MODE_*` select in buck2/{cxx,haskell}.bzl+# uses for "dev") - it's here so a select() that ever checks *for*+# `root//buck2/constraints:dev` positively, rather than treating its+# absence as the dev case, still gets a real match under this platform+# too, rather than depending on coincidence. `:exec-opt` is then+# derived from *this*, not the raw prelude target, so it inherits+# `clang` too instead of needing its own copy of the same reasoning.+execution_platform_with_constraints(+ name = "exec-default",+ base = "prelude//platforms:default",+ constraint_values = [+ "root//buck2/constraints:clang",+ "root//buck2/constraints:dev",+ ],+ visibility = ["PUBLIC"],+)++# A second execution platform, identical to `:exec-default` except its+# configuration also carries the `opt` build-mode constraint value+# instead of `dev` (see `defs.bzl`'s `execution_platform_with_+# constraints()` - constraint_values passed here for the `build_mode`+# constraint_setting *replace* whatever `base` already had for that+# same setting, not add to it, so this doesn't end up with both `dev`+# and `opt` set at once) - see buck2.md's entry on forcing `opt` for+# build-time codegen tools. Listed second in `.buckconfig`'s `[build]+# execution_platforms`, so it's only selected for targets that+# explicitly opt in via `exec_compatible_with` requiring+# `root//buck2/constraints:opt` (currently: hsthrift//compiler:+# thrift-compiler, //glean/schema/gen:gen-schema, //glean/bytecode:+# gen-bytecode-hs - unconditionally, they always want to run fast+# regardless of the ambient build mode - and, via buck2/haskell.bzl's+# `_BUILD_MODE_EXEC_COMPATIBLE_WITH`, every haskell_binary()/+# haskell_test() *only when the ambient build mode is itself `opt`* -+# see that file's own comment for why a plain, unconditional+# `exec_compatible_with` requirement on clang-index/hie-indexer's own+# targets wouldn't have worked here). Every other exec_dep/`$(exe ...)`+# edge in the build has no such requirement, so it stays compatible+# with, and keeps resolving to, `:exec-default`.+#+# `root//buck2/constraints:opt`, not a bare `//buck2/constraints:opt` -+# this needs to be the exact same constraint *value* the project's own+# dev/opt PACKAGE-level cfg modifier (`root//PACKAGE`) attaches to the+# *target* configuration, so a `select()` written the usual way (keyed on+# `root//buck2/constraints:opt`, e.g. buck2/haskell.bzl's `_BUILD_MODE_*`)+# resolves the same "opt" arm here as it would under a plain `-m opt`+# build - "root" is a cell alias, not a literal cell name, so this+# resolves correctly both nested inside another project and when this+# checkout is standalone (see hsthrift/PACKAGE's own comment on the same+# convention).+execution_platform_with_constraints(+ name = "exec-opt",+ base = ":exec-default",+ constraint_values = ["root//buck2/constraints:opt"],+ visibility = ["PUBLIC"],+)++# The actual target `.buckconfig`'s `[build] execution_platforms` points+# at - see defs.bzl's own comment on why this indirection is needed+# (that buckconfig key takes one target, not a list). Order matters:+# `:exec-default` first, so anything with no `exec_compatible_with`+# requirement (almost everything) keeps resolving to it.+execution_platforms(+ name = "exec",+ platforms = [+ ":exec-default",+ ":exec-opt",+ ],+ visibility = ["PUBLIC"],+)
@@ -0,0 +1,97 @@+# A tiny wrapper rule that takes an existing execution platform (`base`)+# and produces a new one identical to it except for extra constraint+# values merged into its configuration. Used to derive `:exec-opt` from+# `prelude//platforms:default` below, without having to reimplement that+# rule's own executor_config (remote-exec settings, path separators,+# etc.) - we just read it back off `base` and reuse it verbatim, so this+# stays correct even if that vendored rule's own executor_config logic+# ever changes.+load("@prelude//cfg/exec_platform:marker.bzl", "get_exec_platform_marker")+load("@prelude//haskell:per_module_worker.bzl", "has_per_module_worker")++# The execution platform's executor config. Without a cache or persistent+# workers, it is the base platform's config. With either, every action runs+# locally, and nothing runs remotely. With `cache`, the actions' results are+# looked up in, and uploaded to, a remote action cache (the one that+# `[buck2_re_client]` in the buckconfig points to). With+# `persistent_workers`, an action that names a persistent worker may run in+# that worker.+def _executor_config(base: ExecutionPlatformInfo, cache: bool, persistent_workers: bool):+ if not cache and not persistent_workers:+ return base.executor_config+ return CommandExecutorConfig(+ local_enabled = True,+ remote_enabled = False,+ remote_cache_enabled = cache,+ allow_cache_uploads = cache,+ # Look up the per-module compiles by their dep files too (see Note+ # [Early cut-off by dep files] in prelude/haskell/compile_per_module.bzl).+ remote_dep_file_cache_enabled = cache,+ use_persistent_workers = persistent_workers,+ )++def _execution_platform_with_constraints_impl(ctx: AnalysisContext) -> list[Provider]:+ base = ctx.attrs.base[ExecutionPlatformInfo]+ constraints = dict(base.configuration.constraints)+ for constraint_value in ctx.attrs.constraint_values:+ info = constraint_value[ConstraintValueInfo]+ constraints[info.setting.label] = info++ cfg = ConfigurationInfo(constraints = constraints, values = {})+ name = ctx.label.raw_target()+ platform = ExecutionPlatformInfo(+ label = name,+ configuration = cfg,+ executor_config = _executor_config(base, ctx.attrs.cache, ctx.attrs.persistent_workers),+ )++ return [+ DefaultInfo(),+ platform,+ PlatformInfo(label = str(name), configuration = cfg),+ ExecutionPlatformRegistrationInfo(+ platforms = [platform],+ exec_marker_constraint = get_exec_platform_marker(),+ ),+ ]++execution_platform_with_constraints = rule(+ impl = _execution_platform_with_constraints_impl,+ attrs = {+ "base": attrs.dep(providers = [ExecutionPlatformInfo]),+ "constraint_values": attrs.list(attrs.dep(providers = [ConstraintValueInfo]), default = []),+ # `[cabal_buck2] cache = true` in the buckconfig (.buckconfig.local,+ # where `cabal buck2 --cache=ADDRESS` writes it together with the+ # remote cache's address).+ "cache": attrs.bool(default = read_root_config("cabal_buck2", "cache", "false") == "true"),+ # Whether actions may run in persistent workers. This is on when the+ # buckconfig sets up a worker for the per-module compiles (see+ # prelude/haskell/per_module_worker.bzl).+ "persistent_workers": attrs.bool(default = has_per_module_worker()),+ },+)++# `.buckconfig`'s `[build] execution_platforms` takes exactly one target+# pattern, not a list - buck2 gets multiple candidate execution+# platforms from that *one* target's own `ExecutionPlatformRegistrationInfo.+# platforms` list instead (confirmed directly: pointing it at two+# space-separated targets fails to parse as a target pattern at all).+# This aggregates any number of platform deps into one such list, in the+# order given - buck2 picks the first one in that order compatible with+# a given target's `exec_compatible_with`.+def _execution_platforms_impl(ctx: AnalysisContext) -> list[Provider]:+ platforms = [p[ExecutionPlatformInfo] for p in ctx.attrs.platforms]+ return [+ DefaultInfo(),+ ExecutionPlatformRegistrationInfo(+ platforms = platforms,+ exec_marker_constraint = get_exec_platform_marker(),+ ),+ ]++execution_platforms = rule(+ impl = _execution_platforms_impl,+ attrs = {+ "platforms": attrs.list(attrs.dep(providers = [ExecutionPlatformInfo])),+ },+)
@@ -0,0 +1,38 @@+[repositories]+prelude = .++# We want to disable the following values when we don't have open source,+# but our custom config format (yuk) doesn't accept inline comments.+# Therefore, we hide the name of the group when not open source.++[repository_aliases]+[not_repository_aliases] # @oss-enable+config = ovr_config++# Some sort of defaults to make ovrsource macros stop complaining.+[ovrsource]++[java]+ bootclasspath_8 = fbsource//xplat/third-party/java/jdk8:jce-stub fbsource//xplat/third-party/java/jdk8:jsse-stub fbsource//xplat/third-party/java/jdk8:rt-stub+ javacd_dep_files = per_class+ source_level = 8+ src_roots = /fbandroid/instrumentation_tests/, src, test, java, javatests, src-gen, src-test, tests, javatestgen, testgen+ target_level = 8++[kotlin]+ enable_incremental_compilation = true+ frontend_compiler = defined_by_target+ kotlin_home = $(config fbsource.repo_relative_path)/xplat/toolchains/android/sdk/third-party/java/kotlin/$(config kotlin.kotlin_version)+ kotlin_version = 2.2.0+ kotlin_version_for_upgrade_only_do_not_use = 2.2.0+ kotlincd_dep_files = per_class+ ksp_version = 2.0.2+ ksp_version_for_upgrade_only_do_not_use=2.0.2+ min_language_version_for_dcg = 1.9+ min_language_version_for_jvm_abi_gen = 1.9+ track_class_usage = true++[http]+[not_http] # @oss-enable+ # Internal Maven mirror+ maven_repo = https://maven.thefacebook.com/nexus/content/groups/public
@@ -0,0 +1,69 @@+load("@prelude//:none.bzl", "none_rule")+load("@prelude//transitions:constraint_override_registry.bzl", "constraint_override_refs", "constraint_override_registry")+load("@prelude//utils:source_listing.bzl", "source_listing")+load(":native.bzl", prelude = "native")++oncall("build_infra")++source_listing(+ exclude = [+ # Exclude PACKAGE file using modifiers since those are not enabled everywhere yet.+ "PACKAGE",+ ]+)++# Done to avoid triggering a lint rule that replaces glob with an fbcode macro+globby = glob++srcs = globby(+ ["**"],+ # Context: https://fb.workplace.com/groups/buck2users/posts/3121903854732641/+ exclude = [+ "**/.pyre_configuration.local",+ # Unfortunately, using modifiers require loading bzl files in outside of prelude,+ # and that currently breaks isolated tests that attempt to grab a best-effort prelude+ # from the filegroup below.+ # TODO: Switch these tests to use the bundled prelude instead.+ "PACKAGE",+ ],+)++# Re-export filegroups that are behind package boundary violations for+# Buck2.+prelude.filegroup(+ name = "files",+ srcs = srcs,+ visibility = ["PUBLIC"],+)++# Tests want BUCK.v2 instead of TARGETS.v2+prelude.genrule(+ name = "copy_android_constraint",+ out = "BUCK",+ cmd = "cp $(location prelude//android/constraints:files)/BUCK $OUT",+ visibility = ["PUBLIC"],+)++prelude.filegroup(+ name = "prelude",+ srcs = {+ "": ":files",+ "android/constraints/BUCK": ":copy_android_constraint",+ # explicitly include files that fall off the glob due to package boundary violations+ "cfg/exec_platform/marker/BUCK": "//cfg/exec_platform/marker:buck_file",+ # @oss-disable[end= ]: "python/meta_only/config.bzl": "//python/meta_only:config.bzl",+ "rust/tools/attrs.bzl": "//rust/tools:attrs.bzl",+ },+ visibility = ["PUBLIC"],+)++none_rule(+ name = "none",+ visibility = ["PUBLIC"],+)++constraint_override_registry(+ name = "constraint_override_registry",+ refs = constraint_override_refs(),+ visibility = ["PUBLIC"],+)
@@ -0,0 +1,201 @@+Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ 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.
@@ -0,0 +1,21 @@+MIT License++Copyright (c) Meta Platforms, Inc. and affiliates.++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
@@ -0,0 +1,29 @@+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("build_infra")++source_listing()++config_setting(+ name = "gnu",+ constraint_values = [+ "prelude//abi/constraints:gnu",+ ],+ visibility = ["PUBLIC"],+)++config_setting(+ name = "msvc",+ constraint_values = [+ "prelude//abi/constraints:msvc",+ ],+ visibility = ["PUBLIC"],+)++config_setting(+ name = "musl",+ constraint_values = [+ "prelude//abi/constraints:musl",+ ],+ visibility = ["PUBLIC"],+)
@@ -0,0 +1,20 @@+load("@prelude//configurations:constraint_alias.bzl", "constraint_with_aliases")+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("build_infra")++source_listing()++# Used by open source projects to support `prelude//`++constraint_with_aliases(+ name = "abi",+ aliases = {+ "gnu": "gnu",+ "msvc": "msvc",+ "musl": "musl",+ },+ default = "unspecified",+ values = ["gnu", "msvc", "musl", "unspecified"],+ visibility = ["PUBLIC"],+)
@@ -0,0 +1,28 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# Implementation of aliases build rules.++def alias_impl(ctx: AnalysisContext) -> list[Provider]:+ if ctx.attrs.actual:+ return ctx.attrs.actual.providers+ else:+ return [DefaultInfo()]++def configured_alias_impl(ctx: AnalysisContext) -> list[Provider]:+ if ctx.attrs.configured_actual != None and ctx.attrs.fallback_actual != None:+ fail("cannot set both of `configured_actual` and `fallback_actual`")+ if ctx.attrs.configured_actual != None:+ return ctx.attrs.configured_actual.providers+ if ctx.attrs.fallback_actual != None:+ return ctx.attrs.fallback_actual.providers+ fail("must set one of `configured_actual` or `fallback_actual`")++def versioned_alias_impl(_ctx: AnalysisContext) -> list[Provider]:+ # Should be intercepted in macro stub and converted to `alias`.+ fail("unsupported")
@@ -0,0 +1,209 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//android:android_providers.bzl", "Aapt2LinkInfo", "AndroidResourceInfo", "RESOURCE_PRIORITY_LOW")+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")++BASE_PACKAGE_ID = 0x7F++def normalize_locale(locale: str) -> str:+ if locale == "NONE":+ return "en"+ if regex("^[a-z][a-z]$").match(locale):+ return locale+ if regex("^[a-z][a-z]_[A-Z][A-Z]$").match(locale):+ # This transforms locales from xx_YY to xx-rYY.+ # E.g.: like "zh_CN" to "zh-rCN".+ return locale[:2] + "-r" + locale[-2:]+ if regex("^[a-z][a-z]-r[A-Z][A-Z]$").match(locale):+ # Already in xx-rYY format+ return locale+ fail("Invalid locale format passed: {} {}".format(locale, regex("/^[a-z][a-z]$/").match(locale)))++def get_aapt2_link(+ ctx: AnalysisContext,+ android_toolchain: AndroidToolchainInfo,+ resource_infos: list[AndroidResourceInfo],+ android_manifest: Artifact,+ manifest_entries: dict,+ includes_vector_drawables: bool,+ no_resource_removal: bool,+ should_keep_raw_values: bool,+ package_id_offset: int,+ resource_stable_ids: Artifact | None,+ preferred_density: [str, None],+ filter_locales: bool,+ locales: list[str],+ compiled_resource_apks: list[Artifact],+ additional_aapt2_params: list[str],+ extra_filtered_resources: list[str],+) -> (Aapt2LinkInfo, Aapt2LinkInfo):+ link_infos = []+ for use_proto_format in [False, True]:+ if use_proto_format:+ identifier = "use_proto"+ else:+ identifier = "not_proto"++ aapt2_command = cmd_args(android_toolchain.aapt2)+ aapt2_command.add("link")++ # aapt2 only supports @ for -R or input files, not for all args, so we pass in all "normal"+ # args here.+ resources_apk = ctx.actions.declare_output("{}/resource-apk.ap_".format(identifier), has_content_based_path = False)+ aapt2_command.add(["-o", resources_apk.as_output()])+ proguard_config = ctx.actions.declare_output("{}/proguard_config.pro".format(identifier), has_content_based_path = False)+ aapt2_command.add(["--proguard", proguard_config.as_output()])++ # We don't need the R.java output, but aapt2 won't output R.txt unless we also request R.java.+ # A drawback of this is that the directory structure for the R.java output is deep, resulting+ # in long path issues on Windows. The structure is <path to target>/<identifier>/unused-rjava/<package>/R.java+ # We can declare a custom dummy package to drastically shorten <package>, which is sketchy, but effective+ r_dot_java = ctx.actions.declare_output("{}/unused-rjava".format(identifier), dir = True, has_content_based_path = False)+ aapt2_command.add(["--java", r_dot_java.as_output()])+ aapt2_command.add(["--custom-package", "dummy.package"])++ r_dot_txt = ctx.actions.declare_output("{}/R.txt".format(identifier), has_content_based_path = False)+ aapt2_command.add(["--output-text-symbols", r_dot_txt.as_output()])++ aapt2_command.add(["--manifest", android_manifest])+ aapt2_command.add(["-I", android_toolchain.android_jar])++ if includes_vector_drawables:+ aapt2_command.add("--no-version-vectors")+ aapt2_command.add("--auto-add-overlay")+ if use_proto_format:+ aapt2_command.add("--proto-format")+ if no_resource_removal:+ aapt2_command.add("--no-resource-removal")+ if should_keep_raw_values:+ aapt2_command.add("--keep-raw-values")+ if package_id_offset != 0:+ aapt2_command.add(["--package-id", "0x{}".format(BASE_PACKAGE_ID + package_id_offset)])+ if resource_stable_ids != None:+ aapt2_command.add(["--stable-ids", resource_stable_ids])+ if preferred_density != None:+ aapt2_command.add(["--preferred-density", preferred_density])++ manifest_entries_min_sdk = manifest_entries.get("min_sdk_version", None)+ if manifest_entries_min_sdk != None:+ aapt2_command.add(["--min-sdk-version", str(manifest_entries_min_sdk)])+ manifest_entries_target_sdk = manifest_entries.get("target_sdk_version", None)+ if manifest_entries_target_sdk != None:+ aapt2_command.add(["--target-sdk-version", str(manifest_entries_target_sdk)])+ manifest_entries_version_code = manifest_entries.get("version_code", None)+ if manifest_entries_version_code != None:+ aapt2_command.add(["--version-code", manifest_entries_version_code])+ manifest_entries_version_name = manifest_entries.get("version_name", None)+ if manifest_entries_version_name != None:+ aapt2_command.add(["--version-name", manifest_entries_version_name])+ manifest_entries_debug_mode = str(manifest_entries.get("debug_mode", "False")).lower() == "true"+ if manifest_entries_debug_mode:+ aapt2_command.add(["--debug-mode"])++ if filter_locales and len(locales) > 0:+ for locale in locales:+ aapt2_command.add(["-c", normalize_locale(locale)])++ for compiled_resource_apk in compiled_resource_apks:+ aapt2_command.add(["-I", compiled_resource_apk])++ # put low priority resources first so that they get overwritten by higher priority resources+ low_priority_aapt2_compile_rules = []+ normal_priority_aapt2_compile_rules = []+ for resource_info in resource_infos:+ if resource_info.aapt2_compile_output:+ (low_priority_aapt2_compile_rules if resource_info.res_priority == RESOURCE_PRIORITY_LOW else normal_priority_aapt2_compile_rules).append(+ resource_info.aapt2_compile_output+ )+ aapt2_compile_rules = low_priority_aapt2_compile_rules + normal_priority_aapt2_compile_rules++ aapt2_compile_rules_args_file = ctx.actions.write(+ "{}/aapt2_compile_rules_args_file".format(identifier), cmd_args(aapt2_compile_rules, delimiter = " "), has_content_based_path = False+ )+ aapt2_command.add("-R")+ aapt2_command.add(+ cmd_args(+ aapt2_compile_rules_args_file,+ format = "@{}",+ hidden = aapt2_compile_rules,+ )+ )++ aapt2_command.add(additional_aapt2_params)++ ctx.actions.run(aapt2_command, category = "aapt2_link", identifier = identifier, allow_cache_upload = True, error_handler = aapt_link_error_handler)++ # The normal resource filtering apparatus is super slow, because it extracts the whole apk,+ # strips files out of it, then repackages it.+ #+ # This is a faster filtering step that just uses zip -d to remove entries from the archive.+ # It's also superbly dangerous.+ #+ # If zip -d returns that there was nothing to do, then we don't fail.+ if len(extra_filtered_resources) > 0:+ filtered_resources_apk = ctx.actions.declare_output("{}/filtered-resource-apk.ap_".format(identifier), has_content_based_path = False)+ filter_resources_cmd = cmd_args(ctx.attrs._android_toolchain[AndroidToolchainInfo].aapt2_filter_resources)+ filter_resources_cmd.add(cmd_args(resources_apk, format = "--input-apk={}"))+ filter_resources_cmd.add(cmd_args(filtered_resources_apk.as_output(), format = "--output-apk={}"))+ filter_resources_cmd.add(cmd_args(extra_filtered_resources, format = "--extra-filtered-resources={}"))+ ctx.actions.run(filter_resources_cmd, category = "aapt2_filter_resources", identifier = identifier, allow_cache_upload = True)+ primary_resources_apk = filtered_resources_apk+ else:+ primary_resources_apk = resources_apk++ link_infos.append(+ Aapt2LinkInfo(+ primary_resources_apk = primary_resources_apk,+ proguard_config_file = proguard_config,+ r_dot_txt = r_dot_txt,+ )+ )++ return link_infos[0], link_infos[1]++def get_module_manifest_in_proto_format(+ ctx: AnalysisContext, android_toolchain: AndroidToolchainInfo, android_manifest: Artifact, primary_resources_apk: Artifact, module_name: str+) -> Artifact:+ aapt2_command = cmd_args(android_toolchain.aapt2)+ aapt2_command.add("link")++ # aapt2 only supports @ for -R or input files, not for all args, so we pass in all "normal"+ # args here.+ resources_apk = ctx.actions.declare_output("{}/resource-apk.ap_".format(module_name), has_content_based_path = False)+ aapt2_command.add(["-o", resources_apk.as_output()])+ aapt2_command.add(["--manifest", android_manifest])+ aapt2_command.add(["-I", android_toolchain.android_jar])+ aapt2_command.add(["-I", primary_resources_apk])+ aapt2_command.add("--proto-format")++ ctx.actions.run(aapt2_command, category = "aapt2_link", identifier = module_name, allow_cache_upload = True, error_handler = aapt_link_error_handler)++ proto_manifest_dir = ctx.actions.declare_output("{}/proto_format_manifest".format(module_name), has_content_based_path = False)+ proto_manifest = proto_manifest_dir.project("AndroidManifest.xml")+ ctx.actions.run(+ cmd_args(["unzip", resources_apk, "AndroidManifest.xml", "-d", proto_manifest_dir.as_output()]),+ category = "unzip_proto_format_manifest",+ identifier = module_name,+ allow_cache_upload = True,+ )++ return proto_manifest++def aapt_link_error_handler(ctx: ActionErrorCtx) -> list[ActionSubError]:+ errors = []+ lowercase_stderr = ctx.stderr.lower()+ if regex(r"failed to write .* to archive").match(lowercase_stderr):+ errors.append(+ ctx.new_sub_error(+ category = "aapt2_link",+ message = "Most probably there are too many res files in the apk (over 65535). Try filtering out some resources.",+ show_in_stderr = True,+ )+ )+ return errors
@@ -0,0 +1,43 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(":android_aar.bzl", "android_aar_impl")+load(":android_apk.bzl", "android_apk_impl")+load(":android_build_config.bzl", "android_build_config_impl")+load(":android_bundle.bzl", "android_bundle_impl")+load(":android_instrumentation_apk.bzl", "android_instrumentation_apk_impl")+load(":android_instrumentation_test.bzl", "android_instrumentation_test_impl")+load(":android_library.bzl", "android_library_impl")+load(":android_manifest.bzl", "android_manifest_impl")+load(":android_prebuilt_aar.bzl", "android_prebuilt_aar_impl")+load(":android_resource.bzl", "android_resource_impl")+load(":apk_genrule.bzl", "apk_genrule_impl")+load(":gen_aidl.bzl", "gen_aidl_impl")+load(":keystore.bzl", "keystore_impl")+load(":prebuilt_native_library.bzl", "prebuilt_native_library_impl")+load(":robolectric_test.bzl", "robolectric_test_impl")+load(":voltron.bzl", "android_app_modularity_impl")++implemented_rules = {+ "android_aar": android_aar_impl,+ "android_app_modularity": android_app_modularity_impl,+ "android_binary": android_apk_impl,+ "android_build_config": android_build_config_impl,+ "android_bundle": android_bundle_impl,+ "android_instrumentation_apk": android_instrumentation_apk_impl,+ "android_instrumentation_test": android_instrumentation_test_impl,+ "android_library": android_library_impl,+ "android_manifest": android_manifest_impl,+ "android_prebuilt_aar": android_prebuilt_aar_impl,+ "android_resource": android_resource_impl,+ "apk_genrule": apk_genrule_impl,+ "gen_aidl": gen_aidl_impl,+ "keystore": keystore_impl,+ "prebuilt_native_library": prebuilt_native_library_impl,+ "robolectric_test": robolectric_test_impl,+}
@@ -0,0 +1,203 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//android:android_binary.bzl", "get_build_config_java_libraries")+load("@prelude//android:android_binary_native_library_rules.bzl", "get_android_binary_native_library_info")+load("@prelude//android:android_binary_resources_rules.bzl", "get_cxx_resources", "get_manifest")+load(+ "@prelude//android:android_providers.bzl",+ "AndroidResourceInfo",+ "ExportedAndroidResourceInfo",+ "get_all_android_packageable_targets",+ "merge_android_packageable_info",+)+load("@prelude//android:android_resource.bzl", "get_text_symbols")+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//android:configuration.bzl", "get_deps_by_platform")+load("@prelude//android:cpu_filters.bzl", "CPU_FILTER_FOR_DEFAULT_PLATFORM", "CPU_FILTER_FOR_PRIMARY_PLATFORM")+load("@prelude//android:util.bzl", "create_enhancement_context")+load("@prelude//java:java_providers.bzl", "create_java_packaging_dep", "get_all_java_packaging_deps", "get_all_java_packaging_deps_from_packaging_infos")+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")+load("@prelude//target_stats:target_stats.bzl", "target_stats_aggregate_providers_and_subtargets")+load("@prelude//utils:argfile.bzl", "argfile")+load("@prelude//utils:utils.bzl", "flatten")++def android_aar_impl(ctx: AnalysisContext) -> list[Provider]:+ deps_by_platform = get_deps_by_platform(ctx)+ primary_platform = CPU_FILTER_FOR_PRIMARY_PLATFORM if CPU_FILTER_FOR_PRIMARY_PLATFORM in deps_by_platform else CPU_FILTER_FOR_DEFAULT_PLATFORM+ deps = deps_by_platform[primary_platform]++ excluded_java_packaging_deps = get_all_java_packaging_deps(ctx, ctx.attrs.excluded_java_deps)+ excluded_java_packaging_deps_targets = set([excluded_dep.label.raw_target() for excluded_dep in excluded_java_packaging_deps])+ java_packaging_deps = [+ packaging_dep+ for packaging_dep in get_all_java_packaging_deps(ctx, deps)+ if packaging_dep.label.raw_target() not in excluded_java_packaging_deps_targets+ ]+ android_packageable_info = merge_android_packageable_info(ctx.label, ctx.actions, deps)++ excluded_android_packageable_targets = set(get_all_android_packageable_targets(ctx.attrs.excluded_java_deps))+ manifest_infos = android_packageable_info.manifests.traverse(ordering = "topological") if android_packageable_info.manifests else []+ manifests = [manifest_info.manifest for manifest_info in manifest_infos if manifest_info.target_label not in excluded_android_packageable_targets]+ android_manifest = get_manifest(ctx, manifests, ctx.attrs.manifest_entries, should_replace_application_id_placeholders = False)++ if ctx.attrs.include_build_config_class:+ build_config_infos = list(android_packageable_info.build_config_infos.traverse()) if android_packageable_info.build_config_infos else []+ java_packaging_deps.extend(+ get_all_java_packaging_deps_from_packaging_infos(+ ctx,+ get_build_config_java_libraries(ctx, build_config_infos, package_type = "release", exopackage_modes = []),+ )+ )++ enhancement_ctx = create_enhancement_context(ctx)+ android_binary_native_library_info = get_android_binary_native_library_info(+ enhancement_ctx,+ android_packageable_info,+ deps_by_platform,+ prebuilt_native_library_dirs_to_exclude = excluded_android_packageable_targets,+ shared_libraries_to_exclude = excluded_android_packageable_targets,+ native_library_merge_glue = getattr(ctx.attrs, "native_library_merge_glue", None),+ native_library_merge_sequence = getattr(ctx.attrs, "native_library_merge_sequence", None),+ native_library_merge_map = getattr(ctx.attrs, "native_library_merge_map", None),+ native_library_merge_non_asset_libs = getattr(ctx.attrs, "native_library_merge_non_asset_libs", False),+ native_library_merge_linker_args = getattr(ctx.attrs, "native_library_merge_linker_args", None),+ native_library_merge_linker_args_all = getattr(ctx.attrs, "native_library_merge_linker_args_all", None),+ native_library_merge_code_generator = getattr(ctx.attrs, "native_library_merge_code_generator", None),+ native_library_merge_sequence_blocklist = getattr(ctx.attrs, "native_library_merge_sequence_blocklist", None),+ )+ java_packaging_deps.extend([+ create_java_packaging_dep(+ ctx,+ library_output,+ )+ for library_output in android_binary_native_library_info.generated_java_code+ ])++ jars = [dep.jar for dep in java_packaging_deps if dep.jar]+ classes_jar = ctx.actions.declare_output("classes.jar", has_content_based_path = False)+ java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]+ classes_jar_cmd = cmd_args([+ java_toolchain.jar_builder,+ "--entries-to-jar",+ argfile(actions = ctx.actions, name = "classes_jar_entries.txt", args = jars),+ "--output",+ classes_jar.as_output(),+ ])++ if ctx.attrs.remove_classes:+ remove_classes_file = ctx.actions.write("remove_classes.txt", ctx.attrs.remove_classes, has_content_based_path = False)+ classes_jar_cmd.add([+ "--blocklist-patterns",+ remove_classes_file,+ "--blocklist-patterns-matcher",+ "remove_classes_patterns_matcher",+ ])++ ctx.actions.run(classes_jar_cmd, category = "create_classes_jar")++ sub_targets = {}+ dependency_sources_jars = [dep.sources_jar for dep in java_packaging_deps if dep.sources_jar]+ if dependency_sources_jars:+ combined_sources_jar = ctx.actions.declare_output("sources.jar", has_content_based_path = False)+ java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]+ combined_sources_jar_cmd = cmd_args([+ java_toolchain.jar_builder,+ "--entries-to-jar",+ argfile(actions = ctx.actions, name = "combined_sources_jar_entries.txt", args = dependency_sources_jars),+ "--output",+ combined_sources_jar.as_output(),+ ])++ if ctx.attrs.remove_classes:+ remove_classes_file = ctx.actions.write("sources_remove_classes.txt", ctx.attrs.remove_classes, has_content_based_path = False)+ combined_sources_jar_cmd.add([+ "--blocklist-patterns",+ remove_classes_file,+ "--blocklist-patterns-matcher",+ "remove_classes_patterns_matcher",+ ])++ ctx.actions.run(combined_sources_jar_cmd, category = "create_sources_jar")+ sub_targets["sources.jar"] = [DefaultInfo(default_output = combined_sources_jar)]++ entries = [android_manifest, classes_jar]++ all_resource_infos = list(android_packageable_info.resource_infos.traverse()) if android_packageable_info.resource_infos else []+ resource_infos = [resource_info for resource_info in all_resource_infos if resource_info.raw_target not in excluded_android_packageable_targets]++ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]+ if resource_infos:+ res_dirs = [resource_info.res for resource_info in resource_infos if resource_info.res]+ if ctx.attrs.package_resources and res_dirs:+ merged_resource_sources_dir = ctx.actions.declare_output("merged_resource_sources_dir/res", dir = True, has_content_based_path = False)+ merge_resource_sources_cmd = cmd_args([+ android_toolchain.merge_android_resource_sources[RunInfo],+ "--resource-paths",+ argfile(actions = ctx.actions, name = "resource_paths.txt", args = res_dirs),+ "--output",+ merged_resource_sources_dir.as_output(),+ ])++ ctx.actions.run(merge_resource_sources_cmd, category = "merge_android_resource_sources")++ r_dot_txt = get_text_symbols(+ ctx, merged_resource_sources_dir, [dep for dep in deps if AndroidResourceInfo in dep or ExportedAndroidResourceInfo in dep]+ )+ entries.extend([merged_resource_sources_dir, r_dot_txt])++ assets_dirs = flatten([resource_infos.assets for resource_infos in resource_infos])+ entries.extend(assets_dirs)++ cxx_resources = get_cxx_resources(ctx, deps, dir_name = "assets")+ if cxx_resources:+ entries.append(cxx_resources)++ native_libs_file = argfile(actions = ctx.actions, name = "native_libs_entries.txt", args = android_binary_native_library_info.native_libs_for_primary_apk)+ native_libs_assets_file = argfile(+ actions = ctx.actions, name = "native_libs_assets_entries.txt", args = android_binary_native_library_info.root_module_native_lib_assets+ )++ entries_file = ctx.actions.write("entries.txt", entries, has_content_based_path = False)++ aar = ctx.actions.declare_output("{}.aar".format(ctx.label.name), has_content_based_path = False)+ create_aar_cmd = cmd_args(+ [+ android_toolchain.aar_builder,+ "--output_path",+ aar.as_output(),+ "--entries_file",+ entries_file,+ "--on_duplicate_entry",+ "fail",+ "--native_libs_file",+ native_libs_file,+ "--native_libs_assets_file",+ native_libs_assets_file,+ ],+ hidden = [+ entries,+ ],+ )+ if ctx.attrs.proguard_config:+ create_aar_cmd.add([+ "--proguard_config_file",+ ctx.attrs.proguard_config,+ ])++ if ctx.attrs.hardcode_permissions_for_deterministic_output == True:+ create_aar_cmd.add([+ "--hardcode_permissions_for_deterministic_output",+ ])++ ctx.actions.run(create_aar_cmd, category = "create_aar")++ target_stats_providers, target_stats_subtargets = target_stats_aggregate_providers_and_subtargets(ctx, deps = deps)+ sub_targets.update(target_stats_subtargets)++ return [DefaultInfo(default_outputs = [aar], sub_targets = enhancement_ctx.get_sub_targets() | sub_targets)] + target_stats_providers
@@ -0,0 +1,335 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")+load("@prelude//android:android_binary.bzl", "get_binary_info")+load(+ "@prelude//android:android_providers.bzl",+ "AndroidApkExopackageInfo",+ "AndroidApkInfo",+ "AndroidApkUnderTestInfo",+ "AndroidBinaryNativeLibsInfo",+ "AndroidBinaryPrimaryPlatformInfo",+ "AndroidBinaryResourcesInfo",+ "DexFilesInfo",+ "ExopackageInfo",+ "KeystoreInfo",+)+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//android:util.bzl", "package_validators_decorator")+load("@prelude//java:class_to_srcs.bzl", "merge_class_to_source_map_from_jar")+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")+load("@prelude//java/utils:java_more_utils.bzl", "get_path_separator_for_exec_os")+load("@prelude//java/utils:java_utils.bzl", "get_class_to_source_map_info")+load("@prelude//target_stats:target_stats.bzl", "target_stats_aggregate_providers_and_subtargets")+load("@prelude//utils:argfile.bzl", "argfile")+load("@prelude//utils:utils.bzl", "flatten")++def android_apk_impl(ctx: AnalysisContext) -> list[Provider]:+ android_binary_info = get_binary_info(ctx, use_proto_format = False)+ java_packaging_deps = android_binary_info.java_packaging_deps+ sub_targets = android_binary_info.sub_targets+ dex_files_info = android_binary_info.dex_files_info+ native_library_info = android_binary_info.native_library_info+ resources_info = android_binary_info.resources_info+ validation_outputs = android_binary_info.validation_outputs++ wrapped_build_apk = package_validators_decorator(+ ctx,+ build_apk,+ extension = ".apk",+ )++ keystore = ctx.attrs.keystore[KeystoreInfo]+ output_apk = wrapped_build_apk(+ output_filename = ctx.label.name,+ actions = ctx.actions,+ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo],+ keystore = keystore,+ dex_files_info = dex_files_info,+ native_library_info = native_library_info,+ resources_info = resources_info,+ compress_resources_dot_arsc = ctx.attrs.resource_compression == "enabled" or ctx.attrs.resource_compression == "enabled_with_strings_as_assets",+ validation_deps_outputs = get_validation_deps_outputs(ctx) + validation_outputs,+ packaging_options = ctx.attrs.packaging_options,+ # Exclude BUCK_BUILD_ID from assets/BuildInfo.json for release builds.+ include_build_info_file = ctx.attrs.include_build_info_file and ctx.attrs.package_type != "release",+ )++ if dex_files_info.secondary_dex_exopackage_info or native_library_info.exopackage_info or resources_info.exopackage_info:+ exopackage_info = ExopackageInfo(+ secondary_dex_info = dex_files_info.secondary_dex_exopackage_info,+ native_library_info = native_library_info.exopackage_info,+ resources_info = resources_info.exopackage_info,+ )+ default_output = ctx.actions.write(+ "{}_exopackage_apk_warning".format(ctx.label.name),+ "exopackage apks should not be used externally, try buck install or building with exopackage disabled\n",+ has_content_based_path = False,+ )+ sub_targets["exo_apk"] = [DefaultInfo(default_output = output_apk)] # Used by tests+ else:+ exopackage_info = None+ default_output = output_apk++ class_to_srcs, _, class_to_srcs_subtargets = get_class_to_source_map_info(+ ctx,+ outputs = None,+ deps = android_binary_info.deps_by_platform[android_binary_info.primary_platform],+ )+ transitive_class_to_src_map = merge_class_to_source_map_from_jar(+ actions = ctx.actions,+ name = ctx.label.name + ".transitive_class_to_src.json",+ java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo],+ relative_to = None,+ deps = [class_to_srcs],+ )+ sub_targets["transitive_class_to_src_map"] = [DefaultInfo(default_output = transitive_class_to_src_map)]++ # We can only be sure that an APK has native libs if it has any shared libraries. Prebuilt native libraries dirs can exist but be empty.+ definitely_has_native_libs = bool(native_library_info.shared_libraries)++ install_info = get_install_info(+ ctx, output_apk = output_apk, manifest = resources_info.manifest, exopackage_info = exopackage_info, definitely_has_native_libs = definitely_has_native_libs+ )++ classpath = [dep.jar for dep in java_packaging_deps if dep.jar]+ sub_targets["classpath"] = [+ DefaultInfo(default_output = ctx.actions.write("classpath.txt", classpath, has_content_based_path = False), other_outputs = classpath)+ ]+ sub_targets["classpath_targets"] = [+ DefaultInfo(+ default_output = ctx.actions.write("classpath_targets.txt", list(set([jar.owner.raw_target() for jar in classpath])), has_content_based_path = False)+ )+ ]++ # ctx.attrs.deps is split-transitioned here (one Dependency per ABI).+ target_stats_providers, target_stats_subtargets = target_stats_aggregate_providers_and_subtargets(+ ctx,+ deps = android_binary_info.deps_by_platform[android_binary_info.primary_platform],+ )+ sub_targets.update(target_stats_subtargets)++ providers = [+ AndroidApkInfo(+ apk = output_apk,+ manifest = resources_info.manifest,+ materialized_artifacts = android_binary_info.materialized_artifacts,+ unstripped_shared_libraries = native_library_info.unstripped_shared_libraries,+ ),+ AndroidBinaryPrimaryPlatformInfo(+ primary_platform = android_binary_info.primary_platform,+ ),+ AndroidApkUnderTestInfo(+ java_packaging_deps = set([dep.label.raw_target() for dep in java_packaging_deps]),+ keystore = keystore,+ manifest_entries = ctx.attrs.manifest_entries,+ min_sdk_version = ctx.attrs.min_sdk_version,+ prebuilt_native_library_dirs = set([native_lib.raw_target for native_lib in native_library_info.prebuilt_native_library_dirs]),+ platform_configurations = set([str(x.label.configured_target().config()) for x in flatten(android_binary_info.deps_by_platform.values())]),+ platforms = android_binary_info.deps_by_platform.keys(),+ primary_platform = android_binary_info.primary_platform,+ resource_infos = set([info.raw_target for info in resources_info.unfiltered_resource_infos]),+ r_dot_java_packages = set(+ [info.specified_r_dot_java_package for info in resources_info.unfiltered_resource_infos if info.specified_r_dot_java_package]+ ),+ shared_libraries = set(native_library_info.shared_libraries),+ # Merge map delegate+ native_library_merge_sequence = ctx.attrs.native_library_merge_sequence,+ native_library_merge_code_generator = ctx.attrs.native_library_merge_code_generator,+ native_library_merge_glue = ctx.attrs.native_library_merge_glue,+ native_library_merge_linker_args_all = ctx.attrs.native_library_merge_linker_args_all,+ native_library_merge_linker_args = ctx.attrs.native_library_merge_linker_args,+ native_library_merge_map = ctx.attrs.native_library_merge_map,+ native_library_merge_non_asset_libs = ctx.attrs.native_library_merge_non_asset_libs,+ native_library_merge_sequence_blocklist = ctx.attrs.native_library_merge_sequence_blocklist,+ ),+ DefaultInfo(+ default_output = default_output,+ other_outputs = install_info.files.values() + android_binary_info.materialized_artifacts,+ sub_targets = sub_targets | class_to_srcs_subtargets,+ ),+ install_info,+ TemplatePlaceholderInfo(+ keyed_variables = {+ "classpath": cmd_args(classpath, delimiter = get_path_separator_for_exec_os(ctx)),+ "classpath_including_targets_with_no_output": cmd_args(+ [dep.output_for_classpath_macro for dep in java_packaging_deps], delimiter = get_path_separator_for_exec_os(ctx)+ ),+ },+ ),+ class_to_srcs,+ ] + target_stats_providers++ if android_binary_info.preprocessed_java_classes_info:+ providers.append(android_binary_info.preprocessed_java_classes_info)++ # Expose the exopackage secondary-dex dir so android_instrumentation_test can push it to the device.+ if exopackage_info != None and exopackage_info.secondary_dex_info != None:+ providers.append(+ AndroidApkExopackageInfo(secondary_dex_directory = exopackage_info.secondary_dex_info.directory),+ )++ return providers++def build_apk(+ output_filename: str,+ actions: AnalysisActions,+ keystore: KeystoreInfo,+ android_toolchain: AndroidToolchainInfo,+ dex_files_info: DexFilesInfo,+ native_library_info: AndroidBinaryNativeLibsInfo,+ resources_info: AndroidBinaryResourcesInfo,+ compress_resources_dot_arsc: bool = False,+ validation_deps_outputs: [list[Artifact], None] = None,+ packaging_options: dict | None = None,+ include_build_info_file: bool = False,+) -> Artifact:+ output_apk = actions.declare_output("{}.apk".format(output_filename), has_content_based_path = False)++ apk_builder_args = cmd_args(+ android_toolchain.apk_builder[RunInfo],+ "--output-apk",+ output_apk.as_output(),+ "--resource-apk",+ resources_info.primary_resources_apk,+ "--dex-file",+ dex_files_info.primary_dex,+ "--keystore-path",+ keystore.store,+ "--keystore-properties-path",+ keystore.properties,+ "--zipalign_tool",+ android_toolchain.zipalign[RunInfo],+ "--package-meta-inf-version-files" if android_toolchain.package_meta_inf_version_files else [],+ "--compress-resources-dot-arsc" if compress_resources_dot_arsc else [],+ # The outputs of validation_deps need to be added as hidden arguments+ # to an action for the validation_deps targets to be built and enforced.+ hidden = validation_deps_outputs or [],+ )++ asset_directories = (+ native_library_info.root_module_native_lib_assets+ + native_library_info.non_root_module_native_lib_assets+ + dex_files_info.root_module_bootstrap_dex_dirs+ + dex_files_info.root_module_secondary_dex_dirs+ + dex_files_info.non_root_module_secondary_dex_dirs+ + resources_info.module_manifests+ )+ asset_directories_file = argfile(actions = actions, name = "asset_directories.txt", args = asset_directories)+ native_library_directories = argfile(actions = actions, name = "native_library_directories", args = native_library_info.native_libs_for_primary_apk)+ all_zip_files = [resources_info.packaged_string_assets] if resources_info.packaged_string_assets else []+ zip_files = argfile(actions = actions, name = "zip_files", args = all_zip_files)+ jar_files_that_may_contain_resources = argfile(+ actions = actions, name = "jar_files_that_may_contain_resources", args = resources_info.jar_files_that_may_contain_resources+ )++ apk_builder_args.add([+ "--asset-directories-list",+ asset_directories_file,+ "--native-libraries-directories-list",+ native_library_directories,+ "--zip-files-list",+ zip_files,+ "--jar-files-that-may-contain-resources-list",+ jar_files_that_may_contain_resources,+ ])++ # Invoke the toolchain's build-info generator from this apk packaging action (which already has+ # every APK input) so the baked BUCK_BUILD_ID refreshes when the APK content changes and+ # cache-hits otherwise -- no separate action. Its run command is multi-token (java -jar ...), so+ # pass it via an argfile the apk-builder reads and execs.+ if include_build_info_file:+ apk_builder_args.add(+ "--build-info-generator-args",+ argfile(+ actions = actions,+ name = "build_info_generator_args",+ args = cmd_args(android_toolchain.build_info_generator[RunInfo]),+ allow_args = True,+ ),+ )++ if packaging_options:+ for key, value in packaging_options.items():+ if key == "excluded_resources":+ apk_builder_args.add("--excluded-resources", actions.write("excluded_resources.txt", value, has_content_based_path = False))+ elif key == "uncompressed_files":+ apk_builder_args.add("--uncompressed-files", actions.write("uncompressed_files.txt", value, has_content_based_path = False))+ else:+ fail("Only 'excluded_resources' and 'uncompressed_files' are supported in packaging_options right now!")++ actions.run(apk_builder_args, category = "apk_build", allow_cache_upload = True)++ return output_apk++def get_install_info(+ ctx: AnalysisContext,+ output_apk: Artifact,+ manifest: Artifact,+ exopackage_info: [ExopackageInfo, None],+ definitely_has_native_libs: bool = True,+ apex_mode: bool = False,+) -> InstallInfo:+ files = {+ ctx.attrs.name: output_apk,+ "manifest": manifest,+ "options": generate_install_config(ctx, apex_mode),+ }++ if exopackage_info:+ secondary_dex_exopackage_info = exopackage_info.secondary_dex_info+ native_library_exopackage_info = exopackage_info.native_library_info+ resources_info = exopackage_info.resources_info+ else:+ secondary_dex_exopackage_info = None+ native_library_exopackage_info = None+ resources_info = None++ if secondary_dex_exopackage_info:+ files["secondary_dex_exopackage_info_directory"] = secondary_dex_exopackage_info.directory+ files["secondary_dex_exopackage_info_metadata"] = secondary_dex_exopackage_info.metadata++ if native_library_exopackage_info:+ files["native_library_exopackage_info_directory"] = native_library_exopackage_info.directory+ files["native_library_exopackage_info_metadata"] = native_library_exopackage_info.metadata++ if resources_info:+ if resources_info.assets:+ files["resources_exopackage_assets"] = resources_info.assets+ files["resources_exopackage_assets_hash"] = resources_info.assets_hash++ files["resources_exopackage_res"] = resources_info.res+ files["resources_exopackage_res_hash"] = resources_info.res_hash++ if definitely_has_native_libs and hasattr(ctx.attrs, "cpu_filters"):+ files["cpu_filters"] = ctx.actions.write("cpu_filters.txt", ctx.attrs.cpu_filters, has_content_based_path = False)++ return InstallInfo(+ installer = ctx.attrs._android_toolchain[AndroidToolchainInfo].installer,+ files = files,+ )++def generate_install_config(ctx: AnalysisContext, apex_mode: bool) -> Artifact:+ data = get_install_config(apex_mode)+ return ctx.actions.write_json("install_android_options.json", data, has_content_based_path = False)++def get_install_config(apex_mode: bool) -> dict[str, typing.Any]:+ # TODO: read from toolchains+ install_config = {+ "adb_restart_on_failure": read_root_config("adb", "adb_restart_on_failure", "true"),+ "apex_mode": apex_mode,+ "multi_install_mode": read_root_config("adb", "multi_install_mode", "false"),+ "staged_install_mode": read_root_config("adb", "staged_install_mode", None),+ }++ adb_executable = read_root_config("android", "adb", None)+ if adb_executable:+ install_config["adb_executable"] = adb_executable++ return install_config
@@ -0,0 +1,315 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//android:android_binary_native_library_rules.bzl", "get_android_binary_native_library_info")+load("@prelude//android:android_binary_resources_rules.bzl", "get_android_binary_resources_info")+load("@prelude//android:android_build_config.bzl", "generate_android_build_config", "get_build_config_fields")+load(+ "@prelude//android:android_providers.bzl",+ "AndroidBinaryNativeLibsInfo", # @unused Used as type+ "AndroidBinaryResourcesInfo", # @unused Used as type+ "AndroidBuildConfigInfo", # @unused Used as type+ "AndroidPreprocessedJavaClassesInfo", # @unused Used as type+ "BuildConfigField",+ "DexFilesInfo",+ "merge_android_packageable_info",+)+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//android:configuration.bzl", "get_deps_by_platform")+load("@prelude//android:cpu_filters.bzl", "CPU_FILTER_FOR_DEFAULT_PLATFORM", "CPU_FILTER_FOR_PRIMARY_PLATFORM")+load("@prelude//android:dex_rules.bzl", "get_multi_dex", "get_single_primary_dex", "get_split_dex_merge_config", "merge_to_single_dex", "merge_to_split_dex")+load("@prelude//android:duplicate_class_check.bzl", "check_for_duplicate_classes_for_non_pre_dexed_jars", "check_for_duplicate_classes_for_pre_dexed_libs")+load("@prelude//android:exopackage.bzl", "get_exopackage_flags")+load("@prelude//android:preprocess_java_classes.bzl", "get_preprocessed_java_classes")+load("@prelude//android:util.bzl", "create_enhancement_context")+load("@prelude//android:voltron.bzl", "get_target_to_module_mapping")+load(+ "@prelude//java:java_providers.bzl",+ "JavaPackagingDep", # @unused Used as type+ "JavaPackagingInfo",+ "create_java_packaging_dep",+ "get_all_java_packaging_deps",+ "get_all_java_packaging_deps_from_packaging_infos",+)+load("@prelude//java:proguard.bzl", "get_proguard_output")+load("@prelude//utils:expect.bzl", "expect")++AndroidBinaryInfo = record(+ sub_targets = dict,+ java_packaging_deps = list[JavaPackagingDep],+ deps_by_platform = dict,+ primary_platform = str,+ dex_files_info = DexFilesInfo,+ native_library_info = AndroidBinaryNativeLibsInfo,+ resources_info = AndroidBinaryResourcesInfo,+ materialized_artifacts = list[Artifact],+ preprocessed_java_classes_info = AndroidPreprocessedJavaClassesInfo | None,+ validation_outputs = list[Artifact],+)++def get_binary_info(ctx: AnalysisContext, use_proto_format: bool) -> AndroidBinaryInfo:+ sub_targets = {}+ materialized_artifacts = []+ preprocessed_java_classes_info = None++ deps_by_platform = get_deps_by_platform(ctx)+ primary_platform = CPU_FILTER_FOR_PRIMARY_PLATFORM if CPU_FILTER_FOR_PRIMARY_PLATFORM in deps_by_platform else CPU_FILTER_FOR_DEFAULT_PLATFORM+ deps = deps_by_platform[primary_platform]++ target_to_module_mapping_file = get_target_to_module_mapping(ctx, deps_by_platform)++ no_dx_target_labels = [no_dx_target.label.raw_target() for no_dx_target in ctx.attrs.no_dx]+ java_packaging_deps = [packaging_dep for packaging_dep in get_all_java_packaging_deps(ctx, deps)]++ android_packageable_info = merge_android_packageable_info(ctx.label, ctx.actions, deps)+ build_config_infos = list(android_packageable_info.build_config_infos.traverse()) if android_packageable_info.build_config_infos else []++ build_config_libs = get_build_config_java_libraries(ctx, build_config_infos, ctx.attrs.package_type, ctx.attrs.exopackage_modes)+ java_packaging_deps += get_all_java_packaging_deps_from_packaging_infos(ctx, build_config_libs)++ has_proguard_config = (+ ctx.attrs.proguard_config != None or ctx.attrs.android_sdk_proguard_config == "default" or ctx.attrs.android_sdk_proguard_config == "optimized"+ )+ should_pre_dex = not ctx.attrs.disable_pre_dex and not has_proguard_config and not ctx.attrs.preprocess_java_classes_bash++ enhancement_ctx = create_enhancement_context(ctx)+ if target_to_module_mapping_file:+ enhancement_ctx.debug_output("module.mapping", target_to_module_mapping_file)++ shared_libraries_to_exclude_set = set([label.raw_target() for label in ctx.attrs.shared_libraries_to_exclude])+ native_library_info = get_android_binary_native_library_info(+ enhancement_ctx,+ android_packageable_info,+ deps_by_platform,+ apk_module_graph_file = target_to_module_mapping_file,+ shared_libraries_to_exclude = shared_libraries_to_exclude_set,+ native_library_merge_glue = getattr(ctx.attrs, "native_library_merge_glue", None),+ native_library_merge_sequence = getattr(ctx.attrs, "native_library_merge_sequence", None),+ native_library_merge_map = getattr(ctx.attrs, "native_library_merge_map", None),+ native_library_merge_non_asset_libs = getattr(ctx.attrs, "native_library_merge_non_asset_libs", False),+ native_library_merge_linker_args = getattr(ctx.attrs, "native_library_merge_linker_args", None),+ native_library_merge_linker_args_all = getattr(ctx.attrs, "native_library_merge_linker_args_all", None),+ native_library_merge_code_generator = getattr(ctx.attrs, "native_library_merge_code_generator", None),+ native_library_merge_sequence_blocklist = getattr(ctx.attrs, "native_library_merge_sequence_blocklist", None),+ )+ java_packaging_deps.extend([+ create_java_packaging_dep(+ ctx,+ library_output,+ )+ for library_output in native_library_info.generated_java_code+ ])++ referenced_resources_lists = (+ [java_packaging_dep.dex.referenced_resources for java_packaging_dep in java_packaging_deps if java_packaging_dep.dex]+ if ctx.attrs.trim_resource_ids and should_pre_dex+ else []+ )+ resources_info = get_android_binary_resources_info(+ ctx,+ deps,+ android_packageable_info,+ java_packaging_deps,+ apk_module_graph_file = target_to_module_mapping_file,+ use_proto_format = use_proto_format,+ referenced_resources_lists = referenced_resources_lists,+ manifest_entries = ctx.attrs.manifest_entries,+ generate_strings_and_ids_separately = should_pre_dex,+ aapt2_preferred_density = ctx.attrs.aapt2_preferred_density,+ )+ sub_targets["manifest"] = [DefaultInfo(default_output = resources_info.manifest)]+ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]+ compiled_r_dot_java_deps = [+ create_java_packaging_dep(+ ctx,+ r_dot_java.library_info.library_output.full_library,+ dex_weight_factor = android_toolchain.r_dot_java_weight_factor,+ )+ for r_dot_java in resources_info.r_dot_java_infos+ ]+ java_packaging_deps += compiled_r_dot_java_deps+ sub_targets["compiled_r_dot_java"] = [+ DefaultInfo(+ default_outputs = [compiled_r_dot_java_dep.jar for compiled_r_dot_java_dep in compiled_r_dot_java_deps],+ ),+ ]+ for r_dot_java_info in resources_info.r_dot_java_infos:+ sub_targets[r_dot_java_info.identifier + "_src"] = [+ DefaultInfo(+ default_output = r_dot_java_info.source_zipped,+ ),+ ]+ validation_outputs = list(native_library_info.validation_outputs)+ dex_java_packaging_deps = [+ packaging_dep for packaging_dep in java_packaging_deps if packaging_dep.dex and packaging_dep.dex.dex.owner.raw_target() not in no_dx_target_labels+ ]+ if should_pre_dex:+ pre_dexed_libs = [packaging_dep.dex for packaging_dep in dex_java_packaging_deps]+ if ctx.attrs.duplicate_class_checker_enabled:+ validation_outputs.append(+ check_for_duplicate_classes_for_pre_dexed_libs(+ ctx,+ {str(lib.class_names.owner.raw_target()): lib.class_names for lib in pre_dexed_libs if lib.dex},+ ),+ )+ if ctx.attrs.use_split_dex:+ dex_files_info = merge_to_split_dex(+ ctx,+ android_toolchain,+ pre_dexed_libs,+ get_split_dex_merge_config(ctx, android_toolchain),+ target_to_module_mapping_file,+ enable_bootstrap_dexes = ctx.attrs.enable_bootstrap_dexes,+ )+ else:+ dex_files_info = merge_to_single_dex(ctx, android_toolchain, pre_dexed_libs)+ else:+ jars_to_owners = {packaging_dep.jar: packaging_dep.jar.owner.raw_target() for packaging_dep in dex_java_packaging_deps}+ if ctx.attrs.duplicate_class_checker_enabled:+ validation_outputs.append(+ check_for_duplicate_classes_for_non_pre_dexed_jars(+ ctx,+ jars_to_owners,+ ),+ )++ if ctx.attrs.preprocess_java_classes_bash:+ jars_to_owners, preprocessed_java_classes_info = get_preprocessed_java_classes(enhancement_ctx, jars_to_owners)+ if preprocessed_java_classes_info:+ materialized_artifacts.append(preprocessed_java_classes_info.materialized_artifacts_dir)+ if has_proguard_config:+ additional_proguard_configs = (+ [resources_info.proguard_config_file] if not ctx.attrs.ignore_aapt_proguard_config and resources_info.proguard_config_file else []+ )++ no_dx_for_additional_jars = [no_dx for no_dx in ctx.attrs.no_dx if no_dx not in ctx.attrs.exclude_duplicate_targets_do_not_use]+ additional_jars = (+ android_toolchain.android_bootclasspath+ + android_toolchain.android_optional_jars+ + [no_dx[DefaultInfo].default_outputs[0] for no_dx in no_dx_for_additional_jars if len(no_dx[DefaultInfo].default_outputs) == 1]+ )++ proguard_output = get_proguard_output(+ ctx,+ jars_to_owners,+ java_packaging_deps,+ additional_proguard_configs,+ additional_jars,+ ctx.attrs.android_sdk_proguard_config,+ android_toolchain.proguard_config,+ android_toolchain.optimized_proguard_config,+ android_toolchain.proguard_jar,+ ctx.attrs.skip_proguard,+ )+ materialized_artifacts.extend(proguard_output.proguard_artifacts)+ jars_to_owners = proguard_output.jars_to_owners+ dir_srcs = {artifact.basename: artifact for artifact in proguard_output.proguard_artifacts}+ for i, hidden_artifact in enumerate(proguard_output.proguard_hidden_artifacts):+ dir_srcs["hidden/{}_{}".format(i, hidden_artifact.basename)] = hidden_artifact+ sub_targets["proguard_text_output"] = [+ DefaultInfo(+ default_output = ctx.actions.symlinked_dir(+ "proguard_text_output",+ dir_srcs,+ has_content_based_path = False,+ ),+ ),+ ]+ else:+ proguard_output = None++ if ctx.attrs.use_split_dex:+ dex_files_info = get_multi_dex(+ ctx,+ android_toolchain,+ jars_to_owners,+ ctx.attrs.primary_dex_patterns,+ proguard_output.proguard_configuration_output_file if proguard_output else None,+ proguard_output.proguard_mapping_output_file if proguard_output else None,+ is_optimized = has_proguard_config,+ apk_module_graph_file = target_to_module_mapping_file,+ enable_bootstrap_dexes = ctx.attrs.enable_bootstrap_dexes,+ multidex_min_api = ctx.attrs.multidex_min_api,+ )+ else:+ dex_files_info = get_single_primary_dex(+ ctx,+ android_toolchain,+ jars_to_owners.keys(),+ is_optimized = has_proguard_config,+ )++ sub_targets = sub_targets | enhancement_ctx.get_sub_targets()+ if resources_info.string_source_map:+ sub_targets["generate_string_resources"] = [DefaultInfo(default_output = resources_info.string_source_map)]++ if resources_info.voltron_string_source_map:+ sub_targets["generate_voltron_string_resources"] = [DefaultInfo(default_output = resources_info.voltron_string_source_map)]++ if dex_files_info.primary_dex_class_names:+ sub_targets["primary_dex_class_names"] = [DefaultInfo(default_output = dex_files_info.primary_dex_class_names)]++ return AndroidBinaryInfo(+ sub_targets = sub_targets,+ java_packaging_deps = java_packaging_deps,+ deps_by_platform = deps_by_platform,+ primary_platform = primary_platform,+ dex_files_info = dex_files_info,+ native_library_info = native_library_info,+ resources_info = resources_info,+ materialized_artifacts = materialized_artifacts,+ preprocessed_java_classes_info = preprocessed_java_classes_info,+ validation_outputs = validation_outputs,+ )++def get_build_config_java_libraries(+ ctx: AnalysisContext, build_config_infos: list[AndroidBuildConfigInfo], package_type: str, exopackage_modes: list[str]+) -> list[JavaPackagingInfo]:+ # BuildConfig deps should not be added for instrumented APKs because BuildConfig.class has+ # already been added to the APK under test.+ if package_type == "instrumented":+ return []++ build_config_constants = [+ BuildConfigField(type = "boolean", name = "DEBUG", value = str(package_type != "release").lower()),+ BuildConfigField(type = "boolean", name = "IS_EXOPACKAGE", value = str(len(exopackage_modes) > 0).lower()),+ BuildConfigField(type = "int", name = "EXOPACKAGE_FLAGS", value = str(get_exopackage_flags(exopackage_modes))),+ ]++ default_build_config_fields = get_build_config_fields(ctx.attrs.build_config_values)++ android_binary_values_file = (+ ctx.attrs.build_config_values_file[DefaultInfo].default_outputs[0]+ if isinstance(ctx.attrs.build_config_values_file, Dependency)+ else ctx.attrs.build_config_values_file+ )++ java_libraries = []+ java_packages_seen = []+ for build_config_info in build_config_infos:+ java_package = build_config_info.package+ expect(java_package not in java_packages_seen, "Got the same java_package {} for different AndroidBuildConfigs".format(java_package))+ java_packages_seen.append(java_package)++ all_build_config_values = {}+ for build_config_field in build_config_info.build_config_fields + default_build_config_fields + build_config_constants:+ all_build_config_values[build_config_field.name] = build_config_field++ values_file = android_binary_values_file if android_binary_values_file else build_config_info.values_file+ java_libraries.append(+ generate_android_build_config(+ ctx,+ java_package,+ java_package,+ True, # use_constant_expressions+ all_build_config_values.values(),+ values_file,+ )[1]+ )++ return java_libraries
@@ -0,0 +1,2927 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load(+ "@prelude//android:android_providers.bzl",+ "AndroidBinaryNativeLibsInfo",+ "AndroidPackageableInfo",+ "ExopackageNativeInfo",+ "PrebuiltNativeLibraryDir", # @unused Used as a type+)+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//android:cpu_filters.bzl", "CPU_FILTER_FOR_PRIMARY_PLATFORM", "CPU_FILTER_TO_ABI_DIRECTORY")+load(+ "@prelude//android:native_build_commands.bzl",+ "EMIT_NATIVE_BUILD_COMMANDS",+ "GATORADE_PHASE_SUBTARGETS",+ "NATIVE_BUILD_COMMAND_KINDS",+ "native_build_command_entry",+ "record_link_command",+)+load("@prelude//android:relinker_linker_outputs.bzl", "get_extra_relinker_args")+load("@prelude//android:util.bzl", "EnhancementContext", "merge_extra_linker_args")+load("@prelude//android:voltron.bzl", "ROOT_MODULE", "all_targets_in_root_module", "get_apk_module_graph_info", "is_root_module")+# @oss-disable[end= ]: load(+ # @oss-disable[end= ]: "@prelude//android/meta_only:gatorade.bzl",+ # @oss-disable[end= ]: "add_gatorade_relinker_args",+ # @oss-disable[end= ]: "early_gatorade_libraries",+ # @oss-disable[end= ]: "gatorade_deferred_libs",+ # @oss-disable[end= ]: "gatorade_libraries",+ # @oss-disable[end= ]: "is_late_gatorade_enabled",+ # @oss-disable[end= ]: "middle_gatorade_merge_args",+ # @oss-disable[end= ]: "relink_for_native_libs",+# @oss-disable[end= ]: )+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo", "PicBehavior")+load(+ "@prelude//cxx:link.bzl",+ "cxx_link_shared_library",+)+load("@prelude//cxx:link_types.bzl", "link_options")+load(+ "@prelude//cxx:symbols.bzl",+ "extract_defined_syms",+ "extract_undefined_syms",+)+load("@prelude//java:java_library.bzl", "compile_to_jar") # @unused+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference", "get_action_execution_attributes")+load(+ "@prelude//linking:link_info.bzl",+ "ArchiveLinkable",+ "LibOutputStyle",+ "LinkArgs",+ "LinkInfo",+ "LinkOrdering",+ "LinkedObject",+ "ObjectsLinkable",+ "SharedLibLinkable",+ "get_lib_output_style",+ "set_link_info_link_whole",+ "unpack_link_args",+ "wrap_link_info",+)+load(+ "@prelude//linking:linkable_graph.bzl",+ "LinkableGraph", # @unused Used as a type+ "LinkableNode", # @unused Used as a type+ "create_linkable_graph",+ "get_linkable_graph_node_map_func",+)+load(+ "@prelude//linking:shared_libraries.bzl",+ "SharedLibrary", # @unused Used as a type+ "SharedLibraryInfo", # @unused Used as a type+ "create_shlib",+ "get_strip_non_global_flags",+ "merge_shared_libraries",+ "traverse_shared_library_info",+ "with_unique_str_sonames",+)+load("@prelude//linking:strip.bzl", "strip_object")+load("@prelude//linking:types.bzl", "Linkage")+load("@prelude//utils:argfile.bzl", "argfile")+load("@prelude//utils:arglike.bzl", "ArgLike")+load("@prelude//utils:expect.bzl", "expect")+load("@prelude//utils:graph_utils.bzl", "post_order_traversal", "pre_order_traversal", "rust_matching_topological_traversal")+load("@prelude//utils:utils.bzl", "dedupe_by_value")++_GATORADE_PHASE_ORDER = ["early", "middle", "late"]++# Native libraries on Android are built for a particular Application Binary Interface (ABI). We+# package native libraries for one (or more, for multi-arch builds) ABIs into an Android APK.+#+# Our native libraries come from two sources:+# 1. "Prebuilt native library dirs", which are directory artifacts whose sub-directories are ABIs,+# and those ABI subdirectories contain native libraries. These come from `android_prebuilt_aar`s+# and `prebuilt_native_library`s, for example.+# 2. "Native linkables". These are each a single shared library - `.so`s for one particular ABI.+#+# Native libraries can be packaged into Android APKs in two ways.+# 1. As native libraries. This means that they are passed to the APK builder as native libraries,+# and the APK builder will package `<ABI>/library.so` into the APK at `libs/<ABI>/library.so`.+# 2. As assets. These are passed to the APK build as assets, and are stored at+# `assets/lib/<ABI>/library.so` In the root module, we only package a native library as an+# asset if it is eligible to be an asset (e.g. `can_be_asset` on a `cxx_library`), and+# `package_asset_libraries` is set to True for the APK. We create a metadata file at+# `assets/libs/metadata.txt` that has a single line entry for each packaged asset consisting of+# '<ABI/library_name> <file_size> <sha256>'.+#+# Native libraries that are not part of the root module (i.e. it is part of some other Voltron+# module) are controlled by `package_voltron_asset_libraries` and `can_be_asset` flags.+# Similarly, the metadata for each module is stored at `assets/<module_name>/libs.txt`.++def _merged_lib_provided_by_apk_under_test(merged_lib, shared_libraries_to_exclude: set) -> bool:+ # True when every primary constituent of a merged library is provided by the+ # apk-under-test, so the instrumentation APK can drop its own copy and resolve+ # the library at runtime from the apk-under-test instead.+ if not shared_libraries_to_exclude or not merged_lib.primary_constituents:+ return False+ for constituent in merged_lib.primary_constituents:+ if constituent.raw_target() not in shared_libraries_to_exclude:+ return False+ return True++def _register_gatorade_phase_evidence(+ enhance_ctx: EnhancementContext,+ platforms: list[str],+ native_library_merge_dir: Artifact | None,+ middle_gatorade_products: Artifact | None,+ unstripped_native_libraries_files: Artifact,+ relinked_libs_output: Artifact | None,+ defer_relink: bool,+) -> None:+ ctx = enhance_ctx.ctx+ configured = getattr(ctx.attrs, "gatorade_phases", [])+ configured_phases = [phase for phase in _GATORADE_PHASE_ORDER if phase in configured]+ phase_outputs = {}+ phase_dependencies = {}+ if "early" in configured_phases and native_library_merge_dir != None:+ phase_outputs["early"] = native_library_merge_dir+ phase_dependencies["early"] = "merge_sequence"+ if "middle" in configured_phases and middle_gatorade_products != None:+ phase_outputs["middle"] = middle_gatorade_products+ phase_dependencies["middle"] = "middle_products"+ if "late" in configured_phases:+ phase_outputs["late"] = relinked_libs_output if defer_relink else unstripped_native_libraries_files+ phase_dependencies["late"] = "relinked_libraries" if defer_relink else "final_unstripped_libraries"+ if not phase_outputs:+ return++ evidence = ctx.actions.declare_output(+ "gatorade_phase_evidence.json",+ has_content_based_path = False,+ )+ # Preserve the associated inputs so building this manifest also materializes+ # the phase products it certifies.+ evidence_inputs = ctx.actions.write_json(+ evidence,+ {+ "configured_phases": configured_phases,+ "defer_relink": defer_relink,+ "engaged_phases": [phase for phase in _GATORADE_PHASE_ORDER if phase in phase_outputs],+ "phase_dependencies": phase_dependencies,+ "phase_outputs": phase_outputs,+ "platforms": sorted(platforms),+ "schema_version": 1,+ "target": str(ctx.label.raw_target()),+ },+ pretty = True,+ with_inputs = True,+ )+ enhance_ctx.debug_output(+ "gatorade_phase_evidence",+ evidence,+ other_outputs = [evidence_inputs],+ )++def _materialize_middle_gatorade_products(+ ctx: AnalysisContext,+ output,+ products_by_platform: dict[str, Artifact],+ relinked_libraries_by_platform: dict[str, dict[str, SharedLibrary]],+) -> None:+ entries = {}+ for platform in sorted(products_by_platform):+ entries["{}/products".format(platform)] = products_by_platform[platform]+ relinked_libraries = relinked_libraries_by_platform[platform]+ for soname in sorted(relinked_libraries):+ entries["{}/relinked/{}".format(platform, soname)] = relinked_libraries[soname].lib.output+ ctx.actions.symlinked_dir(output, entries)++def get_android_binary_native_library_info(+ enhance_ctx: EnhancementContext,+ android_packageable_info: AndroidPackageableInfo,+ deps_by_platform: dict[str, list[Dependency]],+ apk_module_graph_file: Artifact | None = None,+ prebuilt_native_library_dirs_to_exclude: set[TargetLabel] = set(),+ shared_libraries_to_exclude: set[TargetLabel] = set(),+ native_library_merge_sequence: list | None = None,+ native_library_merge_glue: dict | None = None,+ native_library_merge_map: dict | None = None,+ native_library_merge_non_asset_libs: bool = False,+ native_library_merge_linker_args: dict | None = None,+ native_library_merge_linker_args_all: list | None = None,+ native_library_merge_code_generator: Dependency | None = None,+ native_library_merge_sequence_blocklist: list | None = None,+) -> AndroidBinaryNativeLibsInfo:+ ctx = enhance_ctx.ctx++ traversed_prebuilt_native_library_dirs = (+ android_packageable_info.prebuilt_native_library_dirs.traverse() if android_packageable_info.prebuilt_native_library_dirs else []+ )+ all_prebuilt_native_library_dirs = [+ native_lib for native_lib in traversed_prebuilt_native_library_dirs if native_lib.raw_target not in prebuilt_native_library_dirs_to_exclude+ ]++ included_shared_lib_targets = []+ original_shared_libs_by_platform = {} # dict[str, dict[str (soname), list[SharedLibrary]]]+ for platform, deps in deps_by_platform.items():+ if platform == CPU_FILTER_FOR_PRIMARY_PLATFORM and platform not in ctx.attrs.cpu_filters and len(ctx.attrs.cpu_filters) != 0:+ continue++ shared_libs = get_default_shared_libs(ctx, deps, shared_libraries_to_exclude)+ included_shared_lib_targets.extend([lib.label.raw_target() for lib in shared_libs.values()])+ original_shared_libs_by_platform[platform] = shared_libs++ if not all_prebuilt_native_library_dirs and not included_shared_lib_targets:+ enhance_ctx.debug_output("native_libs", ctx.actions.write("native_libs", [], has_content_based_path = False))+ enhance_ctx.debug_output("linker_argsfiles", ctx.actions.symlinked_dir("linker_argsfiles", {}, has_content_based_path = False))+ enhance_ctx.debug_output("linker_commands", ctx.actions.write("linker_commands", [], has_content_based_path = False))+ enhance_ctx.debug_output(+ "native_build_commands",+ ctx.actions.write_json("native_build_commands", [], has_content_based_path = False),+ # Expose the same empty per-kind filter sub_targets as the main path so+ # TARGET[native_build_commands][<kind>] resolves uniformly (to empty JSON) even on+ # apps with no native libraries.+ sub_targets = {+ kind: [DefaultInfo(default_outputs = [ctx.actions.write_json("native_build_commands.{}.json".format(kind), [], has_content_based_path = False)])]+ for kind in NATIVE_BUILD_COMMAND_KINDS+ },+ )+ # The top-level Gatorade-phase sub-targets output that phase's produced artifacts (an empty+ # dir here: an app with no native libraries runs no Gatorade phase), so they resolve+ # uniformly. See the main path for the populated case.+ for gatorade_phase in GATORADE_PHASE_SUBTARGETS:+ enhance_ctx.debug_output(gatorade_phase, ctx.actions.symlinked_dir(gatorade_phase, {}, has_content_based_path = False))+ enhance_ctx.debug_output("unstripped_native_libraries", ctx.actions.write("unstripped_native_libraries", [], has_content_based_path = False))+ enhance_ctx.debug_output(+ "unstripped_native_libraries_json", ctx.actions.write_json("unstripped_native_libraries_json", {}, has_content_based_path = False)+ )+ enhance_ctx.debug_output(+ "unstripped_native_libraries_files", ctx.actions.symlinked_dir("unstripped_native_libraries_files", {}, has_content_based_path = False)+ )+ enhance_ctx.debug_output("relinker_extra_outputs", ctx.actions.symlinked_dir("relinker_extra_outputs", {}, has_content_based_path = False))+ return AndroidBinaryNativeLibsInfo(+ prebuilt_native_library_dirs = [],+ shared_libraries = [],+ native_libs_for_primary_apk = [],+ exopackage_info = None,+ root_module_native_lib_assets = [],+ non_root_module_native_lib_assets = [],+ generated_java_code = [],+ unstripped_shared_libraries = None,+ validation_outputs = [],+ )++ native_libs = ctx.actions.declare_output("native_libs_symlink", has_content_based_path = False)+ native_libs_metadata = ctx.actions.declare_output("native_libs_metadata_symlink", has_content_based_path = False)+ native_libs_always_in_primary_apk = ctx.actions.declare_output("native_libs_always_in_primary_apk_symlink", has_content_based_path = False)+ native_lib_assets_for_primary_apk = ctx.actions.declare_output("native_lib_assets_for_primary_apk_symlink", has_content_based_path = False)+ stripped_native_linkable_assets_for_primary_apk = ctx.actions.declare_output(+ "stripped_native_linkable_assets_for_primary_apk_symlink", has_content_based_path = False+ )+ root_module_metadata_assets = ctx.actions.declare_output("root_module_metadata_assets_symlink", has_content_based_path = False)+ non_root_module_metadata_assets = ctx.actions.declare_output("non_root_module_metadata_assets_symlink", has_content_based_path = False)+ non_root_module_lib_assets = ctx.actions.declare_output("non_root_module_lib_assets_symlink", has_content_based_path = False)++ linker_argsfiles = ctx.actions.declare_output("linker_argsfiles", dir = True, has_content_based_path = False)+ linker_commands = ctx.actions.declare_output("linker_commands", has_content_based_path = False)+ unstripped_native_libraries = ctx.actions.declare_output("unstripped_native_libraries", has_content_based_path = False)+ unstripped_native_libraries_json = ctx.actions.declare_output("unstripped_native_libraries_json", has_content_based_path = False)+ unstripped_native_libraries_files = ctx.actions.declare_output("unstripped_native_libraries.links", dir = True, has_content_based_path = False)++ dynamic_outputs = [+ native_libs,+ native_libs_metadata,+ native_libs_always_in_primary_apk,+ native_lib_assets_for_primary_apk,+ linker_argsfiles,+ linker_commands,+ unstripped_native_libraries,+ unstripped_native_libraries_json,+ unstripped_native_libraries_files,+ stripped_native_linkable_assets_for_primary_apk,+ root_module_metadata_assets,+ non_root_module_metadata_assets,+ non_root_module_lib_assets,+ ]++ # [native_build_commands] outputs. `native_build_commands` (full) + the per-kind filters are+ # produced by a final combine action (see below) that merges two fragments: the "base" fragment+ # (all commands known by the end of the outer dynamic lambda) and the late-Gatorade "codegen"+ # fragment. The codegen commands (clang --codegen-library) are constructed inside a NESTED+ # Gatorade dynamic that runs after the outer lambda, so they cannot be folded in by the outer+ # lambda directly and instead flow through this fragment + combine.+ native_build_commands = ctx.actions.declare_output("native_build_commands.json", has_content_based_path = False)+ native_build_commands_by_kind = {+ kind: ctx.actions.declare_output("native_build_commands.{}.json".format(kind), has_content_based_path = False) for kind in NATIVE_BUILD_COMMAND_KINDS+ }+ native_build_commands_base = ctx.actions.declare_output("native_build_commands.base.json", has_content_based_path = False)+ native_build_commands_codegen = ctx.actions.declare_output("native_build_commands.late_gatorade_codegen.json", has_content_based_path = False)+ dynamic_outputs.append(native_build_commands_base)++ fake_input = ctx.actions.write("dynamic.trigger", "", has_content_based_path = False)++ # some cases don't actually need to use a dynamic_output, but it's simplest to consistently use it anyway. we need some fake input to allow that.+ dynamic_inputs = [fake_input]+ if apk_module_graph_file:+ dynamic_inputs.append(apk_module_graph_file)+ split_groups_map = None+ native_library_merge_dir = None+ native_merge_debug = None+ generated_java_code = []++ glue_linkables = None+ if native_library_merge_glue:+ glue_linkables = {}+ for platform, glue in native_library_merge_glue.items():+ glue_link_graph = glue.get(LinkableGraph)+ expect(glue_link_graph != None, "native_library_merge_glue (`{}`) should be a linkable target", glue.label)+ glue_linkable = glue_link_graph.nodes.value.linkable+ expect(glue_linkable != None, "native_library_merge_glue (`{}`) should be a linkable target", glue.label)+ expect(glue_linkable.preferred_linkage == Linkage("static"), "buck2 currently only supports preferred_linkage='static' native_library_merge_glue")+ glue_linkables[platform] = (glue.label, glue_linkable.link_infos[LibOutputStyle("pic_archive")].default)++ linkable_nodes_by_platform = {}++ # Analysis-scope [native_build_commands] entries (e.g. compute_mergemap) that run before the+ # dynamic lambda. The lambda seeds its own list from a copy of this, then appends the+ # in-lambda link/bolt commands. Entries created inside the frozen lambda cannot be appended+ # here, so anything produced at analysis time is collected into this list instead.+ native_build_command_entries = []++ # TARGET[<phase>] Gatorade-phase product sub-targets. Each outputs the full set of artifacts that+ # phase's gatorade invocation(s) produce, as a symlinked_dir (like [native_libs]).+ # - early runs at analysis scope: early_gatorade_libraries fills this {relpath: artifact} map,+ # and early_gatorade_products is built from it below.+ # - middle reuses middle_gatorade_products, declared below and materialized inside the dynamic+ # lambda when the middle phase runs.+ # - late runs inside the nested Gatorade dynamics, so its dir is declared here, appended to+ # dynamic_outputs, and bound inside (empty when the phase is off).+ early_gatorade_product_mapping = {}+ late_gatorade_products = ctx.actions.declare_output("late_gatorade_products", dir = True, has_content_based_path = False)+ dynamic_outputs.append(late_gatorade_products)++ has_native_merging = native_library_merge_sequence or native_library_merge_map+ enable_relinker = getattr(ctx.attrs, "enable_relinker", False)+ defer_relink = getattr(ctx.attrs, "defer_relink", False) and enable_relinker++ middle_gatorade_products = None+ if enable_relinker and "middle" in getattr(ctx.attrs, "gatorade_phases", []):+ middle_gatorade_products = ctx.actions.declare_output(+ "middle_gatorade_products",+ dir = True,+ has_content_based_path = False,+ )+ dynamic_outputs.append(middle_gatorade_products)++ # The outer lambda owns the codegen fragment. With late Gatorade, the nested Gatorade dynamic+ # (gatorade_libraries or gatorade_deferred_libs) binds it through the passed OutputArtifact;+ # otherwise the outer lambda binds it with an empty list, so the combine always has both inputs.+ # @oss-disable[end= ]: will_capture_late_gatorade_codegen = is_late_gatorade_enabled(ctx)+ will_capture_late_gatorade_codegen = False # @oss-enable+ dynamic_outputs.append(native_build_commands_codegen)++ if has_native_merging or enable_relinker:+ native_merge_debug = ctx.actions.declare_output("native_merge_debug", dir = True, has_content_based_path = False)+ dynamic_outputs.append(native_merge_debug)++ # Argsfiles referenced by [native_build_commands][compile] entries, attached as other_outputs+ # below. Keyed by the Artifact, not short_path: short_path is only the extension-based filename+ # (e.g. `.cpp.cxx_compile_argsfile`), identical across every library and platform.+ compile_argsfiles = {}++ # EMIT_NATIVE_BUILD_COMMANDS also needs the node map (compile entries read each node's+ # compile_cmds), so compile capture works on apps that neither merge nor relink.+ if has_native_merging or enable_relinker or EMIT_NATIVE_BUILD_COMMANDS:+ # We serialize info about the linkable graph and the apk module mapping and pass that to an+ # external subcommand to apply a merge sequence algorithm and return us the merge mapping.+ for platform, deps in deps_by_platform.items():+ if platform == CPU_FILTER_FOR_PRIMARY_PLATFORM and platform not in ctx.attrs.cpu_filters and len(ctx.attrs.cpu_filters) != 0:+ continue+ linkable_graph = create_linkable_graph(ctx, deps = deps)+ graph_node_map = get_linkable_graph_node_map_func(linkable_graph)()+ linkables_debug = ctx.actions.write("linkables." + platform, list(graph_node_map.keys()), has_content_based_path = False)+ enhance_ctx.debug_output("linkables." + platform, linkables_debug)+ linkable_nodes_by_platform[platform] = graph_node_map+ if EMIT_NATIVE_BUILD_COMMANDS:+ for node in graph_node_map.values():+ for cc in node.compile_cmds:+ compile_argsfiles[cc.cxx_compile_cmd.argsfile.file] = None++ jni_onload_check_report = None+ if has_native_merging and ctx.attrs._android_toolchain[AndroidToolchainInfo].jni_onload_check:+ jni_onload_check_report = ctx.actions.declare_output("jni_onload_check.json", has_content_based_path = False)+ dynamic_outputs.append(jni_onload_check_report)++ relinked_libs_output = None+ relinked_libs_manifest = None+ if defer_relink:+ relinked_libs_output = ctx.actions.declare_output("relinked_libs", dir = True)+ relinked_libs_manifest = ctx.actions.declare_output("relinked_libs_manifest.json")+ dynamic_outputs.append(relinked_libs_output)+ dynamic_outputs.append(relinked_libs_manifest)++ # Aggregate of every native library before the relinker's dead-code-stripping+ # pass, exposed as the [unrelinked_libs] sub-target (the pre-relink counterpart+ # of [relinked_libs]). Only the relinker produces an unrelinked vs relinked+ # distinction, so this only exists when relinking is enabled.+ unrelinked_libs_output = None+ if enable_relinker:+ unrelinked_libs_output = ctx.actions.declare_output("unrelinked_libs", dir = True)+ dynamic_outputs.append(unrelinked_libs_output)++ # The `extra_relinker_outputs` of every relinked library, as+ # <type>/<abi>/<soname>/<file>, exposed as the [relinker_extra_outputs] sub-target so+ # they can be built (and so put on disk) without knowing their paths. Always+ # present; empty when nothing is configured or nothing is relinked.+ relinker_extra_outputs = ctx.actions.declare_output("relinker_extra_outputs", dir = True, has_content_based_path = False)+ dynamic_outputs.append(relinker_extra_outputs)++ lib_outputs_by_platform = _declare_library_subtargets(+ ctx, dynamic_outputs, original_shared_libs_by_platform, native_library_merge_map, native_library_merge_sequence, enable_relinker+ )++ if native_library_merge_sequence:+ native_library_merge_input_file = ctx.actions.write_json(+ "mergemap.input",+ {+ "linkable_graphs_by_platform": encode_linkable_graph_for_mergemap(linkable_nodes_by_platform),+ "native_library_merge_sequence": native_library_merge_sequence,+ "native_library_merge_sequence_blocklist": native_library_merge_sequence_blocklist or [],+ },+ has_content_based_path = False,+ )++ if not "early" in getattr(ctx.attrs, "gatorade_phases", []):+ mergemap_cmd = cmd_args(ctx.attrs._android_toolchain[AndroidToolchainInfo].mergemap_tool)+ mergemap_cmd.add(cmd_args(native_library_merge_input_file, format = "--mergemap-input={}"))+ if apk_module_graph_file:+ mergemap_cmd.add(cmd_args(apk_module_graph_file, format = "--apk-module-graph={}"))+ if native_library_merge_non_asset_libs:+ mergemap_cmd.add(cmd_args("--merge-non-asset-libs"))+ native_library_merge_dir = ctx.actions.declare_output("merge_sequence_output", has_content_based_path = False)+ native_library_merge_map = native_library_merge_dir.project("merge.map")+ split_groups_map = native_library_merge_dir.project("split_groups.map")++ # Record the mergemap command before adding the output as an `as_output()` (which+ # cannot be re-serialized by write_json); reference the plain output artifact instead.+ native_build_command_entries.append(+ native_build_command_entry(+ kind = "mergemap",+ category = "compute_mergemap",+ arch = None,+ soname = None,+ output = native_library_merge_dir.short_path,+ argv = cmd_args(mergemap_cmd, cmd_args(native_library_merge_dir, format = "--output={}")),+ )+ )++ ctx.actions.run(+ cmd_args(mergemap_cmd, cmd_args(native_library_merge_dir.as_output(), format = "--output={}")),+ category = "compute_mergemap",+ allow_cache_upload = True,+ )+ else:+ native_library_merge_dir = ctx.actions.declare_output("merge_sequence_output", dir = True, has_content_based_path = False)+ native_library_merge_map = native_library_merge_dir.project("merge.map")+ split_groups_map = native_library_merge_dir.project("split_groups.map")++ # Pass all merge sequence arguments to early_gatorade_libraries+ # which will handle running either Python or C++ implementation+ # Prevent Buildifier from moving comments in a way that breaks things.+ args = [+ ctx,+ original_shared_libs_by_platform,+ linkable_nodes_by_platform,+ native_library_merge_input_file,+ apk_module_graph_file,+ native_library_merge_non_asset_libs,+ native_library_merge_dir,+ # @oss-disable[end= ]: native_build_command_entries,+ # @oss-disable[end= ]: early_gatorade_product_mapping,+ ]+ # @oss-disable[end= ]: early_gatorade_libraries(*args)++ enhance_ctx.debug_output("compute_merge_sequence", native_library_merge_dir)++ dynamic_inputs.append(native_library_merge_map)+ dynamic_inputs.append(split_groups_map)++ mergemap_gencode_jar = None++ if has_native_merging and native_library_merge_code_generator:+ mergemap_gencode_jar = ctx.actions.declare_output("MergedLibraryMapping.jar", has_content_based_path = False)+ dynamic_outputs.append(mergemap_gencode_jar)+ generated_java_code.append(mergemap_gencode_jar)++ def dynamic_native_libs_info(ctx: AnalysisContext, artifacts, outputs):+ middle_gatorade_outputs_by_platform = {}+ middle_gatorade_relinked_libraries_by_platform = {}+ # Seed with the analysis-scope entries (frozen list, read-only copy), then append the+ # in-lambda link/relink/merge/bolt commands as the pipeline produces them.+ native_cmd_entries = list(native_build_command_entries)+ get_module_from_target = all_targets_in_root_module+ get_module_tdeps = all_targets_in_root_module+ get_calculated_module_deps = all_targets_in_root_module+ get_deps_debug_data = None+ if apk_module_graph_file:+ apk_module_graph = get_apk_module_graph_info(ctx, apk_module_graph_file, artifacts)+ get_module_from_target = apk_module_graph.target_to_module_mapping_function+ get_module_tdeps = apk_module_graph.transitive_module_deps_function+ get_calculated_module_deps = apk_module_graph.calculated_deps_function+ get_deps_debug_data = apk_module_graph.get_deps_debug_data++ split_groups = None+ merged_shared_lib_targets_by_platform = {} # dict[str, dict[Label, str]]+ if has_native_merging:+ native_library_merge_debug_outputs = {}++ # When changing this dynamic_output, the workflow is a lot better if you compute the module graph once and+ # then set it as the binary's precomputed_apk_module_graph attr.+ if native_library_merge_sequence:+ merge_map_by_platform = artifacts[native_library_merge_map].read_json()+ split_groups = artifacts[split_groups_map].read_json()+ native_library_merge_debug_outputs["merge_sequence_output"] = native_library_merge_dir+ elif native_library_merge_map:+ merge_map_by_platform = {}+ for platform, linkable_nodes in linkable_nodes_by_platform.items():+ merge_map = merge_map_by_platform.setdefault(platform, {})+ merge_lib_to_fancy_regexes = {+ merge_lib: [regex(pattern, fancy = True) for pattern in patterns] for merge_lib, patterns in native_library_merge_map.items()+ }+ for target, _node in linkable_nodes.items():+ raw_target = str(target.raw_target())+ merge_result = None+ for merge_lib, fancy_regexes in merge_lib_to_fancy_regexes.items():+ for fancy_regex in fancy_regexes:+ if fancy_regex.match(raw_target):+ merge_result = merge_lib+ break+ if merge_result:+ break+ if merge_result:+ merge_map[str(target)] = merge_result+ merge_map = ctx.actions.write_json("merge.map", merge_map_by_platform, pretty = True, has_content_based_path = False)+ native_library_merge_debug_outputs["merge_map_output"] = merge_map+ else:+ fail("unreachable")++ shared_object_targets = {}+ debug_info_by_platform = {} # dict[str, MergedLinkablesDebugInfo]+ merged_shared_libs_by_platform = {} # dict[str, dict[str, MergedSharedLibrary]]+ jni_onload_check_inputs = [] if jni_onload_check_report else None+ for platform in original_shared_libs_by_platform:+ merged_shared_libs, debug_info = _get_merged_linkables_for_platform(+ ctx = ctx,+ cxx_toolchain = ctx.attrs._cxx_toolchain[platform][CxxToolchainInfo],+ platform = platform if len(original_shared_libs_by_platform) > 1 else None,+ native_library_merge_linker_args_all = native_library_merge_linker_args_all,+ glue_linkable = glue_linkables[platform] if glue_linkables else None,+ default_shared_libs = original_shared_libs_by_platform[platform],+ linkable_nodes = linkable_nodes_by_platform[platform],+ merge_map = merge_map_by_platform[platform],+ merge_linker_args = native_library_merge_linker_args or {},+ apk_module_graph = get_module_from_target,+ jni_onload_check_inputs = jni_onload_check_inputs,+ )+ debug_info_by_platform[platform] = debug_info+ merged_shared_libs_by_platform[platform] = merged_shared_libs+ merged_shared_lib_targets = {}+ for soname, lib in merged_shared_libs.items():+ shared_object_targets[soname] = [str(target.raw_target()) for target in lib.primary_constituents]++ for target in lib.primary_constituents:+ merged_shared_lib_targets[target] = soname+ merged_shared_lib_targets_by_platform[platform] = merged_shared_lib_targets++ debug_data_json = ctx.actions.write_json("native_merge_debug.json", debug_info_by_platform, pretty = True, has_content_based_path = False)+ native_library_merge_debug_outputs["native_merge_debug.json"] = debug_data_json++ shared_object_targets_lines = ""+ for soname, targets in shared_object_targets.items():+ shared_object_targets_lines += soname + " " + " ".join(targets) + "\n"+ shared_object_targets_txt = ctx.actions.write("shared_object_targets.txt", shared_object_targets_lines, has_content_based_path = False)+ native_library_merge_debug_outputs["shared_object_targets.txt"] = shared_object_targets_txt++ if mergemap_gencode_jar:+ merged_library_map = write_merged_library_map(ctx, merged_shared_libs_by_platform)+ mergemap_gencode = run_mergemap_codegen(ctx, native_library_merge_code_generator, merged_library_map)+ compile_to_jar(ctx, [mergemap_gencode], output = outputs[mergemap_gencode_jar])+ native_library_merge_debug_outputs["NativeLibraryMergeGeneratedCode.java"] = mergemap_gencode+ native_library_merge_debug_outputs["merged_library_map.txt"] = merged_library_map+ native_library_merge_debug_outputs["mergemap_gencode.jar"] = mergemap_gencode_jar++ # Write the JNI_OnLoad mappings file (merged SO name -> constituent targets)+ jni_on_load_mappings = write_jni_on_load_mappings(ctx, merged_shared_libs_by_platform)+ native_library_merge_debug_outputs["jni_on_load_mappings.txt"] = jni_on_load_mappings++ ctx.actions.symlinked_dir(outputs[native_merge_debug], native_library_merge_debug_outputs)++ if jni_onload_check_report:+ # nm is the same across the android platforms in a binary, so+ # any of them serves for a symbol-table read.+ check_platform = list(original_shared_libs_by_platform.keys())[0]+ _run_jni_onload_check(+ ctx,+ ctx.attrs._cxx_toolchain[check_platform][CxxToolchainInfo],+ jni_onload_check_inputs,+ outputs[jni_onload_check_report],+ )++ # Merged libraries are assembled from the full linkable graph, so unlike the+ # non-merging path (which filters via get_default_shared_libs) they do not+ # otherwise honor shared_libraries_to_exclude. Drop any merged library whose+ # primary constituents are all provided by the apk-under-test: re-emitting it+ # would ship a duplicate merged .so that loads alongside the apk-under-test's+ # copy in the instrumentation process and re-runs its link_whole static+ # initializers. shared_libraries_to_exclude is empty for non-instrumentation+ # binaries, so this is a no-op there.+ final_shared_libs_by_platform = {+ platform: {+ soname: d.lib for soname, d in merged_shared_libs.items() if not _merged_lib_provided_by_apk_under_test(d, shared_libraries_to_exclude)+ }+ for platform, merged_shared_libs in merged_shared_libs_by_platform.items()+ }+ elif enable_relinker:+ final_shared_libs_by_platform, native_library_merge_debug_outputs = _create_all_relinkable_links(+ ctx,+ original_shared_libs_by_platform,+ linkable_nodes_by_platform,+ )+ ctx.actions.symlinked_dir(outputs[native_merge_debug], native_library_merge_debug_outputs)++ else:+ final_shared_libs_by_platform = original_shared_libs_by_platform++ relinked_libs_for_extra_outputs = {}++ # [native_build_commands][merge]: record every per-soname merge link here, once, before any+ # relink reassigns final_shared_libs_by_platform. This is the single capture point for merge+ # links across all paths (inline relink, deferred relink, and late-Gatorade), which is why+ # the finalization step below never labels anything kind=merge.+ if has_native_merging:+ for platform, libs in final_shared_libs_by_platform.items():+ for soname, lib in libs.items():+ record_link_command(native_cmd_entries, "merge", platform, soname, lib.lib)++ # [native_build_commands][compile]: emit one entry per source in every linkable node that+ # carries compile commands (populated only when `-c cxx.emit_native_build_commands=true`, so+ # this whole block is skipped otherwise). Attribute each to the FINAL merged soname via the+ # merge map (falling back to the node's own pre-merge soname), keeping the per-library soname+ # in pre_merge_soname. The soname is best-effort: split groups, static-only nodes, and+ # late-gatorade code motion make it approximate — consumers should cross-reference merge.map.+ if EMIT_NATIVE_BUILD_COMMANDS:+ for platform, node_map in linkable_nodes_by_platform.items():+ merged_by_label = merged_shared_lib_targets_by_platform.get(platform, {})+ for node_label, node in node_map.items():+ pre_merge_soname = node.default_soname+ for cc in node.compile_cmds:+ # A source compiled more than once in the same node (different flavors/flags)+ # carries a non-None index; append it so those entries get distinct identifiers.+ identifier = "{}/{}/{}".format(platform, node_label.raw_target(), cc.src.short_path)+ if cc.index != None:+ identifier += "/{}".format(cc.index)+ native_cmd_entries.append(+ native_build_command_entry(+ kind = "compile",+ category = cc.cxx_compile_cmd.category,+ arch = platform,+ soname = merged_by_label.get(node_label, pre_merge_soname),+ pre_merge_soname = pre_merge_soname,+ output = cc.src.short_path,+ argv = cmd_args(cc.cxx_compile_cmd.base_compile_cmd, cc.cxx_compile_cmd.argsfile.cmd_form, cc.args),+ argsfile = cc.cxx_compile_cmd.argsfile.file,+ identifier = identifier,+ )+ )++ if enable_relinker and not defer_relink:+ unrelinked_shared_libs_by_platform = final_shared_libs_by_platform+ final_shared_libs_by_platform, middle_gatorade_outputs_by_platform = _relink_for_native_libs(ctx, final_shared_libs_by_platform, native_cmd_entries)+ middle_gatorade_relinked_libraries_by_platform = final_shared_libs_by_platform+ relinked_libs_for_extra_outputs = final_shared_libs_by_platform+ _link_library_subtargets(+ ctx,+ outputs,+ lib_outputs_by_platform,+ original_shared_libs_by_platform,+ unrelinked_shared_libs_by_platform,+ merged_shared_lib_targets_by_platform,+ split_groups,+ native_merge_debug,+ unrelinked = True,+ )+ _write_native_libs_dir_and_manifest(+ ctx,+ unrelinked_shared_libs_by_platform,+ outputs[unrelinked_libs_output],+ None,+ stripped = False,+ )++ if defer_relink:+ # Run relinking as separate actions that can execute in parallel with other build steps.+ # The relinked libs are exposed as [relinked_libs] sub-target for the combine genrule.+ # A JSON manifest listing the <abi>/<soname> entries is produced alongside so that+ # the combine script knows exactly which libraries to replace without guessing.+ relinked_libs_by_platform, middle_gatorade_outputs_by_platform = _relink_for_native_libs(ctx, final_shared_libs_by_platform, native_cmd_entries)+ middle_gatorade_relinked_libraries_by_platform = relinked_libs_by_platform+ relinked_libs_for_extra_outputs = relinked_libs_by_platform++ if False: # @oss-enable+ # @oss-disable[end= ]: if is_late_gatorade_enabled(ctx):+ # Run Gatorade cross-library optimization + codegen + re-link on+ # the deferred relinked libs. The callback writes the final+ # Gatorade-processed libs to the relinked_libs_output artifacts.+ def deferred_gatorade_output(ctx, gatorade_libs_by_platform, dyn_outputs):+ _write_native_libs_dir_and_manifest(+ ctx, gatorade_libs_by_platform, dyn_outputs[relinked_libs_output], dyn_outputs[relinked_libs_manifest], stripped = True+ )++ # @oss-disable[end= ]: gatorade_deferred_libs(+ # @oss-disable[end= ]: ctx,+ # @oss-disable[end= ]: relinked_libs_by_platform,+ # @oss-disable[end= ]: deferred_gatorade_output,+ # @oss-disable[end= ]: [outputs[relinked_libs_output], outputs[relinked_libs_manifest]],+ # @oss-disable[end= ]: native_cmd_entries,+ # @oss-disable[end= ]: outputs[native_build_commands_codegen],+ # @oss-disable[end= ]: outputs[late_gatorade_products],+ # @oss-disable[end= ]: )+ else:+ _write_native_libs_dir_and_manifest(+ ctx, relinked_libs_by_platform, outputs[relinked_libs_output], outputs[relinked_libs_manifest], stripped = True+ )++ # Bind unrelinked subtarget outputs (same as final since we skipped inline relinking)+ _link_library_subtargets(+ ctx,+ outputs,+ lib_outputs_by_platform,+ original_shared_libs_by_platform,+ final_shared_libs_by_platform,+ merged_shared_lib_targets_by_platform,+ split_groups,+ native_merge_debug,+ unrelinked = True,+ )+ _write_native_libs_dir_and_manifest(+ ctx,+ final_shared_libs_by_platform,+ outputs[unrelinked_libs_output],+ None,+ stripped = False,+ )++ if middle_gatorade_products != None:+ _materialize_middle_gatorade_products(+ ctx,+ outputs[middle_gatorade_products],+ middle_gatorade_outputs_by_platform,+ middle_gatorade_relinked_libraries_by_platform,+ )++ if ctx.attrs._android_toolchain[AndroidToolchainInfo].cross_module_native_deps_check and (has_native_merging or enable_relinker):+ # note: can only detect these if linkable_nodes_by_platform is created, ie. if using relinker or merging.+ # EMIT_NATIVE_BUILD_COMMANDS also builds it on apps that do neither; those apps never ran+ # this check, so it stays gated on merging/relinking.+ cross_module_link_errors = []+ for linkable_nodes in linkable_nodes_by_platform.values():+ for target, node in linkable_nodes.items():+ node_target = str(target.raw_target())+ node_module = get_module_from_target(node_target)+ for dep in node.deps:+ dep_target = str(dep.raw_target())+ dep_module = get_module_from_target(dep_target)+ if (+ not is_root_module(dep_module)+ and node_module != dep_module+ and dep_module not in get_module_tdeps(node_module)+ and dep_module not in get_calculated_module_deps(node_module)+ ):+ cross_module_link_errors.append("{} (module: {}) -> {} (module: {}) ".format(node_target, node_module, dep_target, dep_module))++ if cross_module_link_errors:+ cross_module_link_errors.append(get_deps_debug_data())+ fail(+ "Native libraries in modules should only depend on libraries in the same module or the root. Remove these deps:\n"+ + "\n".join(cross_module_link_errors)+ )++ _write_relinker_extra_outputs_dir(ctx, relinked_libs_for_extra_outputs, outputs[relinker_extra_outputs])++ native_lib_dynamic_outputs = {+ "linker_argsfiles": outputs[linker_argsfiles],+ "linker_commands": outputs[linker_commands],+ "native_lib_assets_for_primary_apk": outputs[native_lib_assets_for_primary_apk],+ "native_libs": outputs[native_libs],+ "native_libs_always_in_primary_apk": outputs[native_libs_always_in_primary_apk],+ "native_libs_metadata": outputs[native_libs_metadata],+ "non_root_module_lib_assets": outputs[non_root_module_lib_assets],+ "non_root_module_metadata_assets": outputs[non_root_module_metadata_assets],+ "root_module_metadata_assets": outputs[root_module_metadata_assets],+ "stripped_native_linkable_assets_for_primary_apk": outputs[stripped_native_linkable_assets_for_primary_apk],+ "unstripped_native_libraries": outputs[unstripped_native_libraries],+ "unstripped_native_libraries_files": outputs[unstripped_native_libraries_files],+ "unstripped_native_libraries_json": outputs[unstripped_native_libraries_json],+ }++ if False: # @oss-enable+ # @oss-disable[end= ]: if is_late_gatorade_enabled(ctx) and not defer_relink:+ # Prevent Buildifier from moving comments in a way that breaks things.+ # When defer_relink is True, Gatorade runs in the deferred pipeline via+ # gatorade_deferred_libs() above.+ args = [+ ctx,+ final_shared_libs_by_platform,+ _post_native_lib_graph_finalization_steps,+ all_prebuilt_native_library_dirs,+ get_module_from_target,+ native_lib_dynamic_outputs,+ # @oss-disable[end= ]: native_cmd_entries,+ # @oss-disable[end= ]: outputs[native_build_commands_codegen],+ # @oss-disable[end= ]: outputs[late_gatorade_products],+ ]+ # @oss-disable[end= ]: subtarget_shared_libs_by_platform = gatorade_libraries(*args)+ else:+ subtarget_shared_libs_by_platform = _post_native_lib_graph_finalization_steps(+ ctx,+ final_shared_libs_by_platform,+ all_prebuilt_native_library_dirs,+ get_module_from_target,+ native_cmd_entries = native_cmd_entries,+ # Only record the libs finalized here as plain kind=link when the app neither merges+ # nor relinks; otherwise merge/relink links are already captured at their own sites.+ record_final_link = not has_native_merging and not enable_relinker,+ **native_lib_dynamic_outputs,+ )++ # Subtargets can't be created or changed from within dynamic actions, so the individual+ # library subtargets can't reflect any changes to the set of libraries made by a dynamic+ # action. All other logic should be in _post_native_lib_graph_finalization_steps, which+ # receives the final set of native libraries.+ _link_library_subtargets(+ ctx,+ outputs,+ lib_outputs_by_platform,+ original_shared_libs_by_platform,+ subtarget_shared_libs_by_platform,+ merged_shared_lib_targets_by_platform,+ split_groups,+ native_merge_debug,+ )++ # Write the "base" fragment: every native-build command known by the end of this lambda.+ # with_inputs = False embeds each argv/argsfile as text without materializing the produced+ # .o/.so, matching the linker_commands writer. The final [native_build_commands] JSON and its+ # per-kind filters are produced by the combine action below (which folds in the late-Gatorade+ # codegen fragment).+ ctx.actions.write_json(outputs[native_build_commands_base], native_cmd_entries, with_inputs = False)++ # On paths that don't capture late-Gatorade codegen, bind its fragment here (empty) so the+ # combine action always has both inputs. On the capturing path the nested Gatorade dynamic+ # binds it instead.+ if not will_capture_late_gatorade_codegen:+ ctx.actions.write_json(outputs[native_build_commands_codegen], [], with_inputs = False)++ # TARGET[late_gatorade] products are bound inside the nested Gatorade dynamic (which knows the+ # output library graph); on every non-late path the outer lambda binds it empty here, mirroring+ # the native_build_commands_codegen fragment's ownership.+ if not will_capture_late_gatorade_codegen:+ ctx.actions.symlinked_dir(outputs[late_gatorade_products], {})++ ctx.actions.dynamic_output(dynamic = dynamic_inputs, inputs = [], outputs = [o.as_output() for o in dynamic_outputs], f = dynamic_native_libs_info)++ # Combine the base fragment with the late-Gatorade codegen fragment into the final+ # [native_build_commands] JSON and its per-kind filters. Both fragments were written with+ # with_inputs = False, so their entries are already-rendered plain JSON; read them back and+ # re-emit. This runs after the (possibly nested) writers of both fragments complete.+ def _combine_native_build_commands(ctx: AnalysisContext, artifacts, outputs):+ entries = artifacts[native_build_commands_base].read_json() + artifacts[native_build_commands_codegen].read_json()+ ctx.actions.write_json(outputs[native_build_commands], entries)+ for kind in NATIVE_BUILD_COMMAND_KINDS:+ ctx.actions.write_json(outputs[native_build_commands_by_kind[kind]], [entry for entry in entries if entry["kind"] == kind])++ ctx.actions.dynamic_output(+ dynamic = [native_build_commands_base, native_build_commands_codegen],+ inputs = [],+ outputs = [native_build_commands.as_output()] + [native_build_commands_by_kind[kind].as_output() for kind in NATIVE_BUILD_COMMAND_KINDS],+ f = _combine_native_build_commands,+ )+ combined_asset_libs = ctx.actions.declare_output("combined_asset_libs", dir = True, has_content_based_path = False)+ ctx.actions.run(+ cmd_args([+ ctx.attrs._android_toolchain[AndroidToolchainInfo].combine_native_library_dirs[RunInfo],+ "--output-dir",+ combined_asset_libs.as_output(),+ "--library-dirs",+ native_lib_assets_for_primary_apk,+ stripped_native_linkable_assets_for_primary_apk,+ "--subdir",+ "assets/lib",+ ]),+ category = "combine_native_asset_libs",+ allow_cache_upload = True,+ )+ all_native_libs = ctx.actions.symlinked_dir(+ "debug_all_native_libs",+ {+ "assets": combined_asset_libs,+ "others": native_libs,+ "primary": native_libs_always_in_primary_apk,+ },+ has_content_based_path = False,+ )++ lib_subtargets = _create_library_subtargets(+ lib_outputs_by_platform,+ native_libs,+ # @oss-disable[end= ]: create_default_outputs = not is_late_gatorade_enabled(ctx),+ create_default_outputs = True, # @oss-enable+ )+ enhance_ctx.debug_output("native_libs", all_native_libs, sub_targets = lib_subtargets)+ if native_merge_debug:+ enhance_ctx.debug_output("native_merge_debug", native_merge_debug)++ if jni_onload_check_report:+ # Buildable on its own so the check can be run, and its report read,+ # without building the whole apk.+ enhance_ctx.debug_output("jni_onload_check", jni_onload_check_report)++ enhance_ctx.debug_output("linker_argsfiles", linker_argsfiles)+ enhance_ctx.debug_output("linker_commands", linker_commands)+ # Materialize the argsfiles a consumer needs to expand an entry's `@argsfile` on disk:+ # - link-family kinds (merge/link/relink/bolt) -> the linker_argsfiles symlinked_dir built in+ # finalization from every final lib's linker_argsfile;+ # - compile -> the per-source compile argsfiles collected at analysis time above.+ # mergemap has no argsfile; Gatorade argsfiles are recorded by path only (see+ # native_build_commands.bzl `argsfile` note), so those kinds get no extra outputs here.+ compile_argsfiles_outputs = list(compile_argsfiles.keys())+ _kind_argsfile_outputs = {kind: [linker_argsfiles] for kind in ["merge", "link", "relink", "bolt"]}+ _kind_argsfile_outputs["compile"] = compile_argsfiles_outputs+ enhance_ctx.debug_output(+ "native_build_commands",+ native_build_commands,+ other_outputs = [linker_argsfiles] + compile_argsfiles_outputs,+ sub_targets = {+ kind: [+ DefaultInfo(+ default_outputs = [native_build_commands_by_kind[kind]],+ other_outputs = _kind_argsfile_outputs.get(kind, []),+ )+ ]+ for kind in NATIVE_BUILD_COMMAND_KINDS+ },+ )+ # TARGET[<phase>] Gatorade-phase product sub-targets: building one runs that phase and outputs+ # the artifacts its gatorade invocation(s) produce (a symlinked_dir, like [native_libs]). Early's+ # products were collected at analysis scope; middle/late were bound inside the dynamic lambda.+ # middle_gatorade_products is only declared when the middle phase runs, so otherwise the+ # sub-target resolves to an empty dir.+ early_gatorade_products = ctx.actions.symlinked_dir("early_gatorade_products", early_gatorade_product_mapping, has_content_based_path = False)+ gatorade_phase_products = {+ "early_gatorade": early_gatorade_products,+ "late_gatorade": late_gatorade_products,+ "middle_gatorade": middle_gatorade_products or ctx.actions.symlinked_dir("middle_gatorade_products", {}, has_content_based_path = False),+ }+ expect(+ sorted(gatorade_phase_products.keys()) == sorted(GATORADE_PHASE_SUBTARGETS),+ "gatorade_phase_products must cover exactly GATORADE_PHASE_SUBTARGETS",+ )+ for gatorade_phase, products in gatorade_phase_products.items():+ enhance_ctx.debug_output(gatorade_phase, products)+ enhance_ctx.debug_output("unstripped_native_libraries", unstripped_native_libraries, other_outputs = [unstripped_native_libraries_files])+ enhance_ctx.debug_output("unstripped_native_libraries_json", unstripped_native_libraries_json, other_outputs = [unstripped_native_libraries_files])+ enhance_ctx.debug_output("unstripped_native_libraries_files", unstripped_native_libraries_files)+ if relinked_libs_output:+ enhance_ctx.debug_output("relinked_libs", relinked_libs_output)+ if relinked_libs_manifest:+ enhance_ctx.debug_output("relinked_libs_manifest", relinked_libs_manifest)+ if unrelinked_libs_output:+ enhance_ctx.debug_output("unrelinked_libs", unrelinked_libs_output)+ enhance_ctx.debug_output("relinker_extra_outputs", relinker_extra_outputs)++ _register_gatorade_phase_evidence(+ enhance_ctx,+ original_shared_libs_by_platform.keys(),+ native_library_merge_dir,+ middle_gatorade_products,+ unstripped_native_libraries_files,+ relinked_libs_output,+ defer_relink,+ )++ native_libs_for_primary_apk, exopackage_info = _get_exopackage_info(ctx, native_libs_always_in_primary_apk, native_libs, native_libs_metadata)+ return AndroidBinaryNativeLibsInfo(+ prebuilt_native_library_dirs = all_prebuilt_native_library_dirs,+ shared_libraries = included_shared_lib_targets,+ native_libs_for_primary_apk = native_libs_for_primary_apk,+ exopackage_info = exopackage_info,+ root_module_native_lib_assets = [native_lib_assets_for_primary_apk, stripped_native_linkable_assets_for_primary_apk, root_module_metadata_assets],+ non_root_module_native_lib_assets = [non_root_module_metadata_assets, non_root_module_lib_assets],+ generated_java_code = generated_java_code,+ unstripped_shared_libraries = unstripped_native_libraries_files,+ validation_outputs = [jni_onload_check_report] if jni_onload_check_report else [],+ )++_NativeLibSubtargetArtifacts = record(+ default = Artifact,+ unrelinked = Artifact | None,+ linker_command = Artifact | None,+ linker_argsfile = Artifact | None,+ # Pre-inline module IR (.ll) emitted by the relink when the `preinline-ir`+ # extra relinker output is enabled; a comment-only `.ll` otherwise. Surfaced+ # as the `[preinline_ir]` sub-target so tooling (evt) can fetch it.+ preinline_ir = Artifact | None,+)++# Writes a directory of <abi>/<soname> shared libraries, and optionally a JSON+# manifest listing those entries. Shared by the [relinked_libs] and+# [unrelinked_libs] sub-targets. [relinked_libs] feeds the combine genrule and+# wants the packaged (stripped) form plus the manifest (so the combine step+# knows which libraries to replace); [unrelinked_libs] mirrors the per-library+# [unrelinked] sub-target, exposing the unstripped linker output, and needs no+# manifest (pass out_manifest = None).+def _write_relinker_extra_outputs_dir(ctx: AnalysisContext, libs_by_platform: dict[str, dict[str, SharedLibrary]], out_dir: Artifact):+ # Only the configured types: the relinker records other things under+ # `extra_outputs` as well, and they are not for building on their own.+ output_types = getattr(ctx.attrs, "extra_relinker_outputs", [])+ files = {}+ for platform, libs in libs_by_platform.items():+ abi_directory = CPU_FILTER_TO_ABI_DIRECTORY[platform]+ for soname, lib in libs.items():+ for output_type in output_types:+ for info in lib.extra_outputs.get(output_type, []):+ for artifact in info.default_outputs:+ # Key by soname as well: two libraries in the same+ # abi/type can emit outputs sharing a basename, which+ # would otherwise collide and drop one silently.+ files["{}/{}/{}/{}".format(output_type, abi_directory, soname, artifact.basename)] = artifact+ ctx.actions.symlinked_dir(out_dir, files)++def _write_native_libs_dir_and_manifest(ctx, libs_by_platform, out_dir, out_manifest, stripped):+ lib_files = {}+ for platform in libs_by_platform:+ libs = libs_by_platform[platform]+ abi_directory = CPU_FILTER_TO_ABI_DIRECTORY[platform]+ for soname in libs:+ shlib = libs[soname]+ lib_files["{}/{}".format(abi_directory, soname)] = (shlib.stripped_lib or shlib.lib.output) if stripped else shlib.lib.output+ ctx.actions.symlinked_dir(out_dir, lib_files)+ if out_manifest != None:+ ctx.actions.write_json(out_manifest, sorted(lib_files.keys()))++def _post_native_lib_graph_finalization_steps(+ ctx: AnalysisContext,+ final_shared_libs_by_platform: dict[str, dict[str, SharedLibrary]],+ all_prebuilt_native_library_dirs: list[PrebuiltNativeLibraryDir],+ get_module_from_target: typing.Callable,+ linker_argsfiles: Artifact,+ linker_commands: Artifact,+ unstripped_native_libraries: Artifact,+ unstripped_native_libraries_json: Artifact,+ unstripped_native_libraries_files: Artifact,+ native_libs: Artifact,+ native_libs_metadata: Artifact,+ native_libs_always_in_primary_apk: Artifact,+ native_lib_assets_for_primary_apk: Artifact,+ stripped_native_linkable_assets_for_primary_apk: Artifact,+ root_module_metadata_assets: Artifact,+ non_root_module_metadata_assets: Artifact,+ non_root_module_lib_assets: Artifact,+ native_cmd_entries = None,+ # True only on apps that neither merge nor relink: then the libs finalized here ARE the plain+ # per-library links, recorded kind=link. When merging/relinking, those commands are captured at+ # their own sites (kind=merge / kind=relink) and this must stay False to avoid double-recording.+ record_final_link: bool = False,+) -> dict[str, dict[str, SharedLibrary]]:+ bolt_args = getattr(ctx.attrs, "native_library_bolt_args", None)+ pre_bolt_libs_by_platform = {}+ if bolt_args and len(bolt_args) != 0:+ final_shared_libs_by_platform, pre_bolt_libs_by_platform = _bolt_libraries(+ ctx, final_shared_libs_by_platform, bolt_args, native_cmd_entries, record_final_link+ )++ unstripped_libs = {}+ linker_argsfiles_list = []+ linker_commands_json = []+ for platform, libs in final_shared_libs_by_platform.items() + pre_bolt_libs_by_platform.items():+ for soname, lib in libs.items():+ unstripped_libs[lib.lib.output] = platform+ if lib.lib.linker_argsfile:+ linker_argsfiles_list.append(lib.lib)+ linker_commands_json.append({+ "argsfile": lib.lib.linker_argsfile,+ "command": lib.lib.linker_command,+ "filename": lib.lib.output.short_path,+ })++ # Record the plain per-library link for [native_build_commands][link], but only on apps+ # that neither merge nor relink (record_final_link). Merge and relink links are captured+ # at their own sites, and on those paths the libs seen here are either already-recorded+ # (merge/relink outputs) or command-less (late-gatorade dummies), so recording here would+ # double-count or add null entries.+ if record_final_link:+ record_link_command(native_cmd_entries, "link", platform, soname, lib.lib)++ ctx.actions.symlinked_dir(linker_argsfiles, {"{}".format(lib.output.basename): lib.linker_argsfile for lib in linker_argsfiles_list})+ ctx.actions.write_json(linker_commands, linker_commands_json, with_inputs = False)+ ctx.actions.write(unstripped_native_libraries, unstripped_libs.keys())+ ctx.actions.write_json(unstripped_native_libraries_json, unstripped_libs)+ ctx.actions.symlinked_dir(unstripped_native_libraries_files, {"{}/{}".format(platform, lib.basename): lib for lib, platform in unstripped_libs.items()})++ dynamic_info = _get_native_libs_and_assets(+ ctx,+ get_module_from_target,+ all_prebuilt_native_library_dirs,+ final_shared_libs_by_platform,+ )++ # Since we are using a dynamic action, we need to declare the outputs in advance.+ # Rather than passing the created outputs into `_get_native_libs_and_assets`, we+ # just symlink to the outputs that function produces.+ ctx.actions.symlink_file(native_libs, dynamic_info.native_libs)+ ctx.actions.symlink_file(native_libs_metadata, dynamic_info.native_libs_metadata)+ ctx.actions.symlink_file(native_libs_always_in_primary_apk, dynamic_info.native_libs_always_in_primary_apk)+ ctx.actions.symlink_file(+ native_lib_assets_for_primary_apk,+ dynamic_info.native_lib_assets_for_primary_apk+ if dynamic_info.native_lib_assets_for_primary_apk+ else ctx.actions.symlinked_dir("empty_native_lib_assets", {}, has_content_based_path = False),+ )+ ctx.actions.symlink_file(+ stripped_native_linkable_assets_for_primary_apk,+ dynamic_info.stripped_native_linkable_assets_for_primary_apk+ if dynamic_info.stripped_native_linkable_assets_for_primary_apk+ else ctx.actions.symlinked_dir("empty_stripped_native_linkable_assets", {}, has_content_based_path = False),+ )+ ctx.actions.symlink_file(root_module_metadata_assets, dynamic_info.root_module_metadata_assets)+ ctx.actions.symlink_file(non_root_module_metadata_assets, dynamic_info.non_root_module_metadata_assets)+ ctx.actions.symlink_file(+ non_root_module_lib_assets,+ dynamic_info.non_root_module_lib_assets+ if dynamic_info.non_root_module_lib_assets+ else ctx.actions.symlinked_dir("empty_non_root_module_lib_assets", {}, has_content_based_path = False),+ )++ return final_shared_libs_by_platform++# Merged libraries are dynamic dependencies, but outputs need to be declared in advance to be used by subtargets.+# This means we have to declare outputs for all possible merged libs (every merged name and every unmerged library name).+def _declare_library_subtargets(+ ctx: AnalysisContext,+ dynamic_outputs: list[Artifact],+ original_shared_libs_by_platform: dict[str, dict[str, SharedLibrary]],+ native_library_merge_map,+ native_library_merge_sequence,+ enable_relinker: bool,+) -> dict[str, dict[str, _NativeLibSubtargetArtifacts]]:+ lib_outputs_by_platform = {}+ for platform, original_shared_libs in original_shared_libs_by_platform.items():+ sonames = set()+ sonames.update(original_shared_libs.keys())+ if native_library_merge_map:+ sonames.update(native_library_merge_map.keys())+ elif native_library_merge_sequence:+ for entry in native_library_merge_sequence:+ if type(entry) == "list":+ sonames.update([soname for (soname, _) in entry])+ else:+ (soname, _) = entry+ sonames.add(soname)++ lib_outputs = {}+ for soname in sonames:+ output_path = _platform_output_path(soname, platform if len(original_shared_libs_by_platform) > 1 else None)+ lib_output = ctx.actions.declare_output(output_path, dir = True, has_content_based_path = False)+ dynamic_outputs.append(lib_output)++ if enable_relinker:+ linker_command_output = ctx.actions.declare_output(output_path + ".linker_command", has_content_based_path = False)+ dynamic_outputs.append(linker_command_output)+ linker_argsfile_output = ctx.actions.declare_output(output_path + ".linker_argsfile", has_content_based_path = False)+ dynamic_outputs.append(linker_argsfile_output)+ preinline_ir_output = ctx.actions.declare_output(output_path + ".preinline.ll", has_content_based_path = False)+ dynamic_outputs.append(preinline_ir_output)++ output_path = output_path + ".unrelinked"+ unrelinked_lib_output = ctx.actions.declare_output(output_path, dir = True, has_content_based_path = False)+ dynamic_outputs.append(unrelinked_lib_output)+ lib_outputs[soname] = _NativeLibSubtargetArtifacts(+ default = lib_output,+ unrelinked = unrelinked_lib_output,+ linker_command = linker_command_output,+ linker_argsfile = linker_argsfile_output,+ preinline_ir = preinline_ir_output,+ )+ else:+ lib_outputs[soname] = _NativeLibSubtargetArtifacts(+ default = lib_output,+ unrelinked = None,+ linker_command = None,+ linker_argsfile = None,+ preinline_ir = None,+ )++ lib_outputs_by_platform[platform] = lib_outputs+ return lib_outputs_by_platform++# Bind debug library subtarget outputs to actual outputs.+# For individual libraries, link to either the unmerged or merged output.+# For merged libraries, link to either the merged output, or a symlinked dir of all merged split group outputs.+def _link_library_subtargets(+ ctx: AnalysisContext,+ outputs, # IndexSet[OutputArtifact]+ lib_outputs_by_platform: dict[str, dict[str, _NativeLibSubtargetArtifacts]], # dict[platform, dict[soname, _NativeLibSubtargetArtifacts]]+ original_shared_libs_by_platform: dict[str, dict[str, SharedLibrary]],+ final_shared_libs_by_platform: dict[str, dict[str, SharedLibrary]],+ merged_shared_lib_targets_by_platform: dict[str, dict[Label, str]],+ split_groups: dict[str, str] | None,+ native_merge_debug,+ unrelinked: bool = False,+):+ for platform, final_shared_libs in final_shared_libs_by_platform.items():+ merged_lib_outputs = {}+ linker_commands_by_soname = {}+ linker_argsfiles_by_soname = {}+ preinline_ir_by_soname = {}++ for soname, lib in final_shared_libs.items():+ base_soname = soname+ if split_groups and soname in split_groups:+ base_soname = split_groups[soname]++ group_outputs = merged_lib_outputs.setdefault(base_soname, {})+ group_outputs[soname] = lib.lib.output++ if not unrelinked:+ if lib.lib.linker_command:+ linker_commands_by_soname[soname] = {+ "argsfile": lib.lib.linker_argsfile,+ "command": lib.lib.linker_command,+ "filename": lib.lib.output.short_path,+ }+ if lib.lib.linker_argsfile:+ linker_argsfiles_by_soname[soname] = lib.lib.linker_argsfile+ preinline_ir = lib.extra_outputs.get("preinline-ir") if lib.extra_outputs else None+ if preinline_ir:+ preinline_ir_outputs = preinline_ir[0].default_outputs+ if preinline_ir_outputs:+ preinline_ir_by_soname[soname] = preinline_ir_outputs[0]++ for soname, lib_outputs in lib_outputs_by_platform[platform].items():+ if soname in merged_lib_outputs:+ group_outputs = merged_lib_outputs[soname]+ elif soname in original_shared_libs_by_platform[platform]:+ # link unmerged soname to merged output+ original_shared_lib = original_shared_libs_by_platform[platform][soname]+ merged_soname = merged_shared_lib_targets_by_platform[platform][original_shared_lib.label]+ if split_groups and merged_soname in split_groups:+ merged_soname = split_groups[merged_soname]+ group_outputs = merged_lib_outputs[merged_soname]+ else:+ # merged group name has no constituents, link to debug output+ group_outputs = {soname: native_merge_debug}++ output = lib_outputs.default+ if unrelinked:+ output = lib_outputs.unrelinked+ ctx.actions.symlinked_dir(outputs[output], group_outputs)++ if not unrelinked and lib_outputs.linker_command:+ if soname in linker_commands_by_soname:+ ctx.actions.write_json(outputs[lib_outputs.linker_command], linker_commands_by_soname[soname])+ else:+ ctx.actions.write_json(outputs[lib_outputs.linker_command], {})++ if soname in linker_argsfiles_by_soname:+ ctx.actions.symlink_file(outputs[lib_outputs.linker_argsfile], linker_argsfiles_by_soname[soname])+ else:+ ctx.actions.write_json(outputs[lib_outputs.linker_argsfile], {})++ if lib_outputs.preinline_ir:+ if soname in preinline_ir_by_soname:+ ctx.actions.symlink_file(outputs[lib_outputs.preinline_ir], preinline_ir_by_soname[soname])+ else:+ # `;` is an LLVM IR line comment, so a consumer that parses this+ # unconditionally reads an empty module rather than choking on a+ # placeholder that is not IR at all.+ ctx.actions.write(+ outputs[lib_outputs.preinline_ir],+ "; no pre-inline IR for {}: the `preinline_ir` relinker output was not enabled for this library (constraint off, or soname absent from `gator.preinline_ir_sonames`)".format(+ soname+ ),+ )++def _create_library_subtargets(+ lib_outputs_by_platform: dict[str, dict[str, _NativeLibSubtargetArtifacts]], native_libs: Artifact, create_default_outputs: bool+):+ def create_library_subtarget(output: _NativeLibSubtargetArtifacts, create_default_outputs: bool):+ if not create_default_outputs and not output.unrelinked:+ fail("create_default_outputs can only be False when relinking")++ sub_targets = {}+ if output.linker_command:+ sub_targets["linker_command"] = [DefaultInfo(default_outputs = [output.linker_command])]+ if output.linker_argsfile:+ sub_targets["linker_argsfile"] = [DefaultInfo(default_outputs = [output.linker_argsfile])]+ if output.preinline_ir:+ sub_targets["preinline_ir"] = [DefaultInfo(default_outputs = [output.preinline_ir])]++ if output.unrelinked:+ sub_targets["unrelinked"] = [DefaultInfo(default_outputs = [output.unrelinked])]+ if create_default_outputs:+ default_outputs = [output.default]+ else:+ sub_targets["relinked"] = [DefaultInfo(default_outputs = [output.default])]+ default_outputs = []+ return [DefaultInfo(default_outputs = default_outputs, sub_targets = sub_targets)]+ return [DefaultInfo(default_outputs = [output.default], sub_targets = sub_targets)]++ if len(lib_outputs_by_platform) > 1:+ return {+ platform: [+ DefaultInfo(+ default_outputs = [native_libs],+ sub_targets = {soname: create_library_subtarget(output, create_default_outputs) for soname, output in lib_outputs.items()},+ )+ ]+ for platform, lib_outputs in lib_outputs_by_platform.items()+ }+ elif len(lib_outputs_by_platform) == 1:+ lib_outputs = list(lib_outputs_by_platform.values())[0]+ return {soname: create_library_subtarget(output, create_default_outputs) for soname, output in lib_outputs.items()}+ else:+ # TODO(ctolliday) at this point we should have thrown an error earlier if no libraries matched cpu_filters+ # (or returned earlier if there are no native library deps)+ return {}++# We could just return two artifacts of libs (one for the primary APK, one which can go+# either into the primary APK or be exopackaged), and one artifact of assets,+# but we'd need an extra action in order to combine them (we can't use `symlinked_dir` since+# the paths overlap) so it's easier to just be explicit about exactly what we produce.+_NativeLibsAndAssetsInfo = record(+ native_libs = Artifact,+ native_libs_metadata = Artifact,+ native_libs_always_in_primary_apk = Artifact,+ native_lib_assets_for_primary_apk = Artifact | None,+ stripped_native_linkable_assets_for_primary_apk = Artifact | None,+ root_module_metadata_assets = Artifact,+ non_root_module_metadata_assets = Artifact,+ non_root_module_lib_assets = [Artifact, None],+)++def _get_exopackage_info(+ ctx: AnalysisContext, native_libs_always_in_primary_apk: Artifact, native_libs: Artifact, native_libs_metadata: Artifact+) -> (list[Artifact], [ExopackageNativeInfo, None]):+ is_exopackage_enabled_for_native_libs = "native_library" in getattr(ctx.attrs, "exopackage_modes", [])+ if is_exopackage_enabled_for_native_libs:+ return [native_libs_always_in_primary_apk], ExopackageNativeInfo(directory = native_libs, metadata = native_libs_metadata)+ else:+ return [native_libs, native_libs_always_in_primary_apk], None++def _get_native_libs_and_assets(+ ctx: AnalysisContext,+ get_module_from_target: typing.Callable,+ all_prebuilt_native_library_dirs: list[PrebuiltNativeLibraryDir],+ platform_to_native_linkables: dict[str, dict[str, SharedLibrary]],+) -> _NativeLibsAndAssetsInfo:+ is_packaging_native_libs_as_assets_supported = getattr(ctx.attrs, "package_asset_libraries", False)+ is_voltron_packaging_native_libs_as_assets_supported = getattr(ctx.attrs, "package_voltron_asset_libraries", False)++ prebuilt_native_library_dirs = []+ prebuilt_native_library_dirs_always_in_primary_apk = []+ prebuilt_native_library_dir_assets_for_primary_apk = []+ prebuilt_native_library_dir_module_assets_map = {}+ prebuilt_native_library_dir_module_libs_map = {}+ for native_lib in all_prebuilt_native_library_dirs:+ native_lib_target = str(native_lib.raw_target)+ module = get_module_from_target(native_lib_target)+ expect(+ not native_lib.for_primary_apk or is_root_module(module),+ "{} which is marked as needing to be in the primary APK cannot be included in non-root-module {}".format(native_lib_target, module),+ )+ expect(+ not native_lib.for_primary_apk or not native_lib.is_asset,+ "{} which is marked as needing to be in the primary APK cannot be an asset".format(native_lib_target),+ )+ if not is_root_module(module):+ if native_lib.is_asset and is_voltron_packaging_native_libs_as_assets_supported:+ prebuilt_native_library_dir_module_assets_map.setdefault(module, []).append(native_lib)+ else:+ prebuilt_native_library_dir_module_libs_map.setdefault(module, []).append(native_lib)+ elif native_lib.is_asset and is_packaging_native_libs_as_assets_supported:+ expect(not native_lib.for_primary_apk, "{} which is marked as needing to be in the primary APK cannot be an asset".format(native_lib_target))+ prebuilt_native_library_dir_assets_for_primary_apk.append(native_lib)+ elif native_lib.for_primary_apk:+ prebuilt_native_library_dirs_always_in_primary_apk.append(native_lib)+ else:+ prebuilt_native_library_dirs.append(native_lib)++ native_libs = _filter_prebuilt_native_library_dir(+ ctx,+ prebuilt_native_library_dirs,+ "native_libs",+ )+ native_libs_always_in_primary_apk = _filter_prebuilt_native_library_dir(+ ctx,+ prebuilt_native_library_dirs_always_in_primary_apk,+ "native_libs_always_in_primary_apk",+ )+ native_lib_assets_for_primary_apk = (+ _filter_prebuilt_native_library_dir(+ ctx,+ prebuilt_native_library_dir_assets_for_primary_apk,+ "native_lib_assets_for_primary_apk",+ package_as_assets = True,+ module = ROOT_MODULE,+ )+ if prebuilt_native_library_dir_assets_for_primary_apk+ else None+ )+ native_lib_module_assets_map = {}+ for module, native_lib_dir in prebuilt_native_library_dir_module_assets_map.items():+ native_lib_module_assets_map.setdefault(module, []).append(+ _filter_prebuilt_native_library_dir(+ ctx,+ native_lib_dir,+ "native_lib_assets_for_module_{}".format(module),+ package_as_assets = True,+ module = module,+ )+ )+ for module, native_lib_dir in prebuilt_native_library_dir_module_libs_map.items():+ native_lib_module_assets_map.setdefault(module, []).append(+ _filter_prebuilt_native_library_dir(+ ctx,+ native_lib_dir,+ "native_lib_libs_for_module_{}".format(module),+ package_as_assets = False,+ module = module,+ )+ )++ stripped_linkables = _get_native_linkables(+ ctx,+ platform_to_native_linkables,+ get_module_from_target,+ is_packaging_native_libs_as_assets_supported,+ is_voltron_packaging_native_libs_as_assets_supported,+ )+ for module, native_linkable_assets in stripped_linkables.linkable_module_assets_map.items():+ native_lib_module_assets_map.setdefault(module, []).append(native_linkable_assets)++ root_module_metadata_srcs = {}+ non_root_module_metadata_srcs = {}+ non_root_module_libs_srcs = []+ assets_for_primary_apk = filter(None, [native_lib_assets_for_primary_apk, stripped_linkables.linkable_assets_for_primary_apk])+ stripped_linkable_assets_for_primary_apk = stripped_linkables.linkable_assets_for_primary_apk+ if assets_for_primary_apk:+ metadata_file = _get_native_libs_as_assets_metadata(ctx, assets_for_primary_apk, ROOT_MODULE)+ root_module_metadata_srcs[paths.join(_get_native_libs_as_assets_dir(ROOT_MODULE), "metadata.txt")] = metadata_file++ for module, native_lib_assets in native_lib_module_assets_map.items():+ metadata_file = _get_native_libs_as_assets_metadata(ctx, native_lib_assets, module)+ libs_metadata_path = paths.join("assets", "libs.txt")+ non_root_module_metadata_srcs[paths.join(_get_native_libs_as_assets_dir(module), libs_metadata_path)] = metadata_file+ non_root_module_libs_srcs.extend(native_lib_assets)++ non_root_module_libs = None+ if non_root_module_libs_srcs:+ non_root_module_libs = ctx.actions.declare_output("non_root_module_libs", has_content_based_path = False)+ ctx.actions.run(+ cmd_args(+ [+ ctx.attrs._android_toolchain[AndroidToolchainInfo].combine_native_library_dirs[RunInfo],+ "--output-dir",+ non_root_module_libs.as_output(),+ "--library-dirs",+ ]+ + non_root_module_libs_srcs+ ),+ category = "combine_non_root_module_native_libs",+ allow_cache_upload = True,+ )++ combined_native_libs = ctx.actions.declare_output("combined_native_libs", dir = True, has_content_based_path = False)+ native_libs_metadata = ctx.actions.declare_output("native_libs_metadata.txt", has_content_based_path = False)+ native_library_pick_first = getattr(ctx.attrs, "native_library_pick_first", [])+ native_library_pick_first_arg = ["--pick-first"] + native_library_pick_first if native_library_pick_first else []+ ctx.actions.run(+ cmd_args(+ [+ ctx.attrs._android_toolchain[AndroidToolchainInfo].combine_native_library_dirs[RunInfo],+ "--output-dir",+ combined_native_libs.as_output(),+ "--library-dirs",+ native_libs,+ stripped_linkables.linkables,+ "--metadata-file",+ native_libs_metadata.as_output(),+ ]+ + native_library_pick_first_arg+ ),+ category = "combine_native_libs",+ allow_cache_upload = True,+ )++ combined_native_libs_always_in_primary_apk = ctx.actions.declare_output(+ "combined_native_libs_always_in_primary_apk", dir = True, has_content_based_path = False+ )+ ctx.actions.run(+ cmd_args([+ ctx.attrs._android_toolchain[AndroidToolchainInfo].combine_native_library_dirs[RunInfo],+ "--output-dir",+ combined_native_libs_always_in_primary_apk.as_output(),+ "--library-dirs",+ native_libs_always_in_primary_apk,+ stripped_linkables.linkables_always_in_primary_apk,+ ]),+ category = "combine_native_libs_always_in_primary_apk",+ allow_cache_upload = True,+ )++ return _NativeLibsAndAssetsInfo(+ native_libs = combined_native_libs,+ native_libs_metadata = native_libs_metadata,+ native_libs_always_in_primary_apk = combined_native_libs_always_in_primary_apk,+ native_lib_assets_for_primary_apk = native_lib_assets_for_primary_apk,+ stripped_native_linkable_assets_for_primary_apk = stripped_linkable_assets_for_primary_apk,+ root_module_metadata_assets = ctx.actions.symlinked_dir("root_module_metadata_assets", root_module_metadata_srcs, has_content_based_path = False),+ non_root_module_metadata_assets = ctx.actions.symlinked_dir(+ "non_root_module_metadata_assets", non_root_module_metadata_srcs, has_content_based_path = False+ ),+ non_root_module_lib_assets = non_root_module_libs,+ )++def _filter_prebuilt_native_library_dir(+ ctx: AnalysisContext, native_libs: list[PrebuiltNativeLibraryDir], identifier: str, package_as_assets: bool = False, module: str = ROOT_MODULE+) -> Artifact:+ cpu_filters = ctx.attrs.cpu_filters or CPU_FILTER_TO_ABI_DIRECTORY.keys()+ abis = [CPU_FILTER_TO_ABI_DIRECTORY[cpu] for cpu in cpu_filters]+ filter_tool = ctx.attrs._android_toolchain[AndroidToolchainInfo].filter_prebuilt_native_library_dir[RunInfo]+ native_libs_dirs_file = argfile(actions = ctx.actions, name = "{}_list.txt".format(identifier), args = [native_lib.dir for native_lib in native_libs])+ base_output_dir = ctx.actions.declare_output(identifier, dir = True, has_content_based_path = False)+ if module == ROOT_MODULE:+ output_dir = base_output_dir.project(_get_native_libs_as_assets_dir(module)) if package_as_assets else base_output_dir+ elif package_as_assets:+ output_dir = base_output_dir.project(paths.join(_get_native_libs_as_assets_dir(module), "assets"))+ else:+ output_dir = base_output_dir.project(paths.join(_get_native_libs_as_assets_dir(module), "lib"))+ ctx.actions.run(+ cmd_args([filter_tool, native_libs_dirs_file, output_dir.as_output(), "--abis"] + abis),+ category = "filter_prebuilt_native_library_dir",+ identifier = identifier,+ allow_cache_upload = True,+ )++ return base_output_dir++_StrippedNativeLinkables = record(+ linkables = Artifact,+ linkables_always_in_primary_apk = Artifact,+ linkable_assets_for_primary_apk = Artifact | None,+ linkable_module_assets_map = dict[str, Artifact],+)++def _get_native_linkables(+ ctx: AnalysisContext,+ platform_to_native_linkables: dict[str, dict[str, SharedLibrary]],+ get_module_from_target: typing.Callable,+ package_native_libs_as_assets_enabled: bool,+ package_voltron_native_libs_as_assets_enabled: bool,+) -> _StrippedNativeLinkables:+ stripped_native_linkables_srcs = {}+ stripped_native_linkables_always_in_primary_apk_srcs = {}+ stripped_native_linkable_assets_for_primary_apk_srcs = {}+ stripped_native_linkable_module_assets_srcs = {}+ strip_libraries = getattr(ctx.attrs, "strip_libraries", True)++ cpu_filters = ctx.attrs.cpu_filters+ for platform, native_linkables in platform_to_native_linkables.items():+ if cpu_filters and platform not in cpu_filters and platform != CPU_FILTER_FOR_PRIMARY_PLATFORM:+ fail("Platform `{}` is not in the CPU filters `{}`".format(platform, cpu_filters))++ abi_directory = CPU_FILTER_TO_ABI_DIRECTORY[platform]+ for so_name, native_linkable in native_linkables.items():+ native_linkable_target = str(native_linkable.label.raw_target())+ module = get_module_from_target(native_linkable_target)+ lib = native_linkable.stripped_lib if strip_libraries else native_linkable.lib.output++ expect(+ not native_linkable.for_primary_apk or is_root_module(module),+ "{} which is marked as needing to be in the primary APK cannot be included in non-root-module {}".format(native_linkable_target, module),+ )+ expect(+ not native_linkable.for_primary_apk or not native_linkable.can_be_asset,+ "{} which is marked as needing to be in the primary APK cannot be an asset".format(native_linkable_target),+ )++ if is_root_module(module):+ if native_linkable.can_be_asset and package_native_libs_as_assets_enabled:+ native_libs_assets_dir = paths.join(_get_native_libs_as_assets_dir(module))+ so_name_path = paths.join(native_libs_assets_dir, abi_directory, so_name)+ stripped_native_linkable_assets_for_primary_apk_srcs[so_name_path] = lib+ else:+ so_name_path = paths.join(abi_directory, so_name)+ if native_linkable.for_primary_apk:+ stripped_native_linkables_always_in_primary_apk_srcs[so_name_path] = lib+ else:+ stripped_native_linkables_srcs[so_name_path] = lib+ else:+ module_dir = "assets" if native_linkable.can_be_asset and package_voltron_native_libs_as_assets_enabled else "lib"+ so_name_path = paths.join(_get_native_libs_as_assets_dir(module), module_dir, abi_directory, so_name)+ stripped_native_linkable_module_assets_srcs.setdefault(module, {})[so_name_path] = lib++ stripped_native_linkables = ctx.actions.symlinked_dir(+ "stripped_native_linkables",+ stripped_native_linkables_srcs,+ has_content_based_path = False,+ )+ stripped_native_linkables_always_in_primary_apk = ctx.actions.symlinked_dir(+ "stripped_native_linkables_always_in_primary_apk",+ stripped_native_linkables_always_in_primary_apk_srcs,+ has_content_based_path = False,+ )+ stripped_native_linkable_assets_for_primary_apk = (+ ctx.actions.symlinked_dir(+ "stripped_native_linkables_assets_for_primary_apk",+ stripped_native_linkable_assets_for_primary_apk_srcs,+ has_content_based_path = False,+ )+ if stripped_native_linkable_assets_for_primary_apk_srcs+ else None+ )+ stripped_native_linkable_module_assets_map = {}+ for module, srcs in stripped_native_linkable_module_assets_srcs.items():+ stripped_native_linkable_module_assets_map[module] = ctx.actions.symlinked_dir(+ "stripped_native_linkable_assets_for_module_{}".format(module),+ srcs,+ has_content_based_path = False,+ )++ return _StrippedNativeLinkables(+ linkables = stripped_native_linkables,+ linkables_always_in_primary_apk = stripped_native_linkables_always_in_primary_apk,+ linkable_assets_for_primary_apk = stripped_native_linkable_assets_for_primary_apk,+ linkable_module_assets_map = stripped_native_linkable_module_assets_map,+ )++def _get_native_libs_as_assets_metadata(ctx: AnalysisContext, native_lib_assets: list[Artifact], module: str) -> Artifact:+ native_lib_assets_file = argfile(+ actions = ctx.actions,+ name = "{}/native_lib_assets".format(module),+ args = [cmd_args([native_lib_asset, _get_native_libs_as_assets_dir(module)], delimiter = "/") for native_lib_asset in native_lib_assets],+ )+ metadata_output = ctx.actions.declare_output("{}/native_libs_as_assets_metadata.txt".format(module), has_content_based_path = False)+ metadata_cmd = cmd_args([+ ctx.attrs._android_toolchain[AndroidToolchainInfo].native_libs_as_assets_metadata[RunInfo],+ "--native-library-dirs",+ native_lib_assets_file,+ "--metadata-output",+ metadata_output.as_output(),+ ])+ ctx.actions.run(metadata_cmd, category = "get_native_libs_as_assets_metadata", identifier = module, allow_cache_upload = True)+ return metadata_output++def _get_native_libs_as_assets_dir(module: str) -> str:+ return "assets/{}".format("lib" if is_root_module(module) else module)++def get_default_shared_libs(ctx: AnalysisContext, deps: list[Dependency], shared_libraries_to_exclude: set) -> dict[str, SharedLibrary]:+ shared_library_info = merge_shared_libraries(+ ctx.actions,+ deps = filter(None, [x.get(SharedLibraryInfo) for x in deps]),+ )++ # Filter out shared libraries whose label.raw_target() is in shared_libraries_to_exclude+ # Do it before calling with_unique_str_sonames to skip duplication check for excluded libs+ shared_libraries = [+ shared_lib+ for shared_lib in traverse_shared_library_info(shared_library_info, transformation_provider = None)+ if (shared_lib.label.raw_target() not in shared_libraries_to_exclude)+ ]+ return {soname: shared_lib for soname, shared_lib in with_unique_str_sonames(shared_libraries).items()}++_LinkableSharedNode = record(+ raw_target = field(str),+ soname = field(str | None),+ labels = field(list[str], []),+ # Linkable deps of this target.+ deps = field(list[Label], []),+ can_be_asset = field(bool),+ force_static = field(bool),+)++def encode_linkable_graph_for_mergemap(graph_node_map_by_platform: dict[str, dict[Label, LinkableNode]]) -> dict[str, dict[Label, _LinkableSharedNode]]:+ return {+ platform: {+ target: _LinkableSharedNode(+ raw_target = str(target.raw_target()),+ soname = node.default_soname,+ labels = node.labels,+ deps = node.deps + node.exported_deps,+ can_be_asset = node.can_be_asset, # and not node.exclude_from_android_merge+ force_static = node.preferred_linkage == Linkage("static"),+ )+ for target, node in graph_node_map.items()+ }+ for platform, graph_node_map in graph_node_map_by_platform.items()+ }++# Debugging info about the linkables merge process. All of this will be written in one of the outputs of+# the `[native_merge_debug]` subtarget.+MergedLinkablesDebugInfo = record(+ unmerged_statics = list[str],+ group_debug = dict[str, typing.Any],+ with_default_soname = list[typing.Any],+ missing_default_solibs = list[Label],+)++# As shared lib output of the linkables merge process. This is not necessarily an actually merged node (there+# may be just one constituent)+MergedSharedLibrary = record(+ soname = str,+ lib = SharedLibrary,+ apk_module = str,+ # this only includes solib constituents that are included in the android merge map+ solib_constituents = list[str],+ # targets that correspond to solib_constituents (i.e., targets with include_in_android_mergemap = True)+ solib_constituent_targets = list[Label],+ is_actually_merged = bool,+ primary_constituents = list[Label],+)++# information about a link group derived from the merge mapping+LinkGroupData = record(+ group_name = [str, Label],+ constituents = list[Label],+ apk_module = str,+)++# Lookup key for somerge groups, either the soname for shared libraries or the target name for unmerged statics+GroupLabel = str++# Represents the primary constituents and deps of primary constituents used to create a LinkGroupLinkableNode for a non-prebuilt shared library.+LinkGroupMergeInfo = record(+ label = GroupLabel,+ deps = list[GroupLabel],+ exported_deps = list[GroupLabel],+ constituent_link_infos = list[LinkInfo],+)++# Represents a node in the final merged linkable map. Most of these will be shared libraries, either prebuilt shared libs or+# libraries that are created below for a node in the link_groups_graph. The exception is for non-merged static-only nodes.+LinkGroupLinkableNode = record(+ # The LinkInfo to add to the link line for a node that links against this.+ link = LinkInfo,+ deps = list[GroupLabel],+ exported_deps = list[GroupLabel],+ shared_lib = [SharedLibrary, None],+ # linker flags to be exported by any node that links against this. This can only be non-None for non-merged static only nodes (as we don't+ # propagate exported linker flags through transitive shared lib deps).+ exported_linker_flags = [(list[typing.Any], list[typing.Any]), None],+)++def write_merged_library_map(ctx: AnalysisContext, shared_libs_by_platform: dict[str, dict[str, MergedSharedLibrary]]) -> Artifact:+ """+ Writes the "merged library map". This is a map of original soname to final soname of the form:++ ```+ original_soname1 final_soname1+ original_soname2 final_soname1+ original_soname3 final_soname2+ ...+ ```+ """+ solib_map = {} # dict[final_soname, set[original_soname]]+ for _, shared_libs in shared_libs_by_platform.items():+ for soname in shared_libs.keys():+ merged_shared_lib = shared_libs[soname]+ if merged_shared_lib.is_actually_merged:+ solib_map.setdefault(soname, set()).update(merged_shared_lib.solib_constituents)++ lines = []+ for final_soname in sorted(solib_map.keys()):+ for original_soname in solib_map[final_soname]:+ lines.append("{} {}".format(original_soname, final_soname))++ # we wanted it sorted by original_soname+ return ctx.actions.write("merged_library_map.txt", sorted(lines), has_content_based_path = False)++def run_mergemap_codegen(ctx: AnalysisContext, merge_generator: Dependency, merged_library_map: Artifact) -> Artifact:+ mapping_java = ctx.actions.declare_output("MergedLibraryMapping.java", has_content_based_path = False)+ args = cmd_args(merge_generator[RunInfo])+ args.add([merged_library_map, mapping_java.as_output()])+ ctx.actions.run(args, category = "mergemap_codegen", allow_cache_upload = True)+ return mapping_java++def write_jni_on_load_mappings(ctx: AnalysisContext, shared_libs_by_platform: dict[str, dict[str, MergedSharedLibrary]]) -> Artifact:+ """+ Writes a mapping from merged library soname to the targets that are included in the android merge map.++ This only includes targets with include_in_android_mergemap = True, which are the same targets+ that appear in merged_library_map.txt.++ The output format matches the merge sequence format:+ ```+ (+ "libappdrivenaudiomerged.so",+ [+ "fbandroid/java/com/facebook/rsys/appdrivenaudio:appdrivenaudio-jni",+ "fbandroid/java/com/facebook/rsys/audio/frame:frame-jni",+ ],+ ),+ ```+ """+ solib_to_targets = {} # dict[final_soname, list[str]]+ for shared_libs in shared_libs_by_platform.values():+ for soname, merged_shared_lib in shared_libs.items():+ if not merged_shared_lib.is_actually_merged:+ continue++ # Only use solib_constituent_targets, which are targets with include_in_android_mergemap = True+ solib_to_targets.setdefault(soname, set()).update(merged_shared_lib.solib_constituent_targets)++ lines = []+ for soname, targets in sorted(solib_to_targets.items()):+ sorted_targets = sorted([t.raw_target() for t in targets])++ # Format targets as a list with proper indentation+ if len(sorted_targets) == 0:+ targets_str = "[]"+ elif len(sorted_targets) == 1:+ targets_str = '["{}"]'.format(sorted_targets[0])+ else:+ target_lines = ",\n ".join(['"{}"'.format(t) for t in sorted_targets])+ targets_str = "[\n {},\n ]".format(target_lines)+ lines.append(' (\n "{}",\n {},\n ),'.format(soname, targets_str))++ return ctx.actions.write("jni_on_load_mappings.txt", "\n".join(lines), has_content_based_path = False)++# We can't merge a prebuilt shared (that has no archive) and must use it's original info.+# Ideally this would probably be structured info on the linkablenode.+def _is_prebuilt_shared(node_data: LinkableNode) -> bool:+ shared_link_info = node_data.link_infos.get(LibOutputStyle("shared_lib"), None)+ if not shared_link_info or not shared_link_info.default.linkables:+ return False+ pic_archive_info = node_data.link_infos.get(LibOutputStyle("pic_archive"), None)+ if not pic_archive_info or not pic_archive_info.default.linkables:+ return True+ return False++def _has_linkable(node_data: LinkableNode) -> bool:+ for _, output in node_data.link_infos.items():+ if output.default.linkables:+ return True+ return False++def _platform_output_path(path: str, platform: [str, None] = None):+ if platform:+ return platform + "/" + path+ return path++def _transitive_has_non_prebuilt_linkable_deps(target: Label, linkable_nodes: dict[Label, LinkableNode], transitive_linkable_cache: dict[Label, bool]) -> bool:+ if target in transitive_linkable_cache:+ return transitive_linkable_cache[target]++ target_node = linkable_nodes.get(target)+ for dep in target_node.deps:+ dep_node = linkable_nodes.get(dep)+ if (_has_linkable(dep_node) and not _is_prebuilt_shared(dep_node)) or _transitive_has_non_prebuilt_linkable_deps(+ dep, linkable_nodes, transitive_linkable_cache+ ):+ transitive_linkable_cache[target] = True+ return True+ for dep in target_node.exported_deps:+ dep_node = linkable_nodes.get(dep)+ if (_has_linkable(dep_node) and not _is_prebuilt_shared(dep_node)) or _transitive_has_non_prebuilt_linkable_deps(+ dep, linkable_nodes, transitive_linkable_cache+ ):+ transitive_linkable_cache[target] = True+ return True++ transitive_linkable_cache[target] = False+ return False++def _shared_lib_for_prebuilt_shared(+ ctx: AnalysisContext,+ cxx_toolchain: CxxToolchainInfo,+ target: Label,+ node_data: LinkableNode,+ linkable_nodes: dict[Label, LinkableNode],+ transitive_linkable_cache: dict[Label, bool],+ platform: [str, None] = None,+) -> SharedLibrary:+ expect(+ len(node_data.shared_libs.libraries) == 1,+ "unexpected shared_libs length for somerge of {} ({})".format(target, node_data.shared_libs),+ )++ # TODO(cjhopman): We don't currently support prebuilt shared libs with deps on other libs because+ # we don't compute the shared lib deps of prebuilt shared libs here. That+ # shouldn't be too hard, but we haven't needed it.+ expect(+ not _transitive_has_non_prebuilt_linkable_deps(target, linkable_nodes, transitive_linkable_cache),+ "prebuilt shared library `{}` with non-prebuilt linkable deps not supported by somerge".format(target),+ )++ shlib = node_data.shared_libs.libraries[0]+ soname = shlib.soname.ensure_str()+ shlib = shlib.lib+ output_path = _platform_output_path(soname, platform)+ return create_shlib(+ lib = shlib,+ stripped_lib = strip_lib(ctx, cxx_toolchain, shlib.output, output_path),+ link_args = None,+ shlib_deps = None,+ can_be_asset = node_data.can_be_asset,+ for_primary_apk = False,+ soname = soname,+ label = target,+ )++def _run_jni_onload_check(+ ctx: AnalysisContext,+ cxx_toolchain: CxxToolchainInfo,+ check_inputs: list,+ output: Artifact,+):+ """Verify that no input to a merged library defines JNI_OnLoad.++ A constituent with allow_jni_merging = True has its JNI_OnLoad renamed by+ jni_lib_merge.h, and the JNI_OnLoad symbol in the merged library is+ manufactured by -Wl,--defsym. --defsym silently overrides a constituent's+ own definition rather than colliding with it, so a constituent that has a+ JNI_OnLoad but did not opt in has it discarded with no diagnostic and is+ never registered on MergedSoMapping$Invoke_JNI_OnLoad -- an+ UnsatisfiedLinkError at runtime and nothing at build time.++ This has to inspect the link *inputs*: by the time the merged library+ exists, --defsym has erased the evidence.+ """+ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]++ # write_json renders each artifact as its path and, with with_inputs, makes+ # the objects inputs of the action so they are materialized for the scan.+ manifest = ctx.actions.write_json(+ "jni_onload_check_inputs.json",+ [{"artifact": obj, "merged_lib": soname, "target": target} for soname, target, obj in check_inputs],+ with_inputs = True,+ has_content_based_path = False,+ )+ ctx.actions.run(+ cmd_args(+ android_toolchain.jni_onload_check[RunInfo],+ "--inputs",+ manifest,+ "--nm",+ cxx_toolchain.binary_utilities_info.nm,+ "--out",+ output.as_output(),+ ),+ category = "jni_onload_check",+ # Reads every object that goes into every merged library; running it+ # remotely avoids shipping them back for a local scan.+ prefer_remote = True,+ )++def _link_info_object_artifacts(link_info: LinkInfo) -> list[Artifact]:+ """The compiled inputs a LinkInfo contributes, for symbol inspection.++ Thin archives are represented by their member objects, which sidesteps the+ fact that a thin archive's member paths are relative to the archive itself+ and so cannot be read from an arbitrary working directory.+ """+ artifacts = []+ for linkable in link_info.linkables:+ if isinstance(linkable, ArchiveLinkable):+ if linkable.archive.external_objects:+ artifacts.extend(linkable.archive.external_objects)+ else:+ artifacts.append(linkable.archive.artifact)+ elif isinstance(linkable, ObjectsLinkable):+ artifacts.extend(linkable.objects or [])+ return artifacts++def _get_merged_linkables_for_platform(+ ctx: AnalysisContext,+ cxx_toolchain: CxxToolchainInfo,+ native_library_merge_linker_args_all: list,+ platform: str | None,+ glue_linkable: [(Label, LinkInfo), None],+ default_shared_libs: dict[str, SharedLibrary],+ linkable_nodes: dict[Label, LinkableNode],+ merge_map: dict[str, [str, None]],+ merge_linker_args: dict[str, typing.Any],+ apk_module_graph: typing.Callable,+ jni_onload_check_inputs: list | None = None,+) -> (dict[str, MergedSharedLibrary], MergedLinkablesDebugInfo):+ """+ This takes the merge mapping and constructs the resulting merged shared libraries.++ This is similar to link_groups used by ios and cxx_binary, but is sufficiently different that it needs its+ own implementation. Potentially we could find a generalization of them that covers both.++ An overview of how this works:++ The input includes a mapping of target -> link group. This mapping does not need to be comprehensive, a target+ not in that mapping is assigned to its own link group. The input also contains a mapping of target -> apk module,+ and this must have a mapping for every target. A link group cannot contain targets in different apk modules.++ Once we have the mapping of link groups, we construct an analog of the LinkableGraph on the new link group graph.+ This new graph consists of LinkGroupLinkableNodes (in some sense, the merged equivalent of LinkableNode).+ We traverse this graph from the bottom up, producing link info for each node.++ First, there are some special cases:++ If a target is "not actually merged" (i.e. it's in a link group where it is the only constituent) then it may get+ special handling if:+ (1) it is lib with static preferred linkage or it contains no linkables (i.e. no code)+ (2) a prebuild shared lib+ For both these cases we will produce a LinkGroupLinkableNode that basically reuses their original information. For+ every other case we will produce a node that represents a shared library that we define.++ When constructing a LinkableNode for a link group, we will be traversing sort of a hybrid graph, as we will traverse+ the primary constituents of the link group itself in the original LinkableGraph, but dependencies outside of the link+ group will be mapped to the corresponding LinkGroupLinkableNode (and potentially then further traversing that node's+ deps).++ The merge mapping input determines the "primary constituents" of each link group. The "real constituents" of that link+ group will include all those primary constituents, all of the transitive non-shared lib deps in the linkgroup linkable+ graph, and then all the shared lib dependencies of all of them (that is describing a traversal similar to the+ normal link strategies).++ There are some subtle differences in the handling of primary constituents and the statically linked non-primary+ constituents:+ 1. all primary constituents are public nodes, non primary ones are only public if they are transitively exported_deps+ of a primary constituent. A public node is linked via "link whole".+ 2. linker_flags of primary constituents are included in the link, for non primary they are not+ """+ debug_info = MergedLinkablesDebugInfo(+ unmerged_statics = [],+ group_debug = {},+ with_default_soname = [],+ missing_default_solibs = [],+ )++ linkable_nodes_graph = {k: dedupe(v.deps + v.exported_deps) for k, v in linkable_nodes.items()}+ topo_sorted_targets = pre_order_traversal(linkable_nodes_graph)++ # first we collect basic information about each link group, this will populate the fields in LinkGroupData and+ # map target labels to their link group name.+ link_groups = {}+ target_to_link_group = {}++ # Because we cannot attach this to the LinkableNode after the fact, declare a cache for each platform+ transitive_linkable_cache = {}++ for target in topo_sorted_targets:+ expect(target not in target_to_link_group, "prelude internal error, target seen twice?")+ target_apk_module = apk_module_graph(str(target.raw_target()))++ link_group = merge_map.get(str(target), None)+ if not link_group:+ link_group = str(target)+ link_groups[link_group] = LinkGroupData(+ group_name = target,+ constituents = [target],+ apk_module = target_apk_module,+ )+ elif link_group in link_groups:+ link_group_data = link_groups[link_group]++ # TODO(cjhopman): buck1 provides a more useful error here in that it lists the module mappings for all+ # constituents of the merge group (rather than just one conflict). That allows users to resolve all the+ # issues at once. With merge sequence merging (the replacement for merge map), this error shouldn't ever be hit+ # and so maybe it's not necessary to improve it.+ expect(+ link_group_data.apk_module == target_apk_module,+ "Native library merge of {} has inconsistent application module mappings:\n{} is in module {}\n{} is in module {}",+ link_group_data.group_name,+ target,+ target_apk_module,+ link_group_data.constituents[0],+ link_group_data.apk_module,+ )+ link_groups[link_group].constituents.append(target)+ else:+ link_groups[link_group] = LinkGroupData(+ group_name = link_group,+ constituents = [target],+ apk_module = target_apk_module,+ )++ target_to_link_group[target] = link_group++ # Now that all targets are assigned to a link group, build up the link group graph.+ link_groups_graph_builder = {}+ for target in topo_sorted_targets:+ target_group = target_to_link_group[target]+ group_deps = link_groups_graph_builder.setdefault(target_group, {})+ for dep in linkable_nodes_graph[target]:+ dep_group = target_to_link_group[dep]+ if target_group != dep_group and dep_group not in group_deps:+ # Store one example of why target_group depends on dep_group+ group_deps[dep_group] = (target, dep)+ link_groups_graph = {k: list(v.keys()) for k, v in link_groups_graph_builder.items()}++ archive_output_style = LibOutputStyle("pic_archive")+ shlib_output_style = LibOutputStyle("shared_lib")++ link_group_linkable_nodes = {}+ group_shared_libs = {}+ included_default_solibs = {}++ def edge_explainer(src_group, dest_group):+ """Explains in an error why src_group has a dependency on dest_group"""+ if src_group not in link_groups_graph_builder or dest_group not in link_groups_graph_builder[src_group]:+ return ["Unknown"]++ src_target, dest_target = link_groups_graph_builder[src_group][dest_group]+ return [" " + str(src_target), "-> " + str(dest_target)]++ # Now we will traverse from the leaves up the graph (the link groups graph). As we traverse, we will produce+ # a link group linkablenode for each group.+ for group in post_order_traversal(link_groups_graph, edge_explainer = edge_explainer):+ group_data = link_groups[group]+ is_actually_merged = len(group_data.constituents) > 1++ non_asset_constituents = [target for target in group_data.constituents if not linkable_nodes[target].can_be_asset]+ can_be_asset = len(non_asset_constituents) == 0++ if not is_actually_merged:+ target = group_data.constituents[0]+ node_data = linkable_nodes[target]++ if node_data.preferred_linkage == Linkage("static") or not _has_linkable(node_data):+ debug_info.unmerged_statics.append(target)+ link_group_linkable_nodes[group] = LinkGroupLinkableNode(+ link = node_data.link_infos[archive_output_style].default,+ deps = dedupe_by_value([target_to_link_group[t] for t in node_data.deps]),+ exported_deps = dedupe_by_value([target_to_link_group[t] for t in node_data.exported_deps]),+ shared_lib = None,+ exported_linker_flags = (node_data.linker_flags.exported_flags, node_data.linker_flags.exported_post_flags),+ )+ continue++ if _is_prebuilt_shared(node_data):+ shared_lib = _shared_lib_for_prebuilt_shared(+ ctx,+ cxx_toolchain,+ target,+ node_data,+ linkable_nodes,+ transitive_linkable_cache,+ platform,+ )+ link_group_linkable_nodes[group] = LinkGroupLinkableNode(+ link = node_data.link_infos[shlib_output_style].default,+ deps = [],+ exported_deps = [],+ shared_lib = shared_lib,+ # exported linker flags for shared libs are in their linkinfo itself and are not exported from dependents+ exported_linker_flags = None,+ )+ group_shared_libs[shared_lib.soname.ensure_str()] = MergedSharedLibrary(+ soname = shared_lib.soname.ensure_str(),+ lib = shared_lib,+ apk_module = group_data.apk_module,+ solib_constituents = [],+ solib_constituent_targets = [],+ is_actually_merged = False,+ primary_constituents = [target],+ )+ continue++ exported_linker_flags = []+ exported_linker_post_flags = []+ links = []++ if is_actually_merged and glue_linkable:+ links.append(set_link_info_link_whole(glue_linkable[1]))++ solib_constituents = []+ solib_constituent_targets = []+ group_deps = []+ group_exported_deps = []+ # (target, object) pairs for the JNI_OnLoad check. Collected here+ # because the constituents' link infos are not retained anywhere else,+ # and associated with the soname below once it is known.+ check_objects = []+ for key in group_data.constituents:+ expect(target_to_link_group[key] == group)+ node = linkable_nodes[key]++ default_solibs = list([shlib.soname.ensure_str() for shlib in node.shared_libs.libraries])+ if not default_solibs and node.preferred_linkage == Linkage("static"):+ default_solibs = [node.default_soname]++ for soname in default_solibs:+ included_default_solibs[soname] = True+ if node.include_in_android_mergemap:+ solib_constituents.append(soname)+ solib_constituent_targets.append(key)++ node = linkable_nodes[key]+ link_info = node.link_infos[archive_output_style].default++ if jni_onload_check_inputs != None:+ target_str = str(key.raw_target())+ for obj in _link_info_object_artifacts(link_info):+ check_objects.append((target_str, obj))++ # the propagated link info should already be wrapped with exported flags.+ link_info = wrap_link_info(+ link_info,+ pre_flags = node.linker_flags.flags,+ post_flags = node.linker_flags.post_flags,+ )+ exported_linker_flags.extend(node.linker_flags.exported_flags)+ exported_linker_post_flags.extend(node.linker_flags.exported_post_flags)+ links.append(set_link_info_link_whole(link_info))++ dep_groups = [target_to_link_group[dep] for dep in node.deps]+ group_deps.extend([dep_group for dep_group in dep_groups if dep_group != group])++ exported_dep_groups = [target_to_link_group[dep] for dep in node.exported_deps]+ group_exported_deps.extend([dep_group for dep_group in exported_dep_groups if dep_group != group])++ soname = group+ if not is_actually_merged:+ soname = linkable_nodes[group_data.constituents[0]].default_soname+ debug_info.with_default_soname.append((soname, group_data.constituents[0]))++ # Only groups that are actually merged are checked. A group of one is a+ # normal standalone library, where defining JNI_OnLoad is correct.+ if jni_onload_check_inputs != None and is_actually_merged:+ for target_str, obj in check_objects:+ jni_onload_check_inputs.append((soname, target_str, obj))++ output_path = _platform_output_path(soname, platform)++ link_merge_info = LinkGroupMergeInfo(+ label = group,+ deps = dedupe_by_value(group_deps),+ exported_deps = dedupe_by_value(group_exported_deps),+ constituent_link_infos = links,+ )+ link_args, shlib_deps, link_deps_graph = _create_merged_link_args(+ root_target = link_merge_info,+ linkable_nodes = link_group_linkable_nodes,+ cxx_toolchain = cxx_toolchain,+ )+ link_args = [link_args]+ if native_library_merge_linker_args_all:+ link_args += [LinkArgs(flags = native_library_merge_linker_args_all)]+ if soname in merge_linker_args:+ link_args += [LinkArgs(flags = merge_linker_args[soname])]++ # Emit the Middle Gatorade container from the merge link; {} when off.+ # @oss-disable[end= ]: mg_args = middle_gatorade_merge_args(ctx, output_path, cxx_toolchain)+ shared_lib = create_shared_lib(+ ctx,+ output_path = output_path,+ soname = soname,+ link_args = link_args,+ cxx_toolchain = cxx_toolchain,+ shared_lib_deps = [link_group_linkable_nodes[label].shared_lib.soname.ensure_str() for label in shlib_deps],+ label = group_data.constituents[0],+ can_be_asset = can_be_asset,+ # @oss-disable[end= ]: **mg_args,+ )++ link_group_linkable_nodes[group] = LinkGroupLinkableNode(+ link = LinkInfo(+ name = soname,+ pre_flags = exported_linker_flags,+ linkables = [+ SharedLibLinkable(+ lib = shared_lib.lib.output,+ )+ ],+ post_flags = exported_linker_post_flags,+ ),+ deps = link_merge_info.deps,+ exported_deps = link_merge_info.exported_deps,+ shared_lib = shared_lib,+ # exported linker flags for shared libs are in their linkinfo itself and are not exported from dependents+ exported_linker_flags = None,+ )+ group_shared_libs[soname] = MergedSharedLibrary(+ soname = soname,+ lib = shared_lib,+ apk_module = group_data.apk_module,+ solib_constituents = solib_constituents,+ solib_constituent_targets = solib_constituent_targets,+ is_actually_merged = is_actually_merged,+ primary_constituents = group_data.constituents,+ )++ debug_info.group_debug.setdefault(+ group,+ struct(+ soname = soname,+ merged = is_actually_merged,+ primary_constituents = group_data.constituents,+ real_constituents = link_deps_graph.keys(),+ shlib_deps = shlib_deps,+ exported_linker_flags = exported_linker_flags,+ exported_linker_post_flags = exported_linker_post_flags,+ non_asset_constituents = non_asset_constituents,+ ),+ )++ debug_info.missing_default_solibs.extend([d for d in default_shared_libs if d not in included_default_solibs])++ return group_shared_libs, debug_info++# The current default link strategies don't produce enough information in the+# SharedLibrary objects to perform relinking. To do that best, linking should be based on+# the LinkableGraph rather than the current approach with MergedLinkInfo.+# The overall plan for linking is to move to linkable graph-based linking, but for now+# we can do it just for the case that we need it.+def _create_all_relinkable_links(+ ctx: AnalysisContext,+ platform_to_original_native_linkables: dict[str, dict[str, SharedLibrary]],+ graph_node_map_by_platform: dict[str, dict[Label, LinkableNode]],+) -> (dict[str, dict[str, SharedLibrary]], dict[str, typing.Any]):+ final_platform_to_native_linkables = {}+ link_graphs_by_platform = {}+ for platform in platform_to_original_native_linkables:+ linkables, link_graphs = _create_relinkable_links(+ ctx,+ cxx_toolchain = ctx.attrs._cxx_toolchain[platform][CxxToolchainInfo],+ linkable_nodes = graph_node_map_by_platform[platform],+ platform = platform,+ )+ link_graphs_by_platform[platform] = link_graphs+ final_platform_to_native_linkables[platform] = linkables++ # sanity check that we produce the same list of linkables that are produced by standard linking.+ original_sonames = sorted(platform_to_original_native_linkables.keys())+ final_sonames = sorted(final_platform_to_native_linkables.keys())+ expect(original_sonames == final_sonames, "Unexpected differences in final sonames! {} {}".format(original_sonames, final_sonames))++ debug_outputs = {}++ # The biggest issue we could run into here is that we produce different link args than the original, so let's make that easy to debug.+ for platform in platform_to_original_native_linkables:+ for soname, lib in platform_to_original_native_linkables[platform].items():+ final = final_platform_to_native_linkables[platform][soname]+ original_args, _ = ctx.actions.write(+ "{}/{}/original.args".format(platform, soname),+ [unpack_link_args(args, LinkOrdering("topological")) for args in lib.link_args] if lib.link_args else "",+ allow_args = True,+ has_content_based_path = False,+ )+ final_args, _ = ctx.actions.write(+ "{}/{}/final.args".format(platform, soname),+ [unpack_link_args(args, LinkOrdering("topological")) for args in final.link_args] if final.link_args else "",+ allow_args = True,+ has_content_based_path = False,+ )+ debug_outputs["{}/{}/original.args".format(platform, soname)] = original_args+ debug_outputs["{}/{}/final.args".format(platform, soname)] = final_args++ if lib.label in link_graphs_by_platform[platform]:+ link_graph = ctx.actions.write_json(+ "{}/{}/link.graph".format(platform, soname),+ link_graphs_by_platform[platform][lib.label],+ pretty = True,+ has_content_based_path = False,+ )+ debug_outputs["{}/{}/link.graph".format(platform, soname)] = link_graph++ # TODO(cjhopman): should we also just produce a diff here? We could also consider creating sort of a merged diff or a list+ # of the differing argsfiles.+ # We can't compare them eagerly because the link args have large tsets that we don't want to traverse at analysis time.++ return final_platform_to_native_linkables, debug_outputs++def _create_relinkable_links(+ ctx: AnalysisContext, *, cxx_toolchain: CxxToolchainInfo, linkable_nodes: dict[Label, LinkableNode], platform: str+) -> (dict[str, SharedLibrary], dict[Label, dict[Label, list[Label]]]):+ linkable_nodes_graph = {target: value.deps + value.exported_deps for target, value in linkable_nodes.items()}+ shared_libs = {}+ shared_lib_overrides = {}+ transitive_linkable_cache = {}+ debug_link_deps = {}+ for target in post_order_traversal(linkable_nodes_graph):+ node = linkable_nodes[target]+ if node.preferred_linkage == Linkage("static") or not _has_linkable(node):+ continue++ if _is_prebuilt_shared(node):+ shared_lib = _shared_lib_for_prebuilt_shared(ctx, cxx_toolchain, target, node, linkable_nodes, transitive_linkable_cache, platform)+ else:+ soname = node.default_soname+ output_path = "relinkable-libs/{}/{}".format(platform, soname)+ link_args, shlib_deps, link_deps_graph = _create_link_args(+ cxx_toolchain = cxx_toolchain,+ root_target = target,+ node = node,+ graph = linkable_nodes,+ shared_lib_overrides = shared_lib_overrides,+ )+ debug_link_deps[target] = link_deps_graph+ shared_lib = create_shared_lib(+ ctx,+ output_path = output_path,+ soname = soname,+ link_args = [link_args],+ cxx_toolchain = cxx_toolchain,+ shared_lib_deps = [shared_lib_overrides[lib].name for lib in shlib_deps if lib in shared_lib_overrides],+ label = target,+ can_be_asset = node.can_be_asset,+ )+ shared_lib_overrides[target] = LinkInfo(+ name = shared_lib.soname.ensure_str(),+ pre_flags = node.linker_flags.exported_flags,+ linkables = [+ SharedLibLinkable(+ lib = shared_lib.lib.output,+ )+ ],+ post_flags = node.linker_flags.exported_post_flags,+ )+ shared_libs[shared_lib.soname.ensure_str()] = shared_lib++ return {lib.soname.ensure_str(): lib for lib in shared_libs.values()}, debug_link_deps++def _create_link_args(+ *,+ cxx_toolchain: CxxToolchainInfo,+ root_target: Label,+ node: LinkableNode,+ graph: dict[Label, LinkableNode],+ shared_lib_overrides: dict[Label, LinkInfo] | None = None,+) -> (LinkArgs, list[Label], dict[Label, list[Label]]):+ if LinkOrdering(cxx_toolchain.linker_info.link_ordering) != LinkOrdering("topological"):+ fail("don't yet support link ordering {}".format(cxx_toolchain.linker_info.link_ordering))++ # TODO(cjhopman): verify picbehavior == pic+ link_strategy = node.default_link_strategy+ if not shared_lib_overrides:+ shared_lib_overrides = {}++ link_traversal_cache = {}++ def link_traversal(label: Label) -> list[Label]:+ def link_traversal_deps(label):+ node = graph[label]+ if label == root_target:+ return node.deps + node.exported_deps+ actual_linkable_type = get_lib_output_style(link_strategy, node.preferred_linkage, PicBehavior("supported"))+ if actual_linkable_type == LibOutputStyle("shared_lib"):+ return node.exported_deps+ else:+ return node.deps + node.exported_deps++ res = link_traversal_cache.get(label, None)+ if res:+ return res+ res = link_traversal_deps(label)+ link_traversal_cache[label] = res+ return res++ links = []+ shlib_deps = []+ for target in rust_matching_topological_traversal(None, [root_target], link_traversal):+ is_root = target == root_target+ node = graph[target]+ preferred_linkable_type = get_lib_output_style(link_strategy, node.preferred_linkage, PicBehavior("supported"))++ if is_root:+ link_info = node.link_infos[LibOutputStyle("pic_archive")].default+ link_info = wrap_link_info(+ link_info,+ pre_flags = node.linker_flags.flags,+ post_flags = node.linker_flags.post_flags,+ )+ links.append(set_link_info_link_whole(link_info))+ elif preferred_linkable_type == LibOutputStyle("shared_lib"):+ if target in shared_lib_overrides:+ links.append(shared_lib_overrides[target])+ else:+ links.append(node.link_infos[LibOutputStyle("shared_lib")].default)+ shlib_deps.append(target)+ else:+ links.append(node.link_infos[preferred_linkable_type].default)++ extra_runtime_flags = cxx_toolchain.linker_info.shared_dep_runtime_ld_flags or []+ if extra_runtime_flags:+ links.append(LinkInfo(pre_flags = extra_runtime_flags))+ return LinkArgs(infos = links), shlib_deps, link_traversal_cache++# Equivalent to _create_link_args but for somerge+def _create_merged_link_args(+ *, cxx_toolchain: CxxToolchainInfo, root_target: LinkGroupMergeInfo, linkable_nodes: dict[GroupLabel, LinkGroupLinkableNode]+) -> (LinkArgs, list[GroupLabel], dict[GroupLabel, list[GroupLabel]]):+ if LinkOrdering(cxx_toolchain.linker_info.link_ordering) != LinkOrdering("topological"):+ fail("don't yet support link ordering {}".format(cxx_toolchain.linker_info.link_ordering))++ link_traversal_cache = {}++ def link_traversal(label: GroupLabel) -> list[GroupLabel]:+ def link_traversal_deps(label: GroupLabel):+ if label == root_target.label:+ return root_target.deps + root_target.exported_deps++ linkable_node = linkable_nodes[label]+ if linkable_node.shared_lib:+ return linkable_node.exported_deps+ else:+ return linkable_node.deps + linkable_node.exported_deps++ res = link_traversal_cache.get(label, None)+ if res:+ return res+ res = link_traversal_deps(label)+ link_traversal_cache[label] = res+ return res++ links = []+ shlib_deps = []+ for label in rust_matching_topological_traversal(None, [root_target.label], link_traversal):+ if label == root_target.label:+ links.extend(root_target.constituent_link_infos)+ else:+ linkable_node = linkable_nodes[label]+ links.append(linkable_node.link)+ if linkable_node.shared_lib:+ shlib_deps.append(label)++ extra_runtime_flags = cxx_toolchain.linker_info.shared_dep_runtime_ld_flags or []+ if extra_runtime_flags:+ links.append(LinkInfo(pre_flags = extra_runtime_flags))+ return LinkArgs(infos = links), shlib_deps, link_traversal_cache++def _bolt_libraries(+ ctx: AnalysisContext,+ libraries_by_platform: dict[str, dict[str, SharedLibrary]],+ bolt_args: dict[str, ArgLike],+ native_cmd_entries = None,+ record_underlying_link: bool = False,+) -> (+ dict[str, dict[str, SharedLibrary]],+ dict[str, dict[str, SharedLibrary]],+):+ bolted_libraries_by_platform = {}+ pre_bolt_libraries_by_platform = {}++ for platform, shared_libraries in libraries_by_platform.items():+ cxx_toolchain = ctx.attrs._cxx_toolchain[platform][CxxToolchainInfo]+ bolted_libraries = bolted_libraries_by_platform.setdefault(platform, {})+ pre_bolt_libraries = pre_bolt_libraries_by_platform.setdefault(platform, {})++ for soname, _ in shared_libraries.items():+ original_shared_library = shared_libraries[soname]+ if not soname in bolt_args:+ bolted_libraries[soname] = original_shared_library+ continue++ # On plain-link apps (record_underlying_link), record the bolted soname's underlying link+ # BEFORE the swap: the bolted/pre-bolt objects below are command-less, so finalization+ # skips them and this plain link would otherwise be lost. When merging/relinking, that+ # underlying command is already captured at the merge/relink site, so skip it here.+ if record_underlying_link:+ record_link_command(native_cmd_entries, "link", platform, soname, original_shared_library.lib)++ # Create pre-BOLT copy with .pre_bolt.so suffix+ pre_bolt_soname = soname.removesuffix(".so") + ".pre_bolt.so"+ pre_bolt_output_path = "pre-bolt-libs/{}/{}".format(platform, pre_bolt_soname)+ pre_bolt_copy = ctx.actions.copy_file(pre_bolt_output_path, original_shared_library.lib.output, has_content_based_path = False)++ # Create pre-BOLT SharedLibrary object+ pre_bolt_linked_object = LinkedObject(+ output = pre_bolt_copy,+ unstripped_output = pre_bolt_copy,+ )++ pre_bolt_shared_lib = create_shlib(+ lib = pre_bolt_linked_object,+ stripped_lib = strip_lib(ctx, cxx_toolchain, pre_bolt_linked_object.output),+ can_be_asset = original_shared_library.can_be_asset,+ for_primary_apk = False,+ soname = pre_bolt_soname,+ label = original_shared_library.label,+ )++ pre_bolt_libraries[pre_bolt_soname] = pre_bolt_shared_lib++ output_path = "bolt-libs/{}/{}".format(platform, soname)++ bolted_libraries[soname] = _create_bolt_lib(+ ctx = ctx,+ cxx_toolchain = cxx_toolchain,+ prebolt_lib = original_shared_library,+ output_path = output_path,+ bolt_args = bolt_args[soname],+ native_cmd_entries = native_cmd_entries,+ platform = platform,+ )++ return bolted_libraries_by_platform, pre_bolt_libraries_by_platform++# When linking shared libraries, by default, all symbols are exported from the library. In a+# particular application, though, many of those symbols may never be used. Ideally, in each apk,+# each shared library would only export the minimal set of symbols that are used by other libraries+# in the apk. This would allow the linker to remove any dead code within the library (the linker+# can strip all code that is unreachable from the set of exported symbols).+#+# The native relinker tries to remedy the situation. When enabled for an apk, the native+# relinker will take the set of libraries in the apk and relink them in reverse order telling the+# linker to only export those symbols that are referenced by a higher library.+#+# The way this works is that the relinker does a topological traversal of the linked libraries (i.e.+# top-down, visiting nodes before their dependencies, this is the opposite order of most things we do+# in a build) and does:+# 1. extract the set of global symbols by the original lib+# 2. intersect that with the set of undefined symbols in all transitive dependents (i.e. higher in the graph) and+# rules for required symbols (Java_*, Jni_Onload, relinker blocklist)+# 3. write a version script that says to make public only those symbols from (2)+# 4. link the lib with the exact same link line + the version script. Note that this means that the relinked libraries each are+# actually linked against non-relinked ones. This does mean there's some risk of not detecting missing symbols (though mostly+# only if they are caused by the relinker changes themselves).+# 5. extract the list of undefined symbols in the relinked libs (i.e. those symbols needed from dependencies and what had been+# used in (1) above from higher nodes).++def relink_libraries(+ ctx: AnalysisContext, libraries_by_platform: dict[str, dict[str, SharedLibrary]], native_cmd_entries = None+) -> dict[str, dict[str, SharedLibrary]]:+ relinker_extra_deps = getattr(ctx.attrs, "relinker_extra_deps", None)+ relinker_extra_args = getattr(ctx.attrs, "relinker_extra_args", {})+ relinker_extra_args_all = getattr(ctx.attrs, "relinker_extra_args_all", [])+ red_linkables = {}+ if relinker_extra_deps:+ for red_elem in relinker_extra_deps:+ for platform, red in red_elem.items():+ red_link_graph = red.get(LinkableGraph)+ expect(red_link_graph != None, "relinker_extra_deps (`{}`) should be a linkable target", red.label)+ red_linkable = red_link_graph.nodes.value.linkable+ expect(red_linkable != None, "relinker_extra_deps (`{}`) should be a linkable target", red.label)+ expect(red_linkable.preferred_linkage == Linkage("static"), "buck2 currently only supports preferred_linkage='static' relinker_extra_deps")+ if platform not in red_linkables:+ red_linkables[platform] = []+ red_linkables[platform].append((red.label, red_linkable.link_infos[LibOutputStyle("pic_archive")].default))++ relinked_libraries_by_platform = {}+ for platform, shared_libraries in libraries_by_platform.items():+ cxx_toolchain = ctx.attrs._cxx_toolchain[platform][CxxToolchainInfo]++ relinked_libraries = relinked_libraries_by_platform.setdefault(platform, {})+ unsupported_libs = {}+ shlib_graph = {}+ rev_shlib_graph = {}+ for soname, solib in shared_libraries.items():+ shlib_graph[soname] = []+ rev_shlib_graph.setdefault(soname, [])+ if solib.shlib_deps == None or solib.link_args == None:+ unsupported_libs[soname] = True+ else:+ for dep in solib.shlib_deps:+ shlib_graph[soname].append(dep)+ rev_shlib_graph.setdefault(dep, []).append(soname)+ needed_symbols_files = {}+ for soname in pre_order_traversal(shlib_graph):+ if soname in unsupported_libs:+ relinked_libraries[soname] = shared_libraries[soname]+ continue++ original_shared_library = shared_libraries[soname]+ output_path = "xdso-dce-relinker-libs/{}/{}".format(platform, soname)++ provided_symbols_file = extract_provided_symbols(ctx, cxx_toolchain, original_shared_library.lib.output)+ needed_symbols_for_this = [needed_symbols_files.get(rdep) for rdep in rev_shlib_graph[soname]]+ relinker_version_script = ctx.actions.declare_output(output_path + ".relinker.version_script", has_content_based_path = False)+ create_relinker_version_script(+ ctx.actions,+ output = relinker_version_script,+ relinker_allowlist = [regex(s) for s in ctx.attrs.relinker_whitelist],+ provided_symbols = provided_symbols_file,+ needed_symbols = needed_symbols_for_this,+ )+ relinker_link_args = (+ original_shared_library.link_args+ + [LinkArgs(flags = relinker_extra_args_all)]+ + ([LinkArgs(infos = [set_link_info_link_whole(red_linkable[1]) for red_linkable in red_linkables[platform]])] if len(red_linkables) > 0 else [])+ ++ # Add per-library linker args from relinker_extra_args attribute+ ([LinkArgs(flags = relinker_extra_args[soname])] if soname in relinker_extra_args else [])+ ++ # We add the version script last to allow easy post-processing if needed.+ [LinkArgs(flags = [cmd_args(relinker_version_script, format = "-Wl,--version-script={}")])]+ )++ extra_args = {} # @oss-enable+ # @oss-disable[end= ]: extra_args = add_gatorade_relinker_args(ctx, cxx_toolchain, output_path, soname, platform)+ relinker_output_args = get_extra_relinker_args(ctx, output_path, soname)+ extra_args = merge_extra_linker_args([extra_args, relinker_output_args])+ shared_lib = create_shared_lib(+ ctx,+ output_path = output_path,+ soname = soname,+ link_args = relinker_link_args,+ cxx_toolchain = cxx_toolchain,+ shared_lib_deps = original_shared_library.shlib_deps,+ label = original_shared_library.label,+ can_be_asset = original_shared_library.can_be_asset,+ **extra_args,+ )+ needed_symbols_from_this = extract_undefined_symbols(ctx, cxx_toolchain, shared_lib.lib.output)+ unioned_needed_symbols_file = ctx.actions.declare_output(output_path + ".all_needed_symbols", has_content_based_path = False)+ union_needed_symbols(ctx.actions, unioned_needed_symbols_file, needed_symbols_for_this + [needed_symbols_from_this])+ needed_symbols_files[soname] = unioned_needed_symbols_file++ relinked_libraries[soname] = shared_lib+ record_link_command(native_cmd_entries, "relink", platform, soname, shared_lib.lib)++ return relinked_libraries_by_platform++def _relink_for_native_libs(ctx: AnalysisContext, libraries_by_platform: dict[str, dict[str, SharedLibrary]], native_cmd_entries = None) -> tuple:+ return (relink_libraries(ctx, libraries_by_platform, native_cmd_entries), {}) # @oss-enable+ # @oss-disable[end= ]: return relink_for_native_libs(ctx, libraries_by_platform, relink_libraries, create_shared_lib, native_cmd_entries)++def extract_provided_symbols(ctx: AnalysisContext, toolchain: CxxToolchainInfo, lib: Artifact) -> Artifact:+ return extract_defined_syms(ctx, toolchain, lib, "relinker_extract_provided_symbols")++def create_relinker_version_script(+ actions: AnalysisActions, relinker_allowlist: list[regex], output: Artifact, provided_symbols: Artifact, needed_symbols: list[Artifact]+):+ def create_version_script(ctx, artifacts, outputs):+ all_needed_symbols = {}+ for symbols_file in needed_symbols:+ for line in artifacts[symbols_file].read_string().splitlines():+ all_needed_symbols[line] = True++ symbols_to_keep = []+ for symbol in artifacts[provided_symbols].read_string().splitlines():+ keep_symbol = False+ if symbol in all_needed_symbols:+ keep_symbol = True+ elif symbol == "JNI_OnLoad":+ keep_symbol = True+ elif symbol.startswith("Java_"):+ keep_symbol = True+ else:+ for pattern in relinker_allowlist:+ if pattern.match(symbol):+ keep_symbol = True+ break++ if keep_symbol:+ symbols_to_keep.append(symbol)++ version_script = "{\n"+ # @oss-disable[end= ]: if is_late_gatorade_enabled(ctx):+ # @oss-disable[end= ]: symbols_to_keep.append("*_Gatorade_Thunk")+ if symbols_to_keep:+ version_script += "global:\n"+ for symbol in symbols_to_keep:+ version_script += " {};\n".format(symbol)+ version_script += "local: *;\n"+ version_script += "};\n"+ ctx.actions.write(outputs[output], version_script)++ actions.dynamic_output(dynamic = needed_symbols + [provided_symbols], inputs = [], outputs = [output.as_output()], f = create_version_script)++def extract_undefined_symbols(ctx: AnalysisContext, toolchain: CxxToolchainInfo, lib: Artifact) -> Artifact:+ return extract_undefined_syms(ctx, toolchain, lib, "relinker_extract_undefined_symbols")++def union_needed_symbols(actions: AnalysisActions, output: Artifact, needed_symbols: list[Artifact]):+ def compute_union(ctx, artifacts, outputs):+ unioned_symbols = {}+ for symbols_file in needed_symbols:+ for line in artifacts[symbols_file].read_string().splitlines():+ unioned_symbols[line] = True+ symbols = sorted(unioned_symbols.keys())+ ctx.actions.write(outputs[output], symbols)++ actions.dynamic_output(dynamic = needed_symbols, inputs = [], outputs = [output.as_output()], f = compute_union)++def strip_lib(ctx: AnalysisContext, cxx_toolchain: CxxToolchainInfo, shlib: Artifact, output_path: [str, None] = None):+ strip_flags = cmd_args(get_strip_non_global_flags(cxx_toolchain))+ return strip_object(+ ctx,+ cxx_toolchain,+ shlib,+ strip_flags,+ output_path = output_path,+ allow_cache_upload = True,+ )++def create_shared_lib(+ ctx: AnalysisContext,+ *,+ output_path: str,+ soname: str,+ link_args: list[LinkArgs],+ cxx_toolchain: CxxToolchainInfo,+ shared_lib_deps: list[str],+ label: Label,+ can_be_asset: bool,+ extra_linker_outputs_factory: typing.Callable | None = None,+ extra_linker_outputs_flags_factory: typing.Callable | None = None,+) -> SharedLibrary:+ for link_arg in link_args:+ flags = link_arg.flags or []+ for info in link_arg.infos or []:+ flags += info.pre_flags or []+ flags += info.post_flags or []+ for flag in flags:+ flag = str(flag)+ if flag.endswith("--exclude-libs,ALL") or flag.endswith("--exclude-libs=ALL"):+ fail(+ "The behavior of --exclude-libs,ALL is not predictable when building Android binaries and may cause runtime crashes, remove it from {} (or its merged constituents)".format(+ label+ )+ )+ link_result = cxx_link_shared_library(+ ctx = ctx,+ output = output_path,+ name = soname,+ opts = link_options(+ links = link_args,+ link_execution_preference = LinkExecutionPreference("any"),+ identifier = output_path,+ strip = False,+ cxx_toolchain = cxx_toolchain,+ extra_linker_outputs_factory = extra_linker_outputs_factory,+ extra_linker_outputs_flags_factory = extra_linker_outputs_flags_factory,+ allow_cache_upload = True,+ ),+ )++ shlib = link_result.linked_object+ return create_shlib(+ lib = shlib,+ stripped_lib = strip_lib(ctx, cxx_toolchain, shlib.output),+ shlib_deps = shared_lib_deps,+ link_args = link_args,+ can_be_asset = can_be_asset,+ for_primary_apk = False,+ soname = soname,+ label = label,+ extra_outputs = link_result.extra_outputs,+ )++def _create_bolt_lib(+ ctx: AnalysisContext,+ cxx_toolchain: CxxToolchainInfo,+ prebolt_lib: SharedLibrary,+ output_path: str,+ bolt_args: list[ArgLike],+ native_cmd_entries = None,+ platform = None,+) -> SharedLibrary:+ soname = prebolt_lib.soname.ensure_str()+ bolt_output = ctx.actions.declare_output(output_path, has_content_based_path = False)+ action_execution_properties = get_action_execution_attributes(LinkExecutionPreference("any"))++ args = cmd_args(+ cmd_args(cxx_toolchain.binary_utilities_info.bolt),+ prebolt_lib.lib.output,+ "-o",+ bolt_output.as_output(),+ bolt_args,+ )++ ctx.actions.run(+ args,+ category = "bolt",+ prefer_local = action_execution_properties.prefer_local,+ prefer_remote = action_execution_properties.prefer_remote,+ local_only = action_execution_properties.local_only,+ identifier = output_path,+ allow_cache_upload = True,+ )++ # Record the bolt command for [native_build_commands], referencing the plain output artifact+ # (not `as_output()`, which cannot be re-serialized by write_json).+ if native_cmd_entries != None:+ native_cmd_entries.append(+ native_build_command_entry(+ kind = "bolt",+ category = "bolt",+ arch = platform,+ soname = soname,+ output = bolt_output.short_path,+ argv = cmd_args(+ cmd_args(cxx_toolchain.binary_utilities_info.bolt),+ prebolt_lib.lib.output,+ "-o",+ bolt_output,+ bolt_args,+ ),+ identifier = output_path,+ )+ )++ linked_object = LinkedObject(+ output = bolt_output,+ unstripped_output = bolt_output,+ )++ return create_shlib(+ lib = linked_object,+ stripped_lib = strip_lib(ctx, cxx_toolchain, linked_object.output),+ can_be_asset = prebolt_lib.can_be_asset,+ for_primary_apk = False,+ soname = soname,+ label = prebolt_lib.label,+ )
@@ -0,0 +1,696 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:resources.bzl", "gather_resources")+load("@prelude//android:aapt2_link.bzl", "get_aapt2_link", "get_module_manifest_in_proto_format")+load("@prelude//android:android_manifest.bzl", "generate_android_manifest")+load(+ "@prelude//android:android_providers.bzl",+ "AndroidBinaryResourcesInfo",+ "AndroidPackageableInfo",+ "AndroidResourceInfo",+ "ExopackageResourcesInfo",+ "ManifestTSet", # @unused Used as type+)+load("@prelude//android:android_resource.bzl", "aapt2_compile")+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//android:r_dot_java.bzl", "generate_r_dot_javas")+load("@prelude//android:voltron.bzl", "ROOT_MODULE", "get_apk_module_graph_info", "is_root_module")+load("@prelude//decls:android_rules.bzl", "RType")+load(+ "@prelude//java:java_providers.bzl",+ "JavaPackagingDep", # @unused Used as type+)+load("@prelude//utils:expect.bzl", "expect")+load("@prelude//utils:utils.bzl", "flatten")++_FilteredResourcesOutput = record(+ resource_infos = list[AndroidResourceInfo],+ voltron_res = list[Artifact],+ override_symbols = Artifact | None,+ string_files_list = Artifact | None,+ string_files_res_dirs = list[Artifact],+)++def get_android_binary_resources_info(+ ctx: AnalysisContext,+ deps: list[Dependency],+ android_packageable_info: AndroidPackageableInfo,+ java_packaging_deps: list[JavaPackagingDep],+ use_proto_format: bool,+ referenced_resources_lists: list[Artifact],+ apk_module_graph_file: Artifact | None = None,+ manifest_entries: dict = {},+ resource_infos_to_exclude: set[TargetLabel] = set(),+ r_dot_java_packages_to_exclude: set[str] = set(),+ generate_strings_and_ids_separately: [bool, None] = True,+ aapt2_preferred_density: [str, None] = None,+) -> AndroidBinaryResourcesInfo:+ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]++ # Use reverse topological sort in resource merging to make sure a resource target will overwrite its dependencies.+ unfiltered_resource_infos = reversed([+ resource_info+ for resource_info in list(+ android_packageable_info.resource_infos.traverse(ordering = "topological") if android_packageable_info.resource_infos else []+ )+ if resource_info.raw_target not in resource_infos_to_exclude+ ])+ filtered_resources_output = _maybe_filter_resources(+ ctx,+ unfiltered_resource_infos,+ android_toolchain,+ )+ resource_infos = filtered_resources_output.resource_infos++ android_manifest = get_manifest(ctx, android_packageable_info.manifests, manifest_entries, should_replace_application_id_placeholders = True)++ non_proto_format_aapt2_link_info, proto_format_aapt2_link_info = get_aapt2_link(+ ctx,+ ctx.attrs._android_toolchain[AndroidToolchainInfo],+ resource_infos,+ android_manifest,+ manifest_entries = getattr(ctx.attrs, "manifest_entries", {}),+ includes_vector_drawables = getattr(ctx.attrs, "includes_vector_drawables", False),+ no_resource_removal = True,+ package_id_offset = 0,+ should_keep_raw_values = getattr(ctx.attrs, "aapt2_keep_raw_values", False),+ resource_stable_ids = getattr(ctx.attrs, "resource_stable_ids", None),+ compiled_resource_apks = getattr(ctx.attrs, "compiled_resource_apks", []),+ additional_aapt2_params = getattr(ctx.attrs, "additional_aapt_params", []),+ extra_filtered_resources = getattr(ctx.attrs, "extra_filtered_resources", []),+ locales = getattr(ctx.attrs, "locales", []) or getattr(ctx.attrs, "locales_for_binary_resources", []),+ filter_locales = getattr(ctx.attrs, "aapt2_locale_filtering", False) or bool(getattr(ctx.attrs, "locales_for_binary_resources", [])),+ preferred_density = aapt2_preferred_density,+ )++ module_manifests = _get_module_manifests(+ ctx,+ manifest_entries,+ apk_module_graph_file,+ use_proto_format,+ non_proto_format_aapt2_link_info.primary_resources_apk,+ )++ aapt2_link_info = proto_format_aapt2_link_info if use_proto_format else non_proto_format_aapt2_link_info++ prebuilt_jars = [packaging_dep.jar for packaging_dep in java_packaging_deps if packaging_dep.is_prebuilt_jar]++ cxx_resources = get_cxx_resources(ctx, deps)+ is_exopackaged_enabled_for_resources = "resources" in getattr(ctx.attrs, "exopackage_modes", [])+ primary_resources_apk, exopackaged_assets, exopackaged_assets_hash, module_assets_apks_dir = _merge_assets(+ ctx,+ is_exopackaged_enabled_for_resources,+ aapt2_link_info.primary_resources_apk,+ resource_infos,+ cxx_resources,+ use_proto_format, # indicates that this is a .aab build+ apk_module_graph_file,+ )++ if is_exopackaged_enabled_for_resources:+ r_dot_txt = ctx.actions.declare_output("after_exo/R.txt", has_content_based_path = False)+ primary_resources_apk = ctx.actions.declare_output("after_exo/primary_resources_apk.apk", has_content_based_path = False)+ exo_resources = ctx.actions.declare_output("exo_resources.apk", has_content_based_path = False)+ exo_resources_hash = ctx.actions.declare_output("exo_resources.apk.hash", has_content_based_path = False)+ ctx.actions.run(+ cmd_args([+ android_toolchain.exo_resources_rewriter[RunInfo],+ "--original-r-dot-txt",+ aapt2_link_info.r_dot_txt,+ "--new-r-dot-txt",+ r_dot_txt.as_output(),+ "--original-primary-apk-resources",+ aapt2_link_info.primary_resources_apk,+ "--new-primary-apk-resources",+ primary_resources_apk.as_output(),+ "--exo-resources",+ exo_resources.as_output(),+ "--exo-resources-hash",+ exo_resources_hash.as_output(),+ ]),+ category = "write_exo_resources",+ allow_cache_upload = True,+ )++ exopackage_info = ExopackageResourcesInfo(+ assets = exopackaged_assets,+ assets_hash = exopackaged_assets_hash,+ res = exo_resources,+ res_hash = exo_resources_hash,+ )+ else:+ exopackage_info = None+ r_dot_txt = aapt2_link_info.r_dot_txt++ override_symbols_paths = [filtered_resources_output.override_symbols] if filtered_resources_output.override_symbols else []+ resources = [resource for resource in resource_infos if resource.res != None]+ r_dot_java_infos = generate_r_dot_javas(+ ctx,+ ctx.attrs._android_toolchain[AndroidToolchainInfo].merge_android_resources[RunInfo],+ resources,+ get_effective_banned_duplicate_resource_types(+ getattr(ctx.attrs, "duplicate_resource_behavior", "allow_by_default"),+ getattr(ctx.attrs, "allowed_duplicate_resource_types", []),+ getattr(ctx.attrs, "banned_duplicate_resource_types", []),+ ),+ [r_dot_txt],+ override_symbols_paths,+ getattr(ctx.attrs, "duplicate_resource_whitelist", None),+ referenced_resources_lists,+ generate_strings_and_ids_separately = generate_strings_and_ids_separately,+ remove_classes = ["{}.R".format(r_dot_java_package) for r_dot_java_package in r_dot_java_packages_to_exclude],+ )+ string_source_map = _maybe_generate_string_source_map(+ ctx.actions,+ getattr(ctx.attrs, "build_string_source_map", False),+ [resource.res for resource in resources if resource.res != None],+ android_toolchain,+ )+ voltron_string_source_map = _maybe_generate_string_source_map(+ ctx.actions,+ getattr(ctx.attrs, "is_voltron_language_pack_enabled", False),+ filtered_resources_output.voltron_res,+ android_toolchain,+ is_voltron_string_source_map = True,+ )++ packaged_string_assets = _maybe_package_strings_as_assets(+ ctx,+ filtered_resources_output.string_files_list,+ filtered_resources_output.string_files_res_dirs,+ r_dot_txt,+ android_toolchain,+ )++ return AndroidBinaryResourcesInfo(+ exopackage_info = exopackage_info,+ manifest = android_manifest,+ module_manifests = module_manifests,+ module_assets = module_assets_apks_dir,+ packaged_string_assets = packaged_string_assets,+ primary_resources_apk = primary_resources_apk,+ proguard_config_file = aapt2_link_info.proguard_config_file,+ r_dot_java_infos = r_dot_java_infos,+ string_source_map = string_source_map,+ voltron_string_source_map = voltron_string_source_map,+ jar_files_that_may_contain_resources = prebuilt_jars,+ unfiltered_resource_infos = unfiltered_resource_infos,+ )++def _maybe_filter_resources(ctx: AnalysisContext, resources: list[AndroidResourceInfo], android_toolchain: AndroidToolchainInfo) -> _FilteredResourcesOutput:+ resources_filter_strings = getattr(ctx.attrs, "resource_filter", [])+ resources_filter = _get_resources_filter(resources_filter_strings)+ resource_compression_mode = getattr(ctx.attrs, "resource_compression", "disabled")+ is_store_strings_as_assets = _is_store_strings_as_assets(resource_compression_mode)+ locales = getattr(ctx.attrs, "locales", None)+ use_aapt2_locale_filtering = getattr(ctx.attrs, "aapt2_locale_filtering", False)+ needs_resource_filtering_for_locales = locales != None and len(locales) > 0 and not use_aapt2_locale_filtering+ post_filter_resources_cmd = getattr(ctx.attrs, "post_filter_resources_cmd", None)++ needs_resource_filtering = (+ resources_filter != None or is_store_strings_as_assets or needs_resource_filtering_for_locales or post_filter_resources_cmd != None+ )++ if not needs_resource_filtering:+ return _FilteredResourcesOutput(+ resource_infos = resources,+ voltron_res = [resource.res for resource in resources if resource.res != None],+ override_symbols = None,+ string_files_list = None,+ string_files_res_dirs = [],+ )++ res_to_out_res_dir = {}+ voltron_res_to_out_res_dir = {}+ res_infos_with_no_res = []+ skip_crunch_pngs = getattr(ctx.attrs, "skip_crunch_pngs", None) or False+ is_voltron_language_pack_enabled = getattr(ctx.attrs, "is_voltron_language_pack_enabled", False)+ for i, resource in enumerate(resources):+ if resource.res == None:+ res_infos_with_no_res.append(resource)+ else:+ filtered_res = ctx.actions.declare_output("filtered_res_{}".format(i), dir = True, has_content_based_path = True)+ res_to_out_res_dir[resource.res] = filtered_res++ if is_voltron_language_pack_enabled:+ filtered_res_for_voltron = ctx.actions.declare_output("filtered_res_for_voltron_{}".format(i), dir = True, has_content_based_path = True)+ voltron_res_to_out_res_dir[resource.res] = filtered_res_for_voltron++ filter_resources_cmd = cmd_args(android_toolchain.filter_resources[RunInfo])+ in_res_dirs = res_to_out_res_dir.keys()+ filter_resources_cmd.add(+ cmd_args(+ hidden = in_res_dirs + [out_res.as_output() for out_res in res_to_out_res_dir.values()],+ )+ )+ filter_resources_cmd.add([+ "--in-res-dir-to-out-res-dir-map",+ ctx.actions.write_json(+ "in_res_dir_to_out_res_dir_map",+ {"res_dir_map": {res: out_res.as_output() for (res, out_res) in res_to_out_res_dir.items()}},+ has_content_based_path = False,+ ),+ ])++ if is_voltron_language_pack_enabled:+ filter_resources_cmd.add(cmd_args(hidden = [out_res.as_output() for out_res in voltron_res_to_out_res_dir.values()]))+ filter_resources_cmd.add([+ "--voltron-in-res-dir-to-out-res-dir-map",+ ctx.actions.write_json(+ "voltron_in_res_dir_to_out_res_dir_map",+ {"res_dir_map": {voltron_res: out_res.as_output() for (voltron_res, out_res) in voltron_res_to_out_res_dir.items()}},+ has_content_based_path = False,+ ),+ ])++ if resources_filter:+ filter_resources_cmd.add([+ "--target-densities",+ ",".join(resources_filter.densities),+ ])++ all_strings_files_list = None+ all_strings_files_res_dirs = []+ if is_store_strings_as_assets:+ all_strings_files_list = ctx.actions.declare_output("all_strings_files", has_content_based_path = False)+ all_strings_files_res_dirs = in_res_dirs+ filter_resources_cmd.add([+ "--enable-string-as-assets-filtering",+ "--string-files-list-output",+ all_strings_files_list.as_output(),+ ])++ packaged_locales = getattr(ctx.attrs, "packaged_locales", [])+ if packaged_locales:+ filter_resources_cmd.add([+ "--packaged-locales",+ ",".join(packaged_locales),+ ])++ not_filtered_string_dirs = [resource.res for resource in resources if not resource.allow_strings_as_assets_resource_filtering]+ if not_filtered_string_dirs:+ filter_resources_cmd.add([+ "--not-filtered-string-dirs",+ ctx.actions.write("not_filtered_string_dirs", not_filtered_string_dirs, has_content_based_path = False),+ ])++ allowlisted_locales = {resource.res: resource.allowlisted_locales for resource in resources if resource.allowlisted_locales}+ filter_resources_cmd.add([+ "--allowlisted-locales",+ ctx.actions.write_json("allowlisted_locales", allowlisted_locales, has_content_based_path = False),+ ])++ if needs_resource_filtering_for_locales:+ filter_resources_cmd.add([+ "--locales",+ ",".join(locales),+ ])++ override_symbols_artifact = None+ if post_filter_resources_cmd != None:+ override_symbols_artifact = ctx.actions.declare_output("post_filter_resources_cmd/R.json", has_content_based_path = False)+ filter_resources_cmd.add([+ "--post-filter-resources-cmd",+ post_filter_resources_cmd,+ "--post-filter-resources-cmd-override-symbols-output",+ override_symbols_artifact.as_output(),+ ])++ ctx.actions.run(+ filter_resources_cmd,+ local_only = post_filter_resources_cmd != None and "run_post_filter_resources_cmd_locally" in ctx.attrs.labels,+ category = "filter_resources",+ allow_cache_upload = True,+ )++ filtered_resource_infos = []+ for i, resource in enumerate(resources):+ if resource.res == None:+ continue++ filtered_res = res_to_out_res_dir[resource.res]+ filtered_aapt2_compile_output = aapt2_compile(+ ctx,+ filtered_res,+ android_toolchain,+ skip_crunch_pngs = skip_crunch_pngs,+ identifier = "filtered_res_{}".format(i),+ )+ filtered_resource = AndroidResourceInfo(+ raw_target = resource.raw_target,+ aapt2_compile_output = filtered_aapt2_compile_output,+ assets = resource.assets,+ manifest_file = resource.manifest_file,+ r_dot_java_package = resource.r_dot_java_package,+ res = filtered_res,+ text_symbols = resource.text_symbols,+ unused_resource_dep_validation_has_non_xml_resources = resource.unused_resource_dep_validation_has_non_xml_resources,+ )+ filtered_resource_infos.append(filtered_resource)++ return _FilteredResourcesOutput(+ resource_infos = res_infos_with_no_res + filtered_resource_infos,+ voltron_res = voltron_res_to_out_res_dir.values(),+ override_symbols = override_symbols_artifact,+ string_files_list = all_strings_files_list,+ string_files_res_dirs = all_strings_files_res_dirs,+ )++ResourcesFilter = record(+ densities = list[str],+)++def _get_resources_filter(resources_filter_strings: list[str]) -> [ResourcesFilter, None]:+ if not resources_filter_strings:+ return None++ return ResourcesFilter(densities = resources_filter_strings)++def _maybe_generate_string_source_map(+ actions: AnalysisActions,+ should_build_source_string_map: bool,+ res_dirs: list[Artifact],+ android_toolchain: AndroidToolchainInfo,+ is_voltron_string_source_map: bool = False,+) -> Artifact | None:+ if not should_build_source_string_map or len(res_dirs) == 0:+ return None++ prefix = "voltron_" if is_voltron_string_source_map else ""+ output = actions.declare_output("{}string_source_map".format(prefix), dir = True, has_content_based_path = False)+ res_dirs_file = actions.write("resource_dirs_for_{}string_source_map".format(prefix), res_dirs, has_content_based_path = False)+ generate_string_source_map_cmd = cmd_args(+ [+ android_toolchain.copy_string_resources[RunInfo],+ "--res-dirs",+ res_dirs_file,+ "--output",+ output.as_output(),+ ],+ hidden = res_dirs,+ )++ if is_voltron_string_source_map:+ generate_string_source_map_cmd.add("--is-voltron")++ actions.run(generate_string_source_map_cmd, category = "generate_{}string_source_map".format(prefix), allow_cache_upload = True)++ return output++def _maybe_package_strings_as_assets(+ ctx: AnalysisContext,+ string_files_list: Artifact | None,+ string_files_res_dirs: list[Artifact],+ r_dot_txt: Artifact,+ android_toolchain: AndroidToolchainInfo,+) -> Artifact | None:+ resource_compression_mode = getattr(ctx.attrs, "resource_compression", "disabled")+ is_store_strings_as_assets = _is_store_strings_as_assets(resource_compression_mode)+ expect(is_store_strings_as_assets == (string_files_list != None))++ if not is_store_strings_as_assets:+ return None++ string_assets_dir = ctx.actions.declare_output("package_strings_as_assets/string_assets", dir = True, has_content_based_path = False)+ string_assets_zip = ctx.actions.declare_output("package_strings_as_assets/string_assets_zip.zip", has_content_based_path = False)+ all_locales_string_assets_zip = ctx.actions.declare_output("package_strings_as_assets/all_locales_string_assets_zip.zip", has_content_based_path = False)++ locales = getattr(ctx.attrs, "locales", [])++ package_strings_as_assets_cmd = cmd_args(+ [+ android_toolchain.package_strings_as_assets[RunInfo],+ "--string-files-list",+ string_files_list,+ "--r-dot-txt",+ r_dot_txt,+ "--string-assets-dir",+ string_assets_dir.as_output(),+ "--string-assets-zip",+ string_assets_zip.as_output(),+ "--all-locales-string-assets-zip",+ all_locales_string_assets_zip.as_output(),+ ],+ hidden = string_files_res_dirs,+ )++ if locales:+ package_strings_as_assets_cmd.add("--locales", ",".join(locales))++ ctx.actions.run(package_strings_as_assets_cmd, category = "package_strings_as_assets", allow_cache_upload = True)++ return string_assets_zip++def get_manifest(+ ctx: AnalysisContext, manifests: [ManifestTSet, list[Artifact], None], manifest_entries: dict, should_replace_application_id_placeholders: bool+) -> Artifact:+ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]+ if ctx.attrs.manifest:+ expect(getattr(ctx.attrs, "manifest_skeleton", None) == None, "Only one of manifest and manifest_skeleton should be declared")+ if isinstance(ctx.attrs.manifest, Dependency):+ android_manifest = ctx.attrs.manifest[DefaultInfo].default_outputs[0]+ else:+ android_manifest = ctx.attrs.manifest+ else:+ expect(ctx.attrs.manifest_skeleton != None, "Must declare one of manifest and manifest_skeleton")+ if isinstance(ctx.attrs.manifest_skeleton, Dependency):+ manifest_skeleton = ctx.attrs.manifest_skeleton[DefaultInfo].default_outputs[0]+ else:+ manifest_skeleton = ctx.attrs.manifest_skeleton++ android_manifest, _ = generate_android_manifest(+ ctx,+ android_toolchain.generate_manifest[RunInfo],+ manifest_skeleton,+ ROOT_MODULE,+ manifests,+ manifest_entries.get("placeholders", {}),+ )++ if should_replace_application_id_placeholders:+ android_manifest_with_replaced_application_id = ctx.actions.declare_output("replaced/AndroidManifest.xml", has_content_based_path = False)+ replace_application_id_placeholders_cmd = cmd_args([+ ctx.attrs._android_toolchain[AndroidToolchainInfo].replace_application_id_placeholders[RunInfo],+ "--manifest",+ android_manifest,+ "--output",+ android_manifest_with_replaced_application_id.as_output(),+ "--sanity-check-placeholders",+ ])++ ctx.actions.run(replace_application_id_placeholders_cmd, category = "replace_application_id_placeholders", allow_cache_upload = True)+ return android_manifest_with_replaced_application_id+ else:+ return android_manifest++def _get_module_manifests(+ ctx: AnalysisContext, manifest_entries: dict, apk_module_graph_file: Artifact | None, use_proto_format: bool, primary_resources_apk: Artifact+) -> list[Artifact]:+ if not apk_module_graph_file:+ return []++ default_module_manifest_skeleton = getattr(ctx.attrs, "default_module_manifest_skeleton", None)+ if use_proto_format:+ if not ctx.attrs.module_manifests:+ fail("module_manifests required for a voltron enabled AAB build")+ elif default_module_manifest_skeleton:+ fail("default_module_manifest_skeleton cannot be provided for a voltron enabled AAB build")+ elif not default_module_manifest_skeleton:+ return []++ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]++ module_manifests_dir = ctx.actions.declare_output("module_manifests_dir", dir = True, has_content_based_path = False)++ def get_manifests_modular(ctx: AnalysisContext, artifacts, outputs):+ apk_module_graph_info = get_apk_module_graph_info(ctx, apk_module_graph_file, artifacts)++ merged_module_manifests = {}+ for module_name in apk_module_graph_info.module_list:+ if is_root_module(module_name):+ continue+ if use_proto_format:+ module_manifest = ctx.attrs.module_manifests[DefaultInfo].default_outputs[0]+ if not module_manifest:+ fail("Module {} does not have a manifest".format(module_name))+ module_manifest = module_manifest.project(module_name + "/AndroidManifest.xml")+ else:+ module_manifest = default_module_manifest_skeleton++ merged_module_manifest, _ = generate_android_manifest(+ ctx,+ android_toolchain.generate_manifest[RunInfo],+ module_manifest,+ module_name,+ # Note - the expectation of voltron modules is that the AndroidManifest entries are merged into the base APK's manifest.+ None,+ manifest_entries.get("placeholders", {}),+ )++ if use_proto_format:+ merged_module_manifest = get_module_manifest_in_proto_format(+ ctx,+ android_toolchain,+ merged_module_manifest,+ primary_resources_apk,+ module_name,+ )++ merged_module_manifests["assets/{}/AndroidManifest.xml".format(module_name)] = merged_module_manifest++ ctx.actions.symlinked_dir(outputs[module_manifests_dir], merged_module_manifests)++ ctx.actions.dynamic_output(+ dynamic = [apk_module_graph_file],+ inputs = [],+ outputs = [module_manifests_dir.as_output()],+ f = get_manifests_modular,+ )++ return [module_manifests_dir]++# Returns the "primary resources APK" (i.e. the resource that are packaged into the primary APK),+# and optionally an "exopackaged assets APK" and the hash for that APK.+def _merge_assets(+ ctx: AnalysisContext,+ is_exopackaged_enabled_for_resources: bool,+ base_apk: Artifact,+ resource_infos: list[AndroidResourceInfo],+ cxx_resources: Artifact | None,+ is_bundle_build: bool,+ apk_module_graph_file: Artifact | None,+) -> (Artifact, Artifact | None, Artifact | None, Artifact | None):+ expect(+ not (is_exopackaged_enabled_for_resources and is_bundle_build),+ "Cannot use exopackage-for-resources with AAB builds.",+ )+ expect(+ not (is_exopackaged_enabled_for_resources and apk_module_graph_file),+ "Cannot use exopackage-for-resources with Voltron builds.",+ )+ asset_resource_infos = [resource_info for resource_info in resource_infos if resource_info.assets]+ if not asset_resource_infos and not cxx_resources:+ return base_apk, None, None, None++ merged_assets_output = ctx.actions.declare_output("merged_assets.ap_", has_content_based_path = False)++ def get_common_merge_assets_cmd(ctx: AnalysisContext, output_apk: Artifact) -> (cmd_args, Artifact | None):+ merge_assets_cmd = cmd_args(ctx.attrs._android_toolchain[AndroidToolchainInfo].merge_assets[RunInfo])+ merge_assets_cmd.add(["--output-apk", output_apk.as_output()])++ if getattr(ctx.attrs, "extra_no_compress_asset_extensions", None):+ merge_assets_cmd.add("--extra-no-compress-asset-extensions")+ merge_assets_cmd.add(ctx.attrs.extra_no_compress_asset_extensions)++ if getattr(ctx.attrs, "extra_no_compress_asset_regex", None):+ merge_assets_cmd.add("--extra_no_compress_asset_regex")+ merge_assets_cmd.add(ctx.attrs.extra_no_compress_asset_regex)++ if is_exopackaged_enabled_for_resources:+ merged_assets_output_hash = ctx.actions.declare_output("merged_assets.ap_.hash", has_content_based_path = False)+ merge_assets_cmd.add(["--output-apk-hash", merged_assets_output_hash.as_output()])+ else:+ merge_assets_cmd.add(["--base-apk", base_apk])+ merged_assets_output_hash = None++ merge_assets_cmd.add("--binary-type", "aab" if is_bundle_build else "apk")++ return merge_assets_cmd, merged_assets_output_hash++ if apk_module_graph_file:+ declared_outputs = [merged_assets_output]+ if is_bundle_build:+ # For Voltron AAB builds, we need to put assets into a separate "APK" for each module.+ module_assets_apks_dir = ctx.actions.declare_output("module_assets_apks", has_content_based_path = False)+ declared_outputs.append(module_assets_apks_dir)+ else:+ module_assets_apks_dir = None++ def merge_assets_modular(ctx: AnalysisContext, artifacts, outputs):+ apk_module_graph_info = get_apk_module_graph_info(ctx, apk_module_graph_file, artifacts)++ module_to_assets_dirs = {}+ if cxx_resources != None:+ module_to_assets_dirs.setdefault(ROOT_MODULE, []).extend([cxx_resources])+ for asset_resource_info in asset_resource_infos:+ module_name = apk_module_graph_info.target_to_module_mapping_function(str(asset_resource_info.raw_target))+ module_to_assets_dirs.setdefault(module_name, []).extend(asset_resource_info.assets)++ merge_assets_cmd, _ = get_common_merge_assets_cmd(ctx, outputs[merged_assets_output])++ if is_bundle_build:+ merge_assets_cmd.add(["--module-assets-apks-dir", outputs[module_assets_apks_dir].as_output()])++ assets_dirs_file = ctx.actions.write_json("assets_dirs.json", module_to_assets_dirs, has_content_based_path = False)+ merge_assets_cmd.add(["--assets-dirs", assets_dirs_file])+ merge_assets_cmd.add(cmd_args(hidden = flatten(module_to_assets_dirs.values())))++ ctx.actions.run(merge_assets_cmd, category = "merge_assets", allow_cache_upload = True)++ ctx.actions.dynamic_output(+ dynamic = [apk_module_graph_file],+ inputs = [],+ outputs = [o.as_output() for o in declared_outputs],+ f = merge_assets_modular,+ )++ return merged_assets_output, None, None, module_assets_apks_dir++ else:+ merge_assets_cmd, merged_assets_output_hash = get_common_merge_assets_cmd(ctx, merged_assets_output)++ assets_dirs = flatten([resource_info.assets for resource_info in asset_resource_infos])+ if cxx_resources:+ assets_dirs.extend([cxx_resources])+ assets_dirs_file = ctx.actions.write_json("assets_dirs.json", {ROOT_MODULE: assets_dirs}, has_content_based_path = False)+ merge_assets_cmd.add(["--assets-dirs", assets_dirs_file])+ merge_assets_cmd.add(cmd_args(hidden = assets_dirs))++ ctx.actions.run(merge_assets_cmd, category = "merge_assets", allow_cache_upload = True)++ if is_exopackaged_enabled_for_resources:+ return base_apk, merged_assets_output, merged_assets_output_hash, None+ else:+ return merged_assets_output, None, None, None++def get_effective_banned_duplicate_resource_types(+ duplicate_resource_behavior: str, allowed_duplicate_resource_types: list[str], banned_duplicate_resource_types: list[str]+) -> list[str]:+ if duplicate_resource_behavior == "allow_by_default":+ expect(+ len(allowed_duplicate_resource_types) == 0,+ "Cannot set allowed_duplicate_resource_types if duplicate_resource_behaviour is allow_by_default",+ )+ return banned_duplicate_resource_types+ elif duplicate_resource_behavior == "ban_by_default":+ expect(+ len(banned_duplicate_resource_types) == 0,+ "Cannot set banned_duplicate_resource_types if duplicate_resource_behaviour is ban_by_default",+ )+ return [rtype for rtype in RType if rtype not in allowed_duplicate_resource_types]+ else:+ fail("Unrecognized duplicate_resource_behavior: {}".format(duplicate_resource_behavior))++def get_cxx_resources(ctx: AnalysisContext, deps: list[Dependency], dir_name: str = "cxx_resources_dir") -> Artifact | None:+ cxx_resources = gather_resources(+ label = ctx.label,+ resources = {},+ deps = deps,+ )++ symlink_tree_dict = {}+ resource_maps = cxx_resources.values()+ for resource_map in resource_maps:+ for name, resource in resource_map.items():+ symlink_tree_dict["cxx-resources/{}".format(name)] = resource.default_output++ return ctx.actions.symlinked_dir(dir_name, symlink_tree_dict, has_content_based_path = False) if symlink_tree_dict else None++def _is_store_strings_as_assets(resource_compression: str) -> bool:+ return resource_compression == "enabled_strings_only" or resource_compression == "enabled_with_strings_as_assets"
@@ -0,0 +1,128 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//java:java_library.bzl", "compile_to_jar")+load(+ "@prelude//java:java_providers.bzl",+ "JavaCompileOutputs", # @unused Used as a type+ "JavaLibraryInfo",+ "JavaPackagingDepTSet",+ "JavaPackagingInfo",+ "create_java_packaging_dep",+ "single_library_compiling_deps",+)+load(":android_providers.bzl", "AndroidBuildConfigInfo", "BuildConfigField", "merge_android_packageable_info")++def android_build_config_impl(ctx: AnalysisContext) -> list[Provider]:+ providers = []++ default_build_config_fields = get_build_config_fields(ctx.attrs.values)+ android_build_config_info = AndroidBuildConfigInfo(+ package = ctx.attrs.package, build_config_fields = default_build_config_fields, values_file = ctx.attrs.values_file+ )+ providers.append(android_build_config_info)+ providers.append(merge_android_packageable_info(ctx.label, ctx.actions, deps = [], build_config_info = android_build_config_info))++ build_config_dot_java_library, java_packaging_info, build_config_dot_java = generate_android_build_config(+ ctx,+ ctx.attrs.name,+ ctx.attrs.package,+ False,+ default_build_config_fields,+ ctx.attrs.values_file,+ )++ providers.append(java_packaging_info)+ providers.append(build_config_dot_java_library)++ providers.append(+ DefaultInfo(+ default_output = build_config_dot_java_library.library_output.full_library,+ sub_targets = {+ "build_config_dot_java": [DefaultInfo(default_output = build_config_dot_java)],+ },+ ),+ )+ return providers++def generate_android_build_config(+ ctx: AnalysisContext, source: str, java_package: str, use_constant_expressions: bool, default_values: list[BuildConfigField], values_file: Artifact | None+) -> (JavaLibraryInfo, JavaPackagingInfo, Artifact):+ build_config_dot_java = _generate_build_config_dot_java(ctx, source, java_package, use_constant_expressions, default_values, values_file)++ compiled_build_config_dot_java = _compile_and_package_build_config_dot_java(ctx, java_package, build_config_dot_java)+ library_output = compiled_build_config_dot_java.classpath_entry++ packaging_deps_kwargs = {"value": create_java_packaging_dep(ctx, library_output.full_library)}+ packaging_deps = ctx.actions.tset(JavaPackagingDepTSet, **packaging_deps_kwargs)+ return (+ JavaLibraryInfo(+ compiling_deps = single_library_compiling_deps(ctx.actions, library_output),+ library_output = library_output,+ output_for_classpath_macro = library_output.full_library,+ ),+ JavaPackagingInfo(+ packaging_deps = packaging_deps,+ ),+ build_config_dot_java,+ )++def _generate_build_config_dot_java(+ ctx: AnalysisContext, source: str, java_package: str, use_constant_expressions: bool, default_values: list[BuildConfigField], values_file: Artifact | None+) -> Artifact:+ generate_build_config_cmd = cmd_args(ctx.attrs._android_toolchain[AndroidToolchainInfo].generate_build_config[RunInfo])+ generate_build_config_cmd.add([+ "--source",+ source,+ "--java-package",+ java_package,+ "--use-constant-expressions",+ str(use_constant_expressions),+ ])++ default_values_file = ctx.actions.write(+ _get_output_name(java_package, "default_values"),+ ["{} {} = {}".format(x.type, x.name, x.value) for x in default_values],+ has_content_based_path = True,+ )+ generate_build_config_cmd.add(["--default-values-file", default_values_file])+ if values_file:+ generate_build_config_cmd.add(["--values-file", values_file])++ build_config_dot_java = ctx.actions.declare_output(+ _get_output_name(java_package, "BuildConfig.java"),+ has_content_based_path = True,+ )+ generate_build_config_cmd.add(["--output", build_config_dot_java.as_output()])++ ctx.actions.run(+ generate_build_config_cmd,+ category = "android_generate_build_config",+ identifier = java_package,+ )++ return build_config_dot_java++def _compile_and_package_build_config_dot_java(ctx: AnalysisContext, java_package: str, build_config_dot_java: Artifact) -> JavaCompileOutputs:+ return compile_to_jar(+ ctx,+ actions_identifier = "build_config_{}".format(java_package.replace(".", "_")),+ srcs = [build_config_dot_java],+ )++def get_build_config_fields(lines: list[str]) -> list[BuildConfigField]:+ return [_get_build_config_field(line) for line in lines]++def _get_build_config_field(line: str) -> BuildConfigField:+ type_and_name, value = [x.strip() for x in line.split("=", 1)]+ field_type, name = type_and_name.split()+ return BuildConfigField(type = field_type, name = name, value = value)++def _get_output_name(java_package: str, output_filename: str) -> str:+ return "android_build_config/{}/{}".format(java_package.replace(".", "_"), output_filename)
@@ -0,0 +1,190 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")+load("@prelude//android:android_apk.bzl", "get_install_info")+load("@prelude//android:android_binary.bzl", "get_binary_info")+load(+ "@prelude//android:android_providers.bzl",+ "AndroidAabInfo",+ "AndroidBinaryNativeLibsInfo",+ "AndroidBinaryPrimaryPlatformInfo",+ "AndroidBinaryResourcesInfo",+ "AndroidDerivedApkInfo",+ "DexFilesInfo",+ "KeystoreInfo",+)+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//android:bundletool_util.bzl", "derive_universal_apk")+load("@prelude//android:util.bzl", "package_validators_decorator")+load("@prelude//java/utils:java_more_utils.bzl", "get_path_separator_for_exec_os")+load("@prelude//target_stats:target_stats.bzl", "target_stats_aggregate_providers_and_subtargets")+load("@prelude//utils:argfile.bzl", "argfile")++def android_bundle_impl(ctx: AnalysisContext) -> list[Provider]:+ android_binary_info = get_binary_info(ctx, use_proto_format = True)+ native_library_info = android_binary_info.native_library_info++ wrapped_build_bundle = package_validators_decorator(+ ctx,+ build_bundle,+ extension = ".aab",+ )++ output_bundle = wrapped_build_bundle(+ output_filename = ctx.label.name,+ actions = ctx.actions,+ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo],+ dex_files_info = android_binary_info.dex_files_info,+ native_library_info = native_library_info,+ resources_info = android_binary_info.resources_info,+ bundle_config = ctx.attrs.bundle_config_file,+ validation_deps_outputs = get_validation_deps_outputs(ctx),+ packaging_options = ctx.attrs.packaging_options,+ )++ extra_providers = []+ if android_binary_info.preprocessed_java_classes_info:+ extra_providers.append(android_binary_info.preprocessed_java_classes_info)+ sub_targets = {}+ sub_targets.update(android_binary_info.sub_targets)+ if ctx.attrs.use_derived_apk:+ keystore = ctx.attrs.keystore[KeystoreInfo]+ default_output = derive_universal_apk(+ ctx,+ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo],+ app_bundle = output_bundle,+ keystore = keystore,+ )+ extra_providers.append(AndroidDerivedApkInfo(apk = default_output))+ extra_providers.append(+ get_install_info(+ ctx,+ exopackage_info = None,+ manifest = android_binary_info.resources_info.manifest,+ output_apk = default_output,+ ),+ )+ sub_targets["aab"] = [+ DefaultInfo(+ default_outputs = [output_bundle],+ )+ ]+ else:+ default_output = output_bundle++ target_stats_providers, target_stats_subtargets = target_stats_aggregate_providers_and_subtargets(+ ctx,+ deps = android_binary_info.deps_by_platform[android_binary_info.primary_platform],+ )+ sub_targets.update(target_stats_subtargets)++ java_packaging_deps = android_binary_info.java_packaging_deps+ return (+ [+ DefaultInfo(default_output = default_output, other_outputs = android_binary_info.materialized_artifacts, sub_targets = sub_targets),+ AndroidAabInfo(+ aab = output_bundle,+ manifest = android_binary_info.resources_info.manifest,+ materialized_artifacts = android_binary_info.materialized_artifacts,+ unstripped_shared_libraries = native_library_info.unstripped_shared_libraries,+ ),+ AndroidBinaryPrimaryPlatformInfo(+ primary_platform = android_binary_info.primary_platform,+ ),+ TemplatePlaceholderInfo(+ keyed_variables = {+ "classpath": cmd_args([dep.jar for dep in java_packaging_deps if dep.jar], delimiter = get_path_separator_for_exec_os(ctx)),+ "classpath_including_targets_with_no_output": cmd_args(+ [dep.output_for_classpath_macro for dep in java_packaging_deps], delimiter = get_path_separator_for_exec_os(ctx)+ ),+ },+ ),+ ]+ + extra_providers+ + target_stats_providers+ )++def build_bundle(+ output_filename: str,+ actions: AnalysisActions,+ android_toolchain: AndroidToolchainInfo,+ dex_files_info: DexFilesInfo,+ native_library_info: AndroidBinaryNativeLibsInfo,+ resources_info: AndroidBinaryResourcesInfo,+ bundle_config: Artifact | None,+ validation_deps_outputs: [list[Artifact], None] = None,+ packaging_options: dict | None = None,+) -> Artifact:+ output_bundle = actions.declare_output("{}.aab".format(output_filename), has_content_based_path = False)++ bundle_builder_args = cmd_args(+ android_toolchain.bundle_builder[RunInfo],+ "--output-bundle",+ output_bundle.as_output(),+ "--resource-apk",+ resources_info.primary_resources_apk,+ "--dex-file",+ dex_files_info.primary_dex,+ # The outputs of validation_deps need to be added as hidden arguments+ # to an action for the validation_deps targets to be built and enforced.+ hidden = validation_deps_outputs or [],+ )++ if bundle_config:+ bundle_builder_args.add(["--path-to-bundle-config-file", bundle_config])++ if android_toolchain.package_meta_inf_version_files:+ bundle_builder_args.add("--package-meta-inf-version-files")++ root_module_asset_directories = (+ native_library_info.root_module_native_lib_assets + dex_files_info.root_module_bootstrap_dex_dirs + dex_files_info.root_module_secondary_dex_dirs+ )+ root_module_asset_directories_file = argfile(actions = actions, name = "root_module_asset_directories.txt", args = root_module_asset_directories)++ non_root_module_asset_directories = resources_info.module_manifests + dex_files_info.non_root_module_secondary_dex_dirs+ non_root_module_asset_directories_file = argfile(actions = actions, name = "non_root_module_asset_directories.txt", args = non_root_module_asset_directories)+ non_root_module_asset_native_lib_directories = argfile(+ actions = actions, name = "non_root_module_asset_native_lib_directories.txt", args = native_library_info.non_root_module_native_lib_assets+ )++ native_library_directories = argfile(actions = actions, name = "native_library_directories", args = native_library_info.native_libs_for_primary_apk)+ all_zip_files = [resources_info.packaged_string_assets] if resources_info.packaged_string_assets else []+ zip_files = argfile(actions = actions, name = "zip_files", args = all_zip_files)+ jar_files_that_may_contain_resources = argfile(+ actions = actions, name = "jar_files_that_may_contain_resources", args = resources_info.jar_files_that_may_contain_resources+ )++ if resources_info.module_assets:+ bundle_builder_args.add(["--module-assets-dir", resources_info.module_assets])++ bundle_builder_args.add([+ "--root-module-asset-directories-list",+ root_module_asset_directories_file,+ "--non-root-module-asset-directories-list",+ non_root_module_asset_directories_file,+ "--non-root-module-asset-native-lib-directories-list",+ non_root_module_asset_native_lib_directories,+ "--native-libraries-directories-list",+ native_library_directories,+ "--zip-files-list",+ zip_files,+ "--jar-files-that-may-contain-resources-list",+ jar_files_that_may_contain_resources,+ ])++ if packaging_options:+ for key, value in packaging_options.items():+ if key != "excluded_resources":+ fail("Only 'excluded_resources' is supported in packaging_options right now!")+ else:+ bundle_builder_args.add("--excluded-resources", actions.write("excluded_resources.txt", value, has_content_based_path = False))++ actions.run(bundle_builder_args, category = "bundle_build")++ return output_bundle
@@ -0,0 +1,30 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""A rule that applies the android_binary CPU transition to a dependency.++This is useful for targets that need to be configured with the same CPU+platform as an android_binary's deps, but are referenced from genrules+that run in the binary's parent (arch-agnostic) configuration.+"""++load("@prelude//android:configuration.bzl", "CPU_TRANSITION_ATTRS", "cpu_transition")+load("@prelude//decls:core_rules.bzl", "TargetCpuType")++def _android_cpu_transitioned_dep_impl(ctx: AnalysisContext) -> list[Provider]:+ return ctx.attrs.dep.providers++android_cpu_transitioned_dep = rule(+ impl = _android_cpu_transitioned_dep_impl,+ attrs = {+ "cpu_filters": attrs.list(attrs.enum(TargetCpuType), default = []),+ "dep": attrs.transition_dep(cfg = cpu_transition),+ "min_sdk_version": attrs.option(attrs.int(), default = None),+ }+ | CPU_TRANSITION_ATTRS,+)
@@ -0,0 +1,193 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//android:android_apk.bzl", "build_apk")+load("@prelude//android:android_binary_native_library_rules.bzl", "get_android_binary_native_library_info")+load("@prelude//android:android_binary_resources_rules.bzl", "get_android_binary_resources_info")+load("@prelude//android:android_providers.bzl", "AndroidApkInfo", "AndroidApkUnderTestInfo", "AndroidInstrumentationApkInfo", "merge_android_packageable_info")+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//android:configuration.bzl", "get_deps_by_platform")+load("@prelude//android:dex_rules.bzl", "get_multi_dex", "get_single_primary_dex", "get_split_dex_merge_config", "merge_to_single_dex", "merge_to_split_dex")+load("@prelude//android:preprocess_java_classes.bzl", "get_preprocessed_java_classes")+load("@prelude//android:util.bzl", "create_enhancement_context")+load("@prelude//java:class_to_srcs.bzl", "merge_class_to_source_map_from_jar")+load("@prelude//java:java_providers.bzl", "create_java_packaging_dep", "get_all_java_packaging_deps")+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")+load("@prelude//java/utils:java_utils.bzl", "get_class_to_source_map_info")+load("@prelude//target_stats:target_stats.bzl", "target_stats_aggregate_providers_and_subtargets")+load("@prelude//utils:expect.bzl", "expect")+load("@prelude//utils:utils.bzl", "flatten")++def android_instrumentation_apk_impl(ctx: AnalysisContext):+ # jar preprocessing cannot be used when the jars were dexed already, so we have to disable predex when we want to preprocess the jars.+ disable_pre_dex = ctx.attrs.disable_pre_dex or ctx.attrs.preprocess_java_classes_bash++ apk_under_test_info = ctx.attrs.apk[AndroidApkUnderTestInfo]++ expect(+ ctx.attrs.min_sdk_version == apk_under_test_info.min_sdk_version,+ """+Android instrumentation APK must have the same min_sdk_version as the APK-under-test!+This is important because the min_sdk_version affects the configuration of all deps.+Instrumentation APK min_sdk_version: {}, APK-under-test min_sdk_version: {}""".format(+ ctx.attrs.min_sdk_version,+ apk_under_test_info.min_sdk_version,+ ),+ )++ # android_instrumentation_apk uses the same platforms as the APK-under-test+ unfiltered_deps_by_platform = get_deps_by_platform(ctx)+ for platform in apk_under_test_info.platforms:+ expect(+ platform in unfiltered_deps_by_platform,+ "Android instrumentation APK must have any platforms that are in the APK-under-test!",+ )++ test_apk_platform_configurations = set([str(x.label.configured_target().config()) for x in flatten(unfiltered_deps_by_platform.values())])+ for platform_configuration in apk_under_test_info.platform_configurations:+ expect(+ platform_configuration in test_apk_platform_configurations,+ """+APK-under-test has deps that are configured in a different manner than the Android instrumentation APK!+This will lead to overbuilding and is not supported. Configuration {} not found in {}""".format(platform_configuration, test_apk_platform_configurations),+ )+ filtered_deps_by_platform = {platform: deps for platform, deps in unfiltered_deps_by_platform.items() if platform in apk_under_test_info.platforms}++ # We use the deps that don't have _build_only_native_code = True+ deps = unfiltered_deps_by_platform.values()[0]++ is_self_instrumenting = ctx.attrs.is_self_instrumenting++ all_java_packaging_deps = [packaging_dep for packaging_dep in get_all_java_packaging_deps(ctx, deps) if packaging_dep.dex]+ java_packaging_deps = [+ packaging_dep+ for packaging_dep in all_java_packaging_deps+ if is_self_instrumenting or packaging_dep.label.raw_target() not in apk_under_test_info.java_packaging_deps+ ]+ desugar_classpath_jars = [+ packaging_dep.jar+ for packaging_dep in all_java_packaging_deps+ if not is_self_instrumenting and packaging_dep.label.raw_target() in apk_under_test_info.java_packaging_deps+ ]++ android_packageable_info = merge_android_packageable_info(ctx.label, ctx.actions, deps)++ resources_info = get_android_binary_resources_info(+ ctx,+ deps,+ android_packageable_info,+ java_packaging_deps = java_packaging_deps,+ use_proto_format = False,+ referenced_resources_lists = [],+ manifest_entries = apk_under_test_info.manifest_entries,+ resource_infos_to_exclude = apk_under_test_info.resource_infos if not is_self_instrumenting else set(),+ r_dot_java_packages_to_exclude = apk_under_test_info.r_dot_java_packages if not is_self_instrumenting else set(),+ )+ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]+ java_packaging_deps += [+ create_java_packaging_dep(+ ctx,+ r_dot_java.library_info.library_output.full_library,+ dex_weight_factor = android_toolchain.r_dot_java_weight_factor,+ )+ for r_dot_java in resources_info.r_dot_java_infos+ ]++ enhance_ctx = create_enhancement_context(ctx)+ sub_targets = enhance_ctx.get_sub_targets()+ materialized_artifacts = []+ preprocessed_java_classes_info = None+ if not disable_pre_dex:+ pre_dexed_libs = [java_packaging_dep.dex for java_packaging_dep in java_packaging_deps]+ if ctx.attrs.use_split_dex:+ dex_merge_config = get_split_dex_merge_config(ctx, android_toolchain)+ dex_files_info = merge_to_split_dex(+ ctx,+ android_toolchain,+ pre_dexed_libs,+ dex_merge_config,+ enable_bootstrap_dexes = ctx.attrs.enable_bootstrap_dexes,+ )+ else:+ dex_files_info = merge_to_single_dex(ctx, android_toolchain, pre_dexed_libs)+ else:+ jars_to_owners = {packaging_dep.jar: packaging_dep.jar.owner.raw_target() for packaging_dep in java_packaging_deps}+ if ctx.attrs.preprocess_java_classes_bash:+ jars_to_owners, preprocessed_java_classes_info = get_preprocessed_java_classes(enhance_ctx, jars_to_owners)+ if preprocessed_java_classes_info:+ materialized_artifacts.append(preprocessed_java_classes_info.materialized_artifacts_dir)+ if ctx.attrs.use_split_dex:+ dex_files_info = get_multi_dex(+ ctx,+ ctx.attrs._android_toolchain[AndroidToolchainInfo],+ jars_to_owners,+ ctx.attrs.primary_dex_patterns,+ enable_bootstrap_dexes = ctx.attrs.enable_bootstrap_dexes,+ multidex_min_api = ctx.attrs.multidex_min_api,+ classpath_jars = desugar_classpath_jars,+ )+ else:+ dex_files_info = get_single_primary_dex(+ ctx,+ ctx.attrs._android_toolchain[AndroidToolchainInfo],+ jars_to_owners.keys(),+ classpath_jars = desugar_classpath_jars,+ )+ native_library_info = get_android_binary_native_library_info(+ enhance_ctx,+ android_packageable_info,+ filtered_deps_by_platform,+ prebuilt_native_library_dirs_to_exclude = apk_under_test_info.prebuilt_native_library_dirs if not is_self_instrumenting else set(),+ shared_libraries_to_exclude = apk_under_test_info.shared_libraries if not is_self_instrumenting else set(),+ native_library_merge_glue = apk_under_test_info.native_library_merge_glue,+ native_library_merge_code_generator = apk_under_test_info.native_library_merge_code_generator,+ native_library_merge_linker_args_all = apk_under_test_info.native_library_merge_linker_args_all,+ native_library_merge_linker_args = apk_under_test_info.native_library_merge_linker_args,+ native_library_merge_map = apk_under_test_info.native_library_merge_map,+ native_library_merge_non_asset_libs = apk_under_test_info.native_library_merge_non_asset_libs,+ native_library_merge_sequence = apk_under_test_info.native_library_merge_sequence,+ native_library_merge_sequence_blocklist = apk_under_test_info.native_library_merge_sequence_blocklist,+ )++ output_apk = build_apk(+ output_filename = ctx.label.name,+ actions = ctx.actions,+ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo],+ keystore = apk_under_test_info.keystore,+ dex_files_info = dex_files_info,+ native_library_info = native_library_info,+ resources_info = resources_info,+ )++ class_to_srcs, _, class_to_srcs_subtargets = get_class_to_source_map_info(+ ctx,+ outputs = None,+ deps = deps,+ )+ transitive_class_to_src_map = merge_class_to_source_map_from_jar(+ actions = ctx.actions,+ name = ctx.label.name + ".transitive_class_to_src.json",+ java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo],+ relative_to = None,+ deps = [class_to_srcs],+ )+ sub_targets["transitive_class_to_src_map"] = [DefaultInfo(default_output = transitive_class_to_src_map)]++ target_stats_providers, target_stats_subtargets = target_stats_aggregate_providers_and_subtargets(ctx, deps = deps)+ sub_targets.update(target_stats_subtargets)++ return (+ [+ AndroidApkInfo(apk = output_apk, materialized_artifacts = materialized_artifacts, manifest = resources_info.manifest),+ AndroidInstrumentationApkInfo(apk_under_test = ctx.attrs.apk[AndroidApkInfo].apk, is_self_instrumenting = is_self_instrumenting),+ DefaultInfo(default_output = output_apk, other_outputs = materialized_artifacts, sub_targets = sub_targets | class_to_srcs_subtargets),+ class_to_srcs,+ ]+ + ([preprocessed_java_classes_info] if preprocessed_java_classes_info else [])+ + target_stats_providers+ )
@@ -0,0 +1,360 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//android:android_providers.bzl", "AndroidApkExopackageInfo", "AndroidApkInfo", "AndroidInstrumentationApkInfo")+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//java:class_to_srcs.bzl", "JavaClassToSourceMapInfo")+load("@prelude//java:java_providers.bzl", "JavaPackagingInfo", "get_all_java_packaging_deps_tset")+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")+load("@prelude//java/utils:java_more_utils.bzl", "get_path_separator_for_exec_os")+load(+ "@prelude//linking:shared_libraries.bzl",+ "SharedLibraryInfo",+ "create_shlib_symlink_tree",+ "merge_shared_libraries",+ "traverse_shared_library_info",+)+load("@prelude//target_stats:target_stats.bzl", "CycleMode", "target_stats_providers_and_subtargets")+load("@prelude//target_stats:target_stats_config.bzl", "TARGET_STATS_ENABLED")+load("@prelude//test:inject_test_run_info.bzl", "inject_test_run_info")+load("@prelude//tests:test_listing.bzl", "TestListingInfo")+load("@prelude//utils:argfile.bzl", "at_argfile")+load("@prelude//utils:expect.bzl", "expect")++ANDROID_EMULATOR_ABI_LABEL_PREFIX = "tpx-re-config::"+DEFAULT_ANDROID_SUBPLATFORM = "android-30"+DEFAULT_ANDROID_PLATFORM = "android-emulator"+DEFAULT_ANDROID_INSTRUMENTATION_TESTS_USE_CASE = "instrumentation-tests"+RIOT_USE_CASES = [+ "foundation-diff",+ "horizon-experiences-diff",+ "horizon-os-codemod-diff",+ "horizon-os-diff",+ "horizon-os-human-lease",+ "horizon-os-other",+ "vr-diff",+ "wearables-diff",+ "wearables-human-lease",+ "wearables-other",+]+SUPPORTED_POOLS = ["EUREKA_POOL", "HOLLYWOOD_POOL", "STAGE_DELPHI_POOL", "PANTHER_POOL", "SEACLIFF_POOL"]+SUPPORTED_PLATFORMS = ["riot", "android-emulator", "rl-emulator"]+SUPPORTED_USE_CASES = RIOT_USE_CASES + [DEFAULT_ANDROID_INSTRUMENTATION_TESTS_USE_CASE]++def android_instrumentation_test_impl(ctx: AnalysisContext):+ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]++ cmd = [ctx.attrs._java_test_toolchain[JavaToolchainInfo].java_for_tests]++ classpath = android_toolchain.instrumentation_test_runner_classpath++ classpath_args = cmd_args()+ classpath_args.add("-classpath")+ env = ctx.attrs.env or {}+ extra_classpath = []+ if ctx.attrs.instrumentation_test_listener != None:+ extra_classpath.extend([+ get_all_java_packaging_deps_tset(ctx, java_packaging_infos = [ctx.attrs.instrumentation_test_listener[JavaPackagingInfo]]).project_as_args(+ "full_jar_args", ordering = "bfs"+ ),+ ])++ shared_library_info = merge_shared_libraries(+ ctx.actions,+ deps = [ctx.attrs.instrumentation_test_listener[SharedLibraryInfo]],+ )++ cxx_library_symlink_tree = create_shlib_symlink_tree(+ actions = ctx.actions,+ out = "cxx_library_symlink_tree",+ shared_libs = traverse_shared_library_info(shared_library_info, transformation_provider = None),+ )++ env["BUCK_LD_SYMLINK_TREE"] = cxx_library_symlink_tree+ classpath_args.add(cmd_args(extra_classpath + classpath, delimiter = get_path_separator_for_exec_os(ctx)))+ cmd.append(at_argfile(actions = ctx.actions, name = "classpath_args_file", args = classpath_args))++ cmd.append(android_toolchain.instrumentation_test_runner_main_class)++ apk_info = ctx.attrs.apk.get(AndroidApkInfo)+ expect(apk_info != None, "Provided APK must have AndroidApkInfo!")++ instrumentation_apk_info = ctx.attrs.apk.get(AndroidInstrumentationApkInfo)+ # A self-instrumenting apk already bundles the app-under-test's contents, and its manifest's+ # targetPackage is the self apk itself rather than the un-merged app-under-test apk's package,+ # so there is no separate app-under-test to install.+ if instrumentation_apk_info != None and not instrumentation_apk_info.is_self_instrumenting:+ cmd.extend(["--apk-under-test-path", instrumentation_apk_info.apk_under_test])+ if ctx.attrs.is_self_instrumenting:+ cmd.extend(["--is-self-instrumenting"])+ extra_instrumentation_args = ctx.attrs.extra_instrumentation_args+ if extra_instrumentation_args:+ for arg_name, arg_value in extra_instrumentation_args.items():+ cmd.extend(+ [+ "--extra-instrumentation-argument",+ cmd_args([arg_name, arg_value], delimiter = "="),+ ],+ )++ target_package_file = ctx.actions.declare_output("target_package_file", has_content_based_path = False)+ package_file = ctx.actions.declare_output("package_file", has_content_based_path = False)+ test_runner_file = ctx.actions.declare_output("test_runner_file", has_content_based_path = False)+ manifest_utils_cmd = cmd_args(ctx.attrs._android_toolchain[AndroidToolchainInfo].manifest_utils[RunInfo])+ manifest_utils_cmd.add([+ "--manifest-path",+ apk_info.manifest,+ "--package-output",+ package_file.as_output(),+ "--target-package-output",+ target_package_file.as_output(),+ "--instrumentation-test-runner-output",+ test_runner_file.as_output(),+ ])+ ctx.actions.run(manifest_utils_cmd, category = "get_manifest_info")+ cmd.extend(+ [+ "--test-package-name",+ cmd_args(package_file, format = "@{}"),+ "--target-package-name",+ cmd_args(target_package_file, format = "@{}"),+ "--test-runner",+ cmd_args(test_runner_file, format = "@{}"),+ ],+ )++ if ctx.attrs.instrumentation_test_listener_class != None:+ cmd.extend(["--extra-instrumentation-test-listener", ctx.attrs.instrumentation_test_listener_class])++ if ctx.attrs.clear_package_data:+ cmd.append("--clear-package-data")++ if ctx.attrs.disable_animations:+ cmd.append("--disable-animations")++ if ctx.attrs.collect_tombstones:+ cmd.append("--collect-tombstones")+ if ctx.attrs.record_video:+ cmd.append("--record-video")+ if android_toolchain.collect_perfetto:+ cmd.append("--collect-perfetto")+ if ctx.attrs.log_extractors:+ for arg_name, arg_value in ctx.attrs.log_extractors.items():+ cmd.extend(+ [+ "--log-extractor",+ cmd_args([arg_name, arg_value], delimiter = "="),+ ],+ )++ cmd.extend(+ [+ "--adb-executable-path",+ "required_but_unused",+ "--instrumentation-apk-path",+ apk_info.apk,+ ],+ )++ # Exopackage secondary dexes live out-of-band, not in base.apk. Pass the build's secondary-dex+ # dir so the runner pushes them to /data/local/tmp/exopackage/<pkg>/secondary-dex before+ # Application init; otherwise classes in those dexes (e.g. com.facebook.R$style) hit NoClassDefFoundError on RE.+ apk_exopackage_info = ctx.attrs.apk.get(AndroidApkExopackageInfo)+ if apk_exopackage_info != None:+ cmd.extend([+ "--exopackage-secondary-dex-local-dir",+ apk_exopackage_info.secondary_dex_directory,+ ])++ listing_info = ctx.attrs._android_toolchain[TestListingInfo]++ list_tests = listing_info.list_tests+ if list_tests != None and "tpx:supports_static_listing=true" in ctx.attrs.labels and "tpx:supports_static_listing=false" not in ctx.attrs.labels:+ list_tests_command = cmd_args([+ list_tests[RunInfo],+ "list-tests",+ "--sources-file",+ ctx.actions.write("source_files.txt", ctx.attrs._test_srcs, with_inputs = True, has_content_based_path = False),+ ])+ env["TPX_LIST_TESTS_COMMAND"] = list_tests_command++ labels = ctx.attrs.labels+ if "tpx:supports-test-result-output-spec" not in labels:+ labels.append("tpx:supports-test-result-output-spec")++ test_info = ExternalRunnerTestInfo(+ type = "android_instrumentation",+ command = cmd,+ env = env,+ labels = labels,+ contacts = ctx.attrs.contacts,+ run_from_project_root = True,+ use_project_relative_paths = True,+ executor_overrides = _compute_executor_overrides(ctx, android_toolchain.instrumentation_test_can_run_locally),+ local_resources = {+ "android_emulator": None if ctx.attrs._android_emulators == None else ctx.attrs._android_emulators.label,+ },+ required_local_resources = [RequiredTestLocalResource("android_emulator", listing = True, execution = True)],+ )++ classmap_source_info = [ctx.attrs.apk[JavaClassToSourceMapInfo]] if JavaClassToSourceMapInfo in ctx.attrs.apk else []++ test_info, run_info = inject_test_run_info(ctx, test_info)++ target_stats_providers = []+ target_stats_subtargets = {}+ if TARGET_STATS_ENABLED:+ target_stats_tools = android_toolchain.target_stats_tools+ if target_stats_tools != None:+ target_stats_deps = [ctx.attrs.apk]+ if ctx.attrs.instrumentation_test_listener != None:+ target_stats_deps.append(ctx.attrs.instrumentation_test_listener)+ target_stats_providers, target_stats_subtargets = target_stats_providers_and_subtargets(+ ctx,+ tools = target_stats_tools,+ srcs = {src.short_path: src for src in ctx.attrs._test_srcs},+ deps = target_stats_deps,+ cycle_mode = CycleMode("package"),+ module_name = ctx.label.name,+ )++ # We append additional args so that "buck2 run" will work with sane defaults+ run_info.args.add(cmd_args(["--auto-run-on-connected-device", "--output", ".", "--adb-executable-path", "adb"]))+ return (+ [+ test_info,+ run_info,+ DefaultInfo(sub_targets = target_stats_subtargets),+ ]+ + classmap_source_info+ + target_stats_providers+ )++def _compute_executor_overrides(ctx: AnalysisContext, instrumentation_test_can_run_locally: bool) -> dict[str, CommandExecutorConfig]:+ remote_execution_properties = {+ "platform": _compute_emulator_platform(ctx.attrs.labels or []),+ "subplatform": _compute_emulator_subplatform(ctx.attrs.labels or []),+ }++ re_emulator_abi = _compute_emulator_abi(ctx.attrs.labels or [])+ if re_emulator_abi != None:+ remote_execution_properties["abi"] = re_emulator_abi++ default_executor_override = CommandExecutorConfig(+ local_enabled = instrumentation_test_can_run_locally,+ remote_enabled = True,+ remote_execution_properties = remote_execution_properties,+ remote_execution_use_case = _compute_re_use_case(ctx.attrs.labels or []),+ )+ dynamic_listing_executor_override = default_executor_override+ test_execution_executor_override = default_executor_override++ if ctx.attrs.re_caps and ctx.attrs.re_use_case:+ if "dynamic-listing" in ctx.attrs.re_caps and "dynamic-listing" in ctx.attrs.re_use_case:+ _validate_executor_override_re_config(ctx.attrs.re_caps["dynamic-listing"], ctx.attrs.re_use_case["dynamic-listing"])+ dynamic_listing_executor_override = CommandExecutorConfig(+ local_enabled = instrumentation_test_can_run_locally,+ remote_enabled = True,+ remote_execution_properties = ctx.attrs.re_caps["dynamic-listing"],+ remote_execution_use_case = ctx.attrs.re_use_case["dynamic-listing"],+ meta_internal_extra_params = ctx.attrs.meta_internal_extra_params,+ )+ if "test-execution" in ctx.attrs.re_caps and "test-execution" in ctx.attrs.re_use_case:+ _validate_executor_override_re_config(ctx.attrs.re_caps["test-execution"], ctx.attrs.re_use_case["test-execution"])+ test_execution_executor_override = CommandExecutorConfig(+ local_enabled = instrumentation_test_can_run_locally,+ remote_enabled = True,+ remote_execution_properties = ctx.attrs.re_caps["test-execution"],+ remote_execution_use_case = ctx.attrs.re_use_case["test-execution"],+ meta_internal_extra_params = ctx.attrs.meta_internal_extra_params,+ )++ return {+ "android-emulator": default_executor_override,+ "dynamic-listing": dynamic_listing_executor_override,+ "static-listing": CommandExecutorConfig(+ ## This was set to True as some point and it was causing listing to happen locally,+ ## which is one of the contributing factors to S504068.+ local_enabled = instrumentation_test_can_run_locally,+ remote_enabled = True,+ remote_execution_properties = {+ "platform": "linux-remote-execution",+ },+ remote_execution_use_case = "buck2-default",+ ),+ "test-execution": test_execution_executor_override,+ }++def _compute_emulator_abi(labels: list[str]):+ emulator_abi_labels = [label for label in labels if label.startswith(ANDROID_EMULATOR_ABI_LABEL_PREFIX)]+ expect(+ len(emulator_abi_labels) <= 1,+ "multiple '{}' labels were found:[{}], there must be only one!".format(ANDROID_EMULATOR_ABI_LABEL_PREFIX, ", ".join(emulator_abi_labels)),+ )+ if len(emulator_abi_labels) == 0:+ return None+ else: # len(emulator_abi_labels) == 1:+ return emulator_abi_labels[0].replace(ANDROID_EMULATOR_ABI_LABEL_PREFIX, "")++# replicating the logic in https://fburl.com/code/1fqowxu4 to match buck1's behavior+def _compute_emulator_subplatform(labels: list[str]) -> str:+ emulator_subplatform_labels = [label for label in labels if label.startswith("re_emulator_")]+ expect(+ len(emulator_subplatform_labels) <= 1,+ "multiple 're_emulator_' labels were found:[{}], there must be only one!".format(", ".join(emulator_subplatform_labels)),+ )+ if len(emulator_subplatform_labels) == 0:+ return DEFAULT_ANDROID_SUBPLATFORM+ else: # len(emulator_subplatform_labels) == 1:+ return emulator_subplatform_labels[0].replace("re_emulator_", "")++def _compute_emulator_platform(labels: list[str]) -> str:+ emulator_platform_labels = [label for label in labels if label.startswith("re_platform_")]+ expect(+ len(emulator_platform_labels) <= 1,+ "multiple 're_platform_' labels were found:[{}], there must be only one!".format(", ".join(emulator_platform_labels)),+ )+ if len(emulator_platform_labels) == 0:+ subplatform = _compute_emulator_subplatform(labels)+ if "aarch64" in subplatform:+ return "android-emulator-aarch64"+ if subplatform == "android-33-google-arm64":+ return "android-emulator-mac"+ return DEFAULT_ANDROID_PLATFORM+ else: # len(emulator_platform_labels) == 1:+ return emulator_platform_labels[0].replace("re_platform_", "")++def _compute_re_use_case(labels: list[str]) -> str:+ re_use_case_labels = [label for label in labels if label.startswith("re_opts_use_case=")]+ expect(len(re_use_case_labels) <= 1, "multiple 're_opts_use_case' labels were found:[{}], there must be only one!".format(", ".join(re_use_case_labels)))+ if len(re_use_case_labels) == 0:+ return DEFAULT_ANDROID_INSTRUMENTATION_TESTS_USE_CASE+ else: # len(re_use_case_labels) == 1:+ return re_use_case_labels[0].replace("re_opts_use_case=", "")++def _validate_executor_override_re_config(re_caps: dict[str, str], re_use_case: str):+ expect(+ re_use_case in SUPPORTED_USE_CASES,+ "Unexpected {} use case found, value is expected to be on of the following: {}",+ re_use_case,+ ", ".join(SUPPORTED_USE_CASES),+ )+ if "pool" in re_caps:+ expect(+ re_caps["pool"] in SUPPORTED_POOLS,+ "Unexpected {} pool found, value is expected to be on of the following: {}",+ re_caps["pool"],+ ", ".join(SUPPORTED_POOLS),+ )+ if "platform" in re_caps:+ expect(+ re_caps["platform"] in SUPPORTED_PLATFORMS,+ "Unexpected {} platform found, value is expected to be on of the following: {}",+ re_caps["platform"],+ ", ".join(SUPPORTED_PLATFORMS),+ )
@@ -0,0 +1,223 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")+load(+ "@prelude//android:android_providers.bzl",+ "AndroidLibraryIntellijInfo",+ "AndroidResourceInfo",+ "merge_android_packageable_info",+ "merge_exported_android_resource_info",+)+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//android:r_dot_java.bzl", "get_dummy_r_dot_java")+load("@prelude//capabilities:capabilities_registration.bzl", "capabilities_registration_providers")+load("@prelude//graphql:graphql.bzl", "graphql_providers")+load("@prelude//java:java_library.bzl", "build_java_library")+load(+ "@prelude//java:java_providers.bzl",+ "JavaLibraryInfo",+ "JavaProviders", # @unused Used as type+ "create_native_providers",+ "to_list",+)+load(+ "@prelude//java/utils:java_utils.bzl",+ "CustomJdkInfo",+ "get_java_version_attributes",+ "get_string_concat_inline_javac_args",+)+load("@prelude//kotlin:kotlin_library.bzl", "build_kotlin_library")+load("@prelude//target_stats:target_stats.bzl", "CycleMode", "target_stats_providers_and_subtargets")+load("@prelude//target_stats:target_stats_config.bzl", "TARGET_STATS_ENABLED")+load("@prelude//utils:expect.bzl", "expect")+load("@prelude//utils:label_provider.bzl", "LabelInfo")++def get_custom_jdk_info(ctx: AnalysisContext) -> CustomJdkInfo:+ bootclasspath_entries = [] + ctx.attrs._android_toolchain[AndroidToolchainInfo].android_bootclasspath + optional_jars(ctx)+ bootclasspath_snapshots = [] + ctx.attrs._android_toolchain[AndroidToolchainInfo].android_bootclasspath_snapshots + optional_abi_jar_snapshots(ctx)++ return CustomJdkInfo(+ bootclasspath = bootclasspath_entries,+ bootclasspath_jar_snapshots = bootclasspath_snapshots,+ system_image = ctx.attrs._android_toolchain[AndroidToolchainInfo].jdk_system_image,+ )++def android_target_stats(ctx: AnalysisContext) -> (list[Provider], dict[str, list[Provider]]):+ if not TARGET_STATS_ENABLED:+ return [], {}+ tools = ctx.attrs._android_toolchain[AndroidToolchainInfo].target_stats_tools+ if tools == None:+ return [], {}+ return target_stats_providers_and_subtargets(+ ctx,+ tools = tools,+ srcs = {src.short_path: src for src in ctx.attrs.srcs},+ # Target stats cover the compile graph, including non-packaged provided deps.+ deps = (ctx.attrs.deps + ctx.attrs.exported_deps + ctx.attrs.runtime_deps + ctx.attrs.provided_deps + ctx.attrs.exported_provided_deps),+ cycle_mode = CycleMode("package"),+ module_name = ctx.label.name,+ )++def android_library_impl(ctx: AnalysisContext) -> list[Provider]:+ packaging_deps = ctx.attrs.deps + ctx.attrs.exported_deps + ctx.attrs.runtime_deps+ if ctx.attrs._build_only_native_code:+ shared_library_info, cxx_resource_info, linkable_graph = create_native_providers(ctx, ctx.label, packaging_deps)+ return [+ merge_android_packageable_info(ctx.label, ctx.actions, packaging_deps),+ shared_library_info,+ cxx_resource_info,+ linkable_graph,+ # Add an unused default output in case this target is used as an attr.source() anywhere.+ DefaultInfo(+ default_output = ctx.actions.write("{}/unused.jar".format(ctx.label.name), [], has_content_based_path = False),+ sub_targets = {+ "generated_sources": [+ DefaultInfo(default_output = ctx.actions.write("{}/generated_sources".format(ctx.label.name), [], has_content_based_path = False)),+ ],+ },+ ),+ TemplatePlaceholderInfo(+ keyed_variables = {+ "classpath": "unused_but_needed_for_analysis",+ },+ ),+ ]++ target_stats_providers, target_stats_subtargets = android_target_stats(ctx)++ java_providers, android_library_intellij_info = build_android_library(+ ctx = ctx,+ validation_deps_outputs = get_validation_deps_outputs(ctx),+ extra_sub_targets = target_stats_subtargets,+ )+ android_providers = [android_library_intellij_info] if android_library_intellij_info else []++ return (+ to_list(java_providers)+ + [+ merge_android_packageable_info(+ ctx.label,+ ctx.actions,+ packaging_deps,+ manifest = ctx.attrs.manifest,+ ),+ merge_exported_android_resource_info(ctx.attrs.exported_deps),+ ]+ + android_providers+ + [LabelInfo(labels = ctx.attrs.labels)]+ + graphql_providers(ctx)+ + capabilities_registration_providers(ctx)+ + target_stats_providers+ )++def optional_jars(ctx: AnalysisContext) -> list[Artifact]:+ if not ctx.attrs.android_optional_jars:+ return []++ result = []+ for dep in ctx.attrs.android_optional_jars:+ java_library_info = dep.get(JavaLibraryInfo)+ expect(+ java_library_info != None and java_library_info.library_output != None,+ "Only targets producing a Java bytecode output can be added as 'android_optional_jars'!",+ )+ result.append(java_library_info.library_output.full_library)++ return result++def optional_abi_jar_snapshots(ctx: AnalysisContext) -> list[Artifact]:+ if not ctx.attrs.android_optional_jars:+ return []++ result = []+ for dep in ctx.attrs.android_optional_jars:+ java_library_info = dep.get(JavaLibraryInfo)+ expect(+ java_library_info != None and java_library_info.library_output != None,+ "Only targets producing a Java bytecode output can be added as 'android_optional_jars'!",+ )++ if java_library_info.library_output.abi_jar_snapshot:+ result.append(java_library_info.library_output.abi_jar_snapshot)++ return result++def build_android_library(+ ctx: AnalysisContext,+ r_dot_java: JavaLibraryInfo | None = None,+ extra_sub_targets = {},+ validation_deps_outputs: [list[Artifact], None] = None,+) -> (JavaProviders, [AndroidLibraryIntellijInfo, None]):+ custom_jdk_info = get_custom_jdk_info(ctx)+ dummy_r_dot_java_info, android_library_intellij_info = _get_dummy_r_dot_java(ctx)+ extra_sub_targets = dict(extra_sub_targets)++ if r_dot_java:+ additional_classpath_entries = r_dot_java.compiling_deps+ elif dummy_r_dot_java_info:+ additional_classpath_entries = dummy_r_dot_java_info.compiling_deps+ extra_sub_targets["dummy_r_dot_java"] = [DefaultInfo(default_output = dummy_r_dot_java_info.library_output.full_library)]+ else:+ additional_classpath_entries = None++ source_level, _ = get_java_version_attributes(ctx)+ extra_arguments = get_string_concat_inline_javac_args(source_level)++ if ctx.attrs.patches_system_module:+ extra_arguments += [+ "--patch-module",+ "java.base=.",+ ]++ if ctx.attrs.language != None and ctx.attrs.language.lower() == "kotlin":+ return build_kotlin_library(+ ctx,+ additional_classpath_entries = additional_classpath_entries,+ custom_jdk_info = custom_jdk_info,+ extra_sub_targets = extra_sub_targets,+ validation_deps_outputs = validation_deps_outputs,+ extra_arguments = extra_arguments,+ ), android_library_intellij_info+ else:+ return build_java_library(+ ctx,+ ctx.attrs.srcs,+ additional_classpath_entries = additional_classpath_entries,+ custom_jdk_info = custom_jdk_info,+ extra_sub_targets = extra_sub_targets,+ validation_deps_outputs = validation_deps_outputs,+ extra_arguments = extra_arguments,+ ), android_library_intellij_info++def _get_dummy_r_dot_java(ctx: AnalysisContext) -> (JavaLibraryInfo | None, [AndroidLibraryIntellijInfo, None]):+ android_resources = dedupe([+ resource+ for resource in filter(+ None,+ [x.get(AndroidResourceInfo) for x in ctx.attrs.deps + ctx.attrs.provided_deps + (getattr(ctx.attrs, "provided_deps_query", []) or [])],+ )+ if resource.res != None+ ])+ if len(android_resources) == 0:+ return (None, None)++ dummy_r_dot_java_info = get_dummy_r_dot_java(+ ctx,+ ctx.attrs._android_toolchain[AndroidToolchainInfo].merge_android_resources[RunInfo],+ android_resources,+ )++ dummy_r_dot_java = dummy_r_dot_java_info.library_output+ return (+ dummy_r_dot_java_info,+ AndroidLibraryIntellijInfo(+ dummy_r_dot_java = dummy_r_dot_java.abi,+ android_resource_deps = android_resources,+ ),+ )
@@ -0,0 +1,89 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//android:android_providers.bzl",+ "AndroidManifestInfo",+ "ManifestTSet", # @unused Used as type+ "merge_android_packageable_info",+)+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//android:voltron.bzl", "ROOT_MODULE")+load("@prelude//utils:argfile.bzl", "argfile")++def android_manifest_impl(ctx: AnalysisContext) -> list[Provider]:+ output, merge_report = generate_android_manifest(+ ctx,+ ctx.attrs._android_toolchain[AndroidToolchainInfo].generate_manifest[RunInfo],+ ctx.attrs.skeleton,+ ROOT_MODULE,+ _get_manifests_from_deps(ctx),+ {},+ )++ return [+ AndroidManifestInfo(manifest = output, merge_report = merge_report),+ DefaultInfo(default_output = output, other_outputs = [merge_report]),+ ]++def generate_android_manifest(+ ctx: AnalysisContext,+ generate_manifest: RunInfo,+ manifest_skeleton: Artifact,+ module_name: str,+ manifests: [ManifestTSet, list[Artifact], None],+ placeholder_entries: dict,+) -> (Artifact, Artifact):+ generate_manifest_cmd = cmd_args(generate_manifest)+ generate_manifest_cmd.add([+ "--skeleton-manifest",+ manifest_skeleton,+ "--module-name",+ module_name,+ ])++ if not manifests:+ manifests = []+ elif isinstance(manifests, TransitiveSet):+ # Manifests are usually resolved only at the binary level, so resolving+ # projection nodes throughout the dependency graph is wasteful.+ manifests = [entry.manifest for entry in manifests.traverse(ordering = "topological")]++ library_manifest_paths_file = argfile(actions = ctx.actions, name = "{}/library_manifest_paths_file".format(module_name), args = manifests)++ generate_manifest_cmd.add(["--library-manifests-list", library_manifest_paths_file])++ placeholder_entries_args = cmd_args()+ for key, val in placeholder_entries.items():+ placeholder_entries_args.add(cmd_args(str(key), str(val), delimiter = " "))+ placeholder_entries_file = ctx.actions.write("{}/placeholder_entries_file".format(module_name), placeholder_entries_args, has_content_based_path = False)++ generate_manifest_cmd.add(["--placeholder-entries-list", placeholder_entries_file])++ output = ctx.actions.declare_output("{}/AndroidManifest.xml".format(module_name), has_content_based_path = False)+ merge_report = ctx.actions.declare_output("{}/merge-report.txt".format(module_name), has_content_based_path = False)+ preprocess_log = ctx.actions.declare_output("{}/preprocess-log.txt".format(module_name), has_content_based_path = False)+ generate_manifest_cmd.add([+ "--output",+ output.as_output(),+ "--merge-report",+ merge_report.as_output(),+ "--preprocess-log",+ preprocess_log.as_output(),+ ])++ ctx.actions.run(generate_manifest_cmd, category = "generate_manifest", identifier = module_name)++ return (output, merge_report)++def _get_manifests_from_deps(ctx: AnalysisContext) -> [ManifestTSet, None]:+ if len(ctx.attrs.deps) == 0:+ return None++ android_packageable_info = merge_android_packageable_info(ctx.label, ctx.actions, ctx.attrs.deps)+ return android_packageable_info.manifests
@@ -0,0 +1,172 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//android:android_providers.bzl",+ "AndroidResourceInfo",+ "AndroidResourceRDotInfo",+ "PrebuiltNativeLibraryDir",+ "RESOURCE_PRIORITY_LOW",+ "merge_android_packageable_info",+)+load("@prelude//android:android_resource.bzl", "aapt2_compile", "extract_package_from_manifest")+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//android:r_dot_java.bzl", "get_dummy_r_dot_java")+load(+ "@prelude//java:java_providers.bzl",+ "ClasspathSnapshotGranularity",+ "JavaClasspathEntry",+ "create_abi",+ "create_java_library_providers",+ "generate_java_classpath_snapshot",+)+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")++def android_prebuilt_aar_impl(ctx: AnalysisContext) -> list[Provider]:+ manifest = ctx.actions.declare_output("AndroidManifest.xml", has_content_based_path = True)+ all_classes_jar = ctx.actions.declare_output("classes.jar", has_content_based_path = True)+ r_dot_txt = ctx.actions.declare_output("R.txt", has_content_based_path = True)+ res = ctx.actions.declare_output("res", dir = True, has_content_based_path = True)+ assets = ctx.actions.declare_output("assets", dir = True, has_content_based_path = True)+ jni = ctx.actions.declare_output("jni", dir = True, has_content_based_path = True)+ annotation_jars_dir = ctx.actions.declare_output("annotation_jars", dir = True, has_content_based_path = True)+ proguard_config = ctx.actions.declare_output("proguard.txt", has_content_based_path = True)+ lint_jar = ctx.actions.declare_output("lint.jar", has_content_based_path = True)++ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]+ unpack_aar_tool = android_toolchain.unpack_aar[RunInfo]+ java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]+ jar_builder_tool = cmd_args(java_toolchain.jar_builder, delimiter = " ")++ unpack_aar_cmd = [+ unpack_aar_tool,+ "--aar",+ ctx.attrs.aar,+ "--manifest-path",+ manifest.as_output(),+ "--all-classes-jar-path",+ all_classes_jar.as_output(),+ "--r-dot-txt-path",+ r_dot_txt.as_output(),+ "--res-path",+ res.as_output(),+ "--assets-path",+ assets.as_output(),+ "--jni-path",+ jni.as_output(),+ "--annotation-jars-dir",+ annotation_jars_dir.as_output(),+ "--proguard-config-path",+ proguard_config.as_output(),+ "--jar-builder-tool",+ jar_builder_tool,+ "--lint-jar-path",+ lint_jar.as_output(),+ ]++ ctx.actions.run(unpack_aar_cmd, category = "android_unpack_aar")++ resource_info = AndroidResourceInfo(+ raw_target = ctx.label.raw_target(),+ aapt2_compile_output = aapt2_compile(ctx, res, android_toolchain),+ allow_strings_as_assets_resource_filtering = True,+ assets = [assets],+ manifest_file = manifest,+ r_dot_java_package = extract_package_from_manifest(ctx, manifest),+ res = res,+ res_priority = RESOURCE_PRIORITY_LOW,+ text_symbols = r_dot_txt,+ unused_resource_dep_validation_has_non_xml_resources = True,+ )++ dummy_r_dot_java_info = get_dummy_r_dot_java(+ ctx,+ android_toolchain.merge_android_resources[RunInfo],+ [resource_info],+ )++ android_resource_r_dot_info = AndroidResourceRDotInfo(+ dummy_r_dot_java = dummy_r_dot_java_info.library_output.abi,+ )++ abi = None if java_toolchain.is_bootstrap_toolchain else create_abi(ctx.actions, java_toolchain.class_abi_generator, all_classes_jar)+ abi_jar_snapshot = generate_java_classpath_snapshot(+ ctx.actions, java_toolchain.cp_snapshot_generator, ClasspathSnapshotGranularity("CLASS_LEVEL"), abi or all_classes_jar, ""+ )++ library_output_classpath_entry = JavaClasspathEntry(+ full_library = all_classes_jar,+ abi = abi or all_classes_jar,+ abi_as_dir = None,+ required_for_source_only_abi = ctx.attrs.required_for_source_only_abi,+ abi_jar_snapshot = abi_jar_snapshot,+ )++ (+ java_library_info,+ java_packaging_info,+ global_code_info,+ shared_library_info,+ linkable_graph,+ cxx_resource_info,+ template_placeholder_info,+ java_library_intellij_info,+ ) = create_java_library_providers(+ ctx = ctx,+ library_output = library_output_classpath_entry,+ global_code_config = java_toolchain.global_code_config,+ exported_deps = ctx.attrs.deps,+ provided_deps = ctx.attrs.desugar_deps,+ is_prebuilt_jar = True,+ annotation_jars_dir = annotation_jars_dir,+ proguard_config = proguard_config,+ lint_jar = lint_jar,+ sources_jar = ctx.attrs.source_jar,+ dex_weight_factor = ctx.attrs.dex_weight_factor,+ )++ native_library = PrebuiltNativeLibraryDir(+ raw_target = ctx.label.raw_target(),+ dir = jni,+ for_primary_apk = ctx.attrs.use_system_library_loader,+ is_asset = False,+ )++ return [+ java_library_info,+ java_packaging_info,+ global_code_info,+ shared_library_info,+ cxx_resource_info,+ linkable_graph,+ template_placeholder_info,+ java_library_intellij_info,+ android_resource_r_dot_info,+ merge_android_packageable_info(+ ctx.label,+ ctx.actions,+ ctx.attrs.deps,+ manifest = manifest,+ prebuilt_native_library_dir = native_library,+ resource_info = resource_info,+ for_primary_apk = ctx.attrs.for_primary_apk,+ ),+ resource_info,+ DefaultInfo(+ default_output = all_classes_jar,+ other_outputs = [+ manifest,+ r_dot_txt,+ res,+ assets,+ jni,+ annotation_jars_dir,+ proguard_config,+ ],+ ),+ ]
@@ -0,0 +1,401 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//java:java_providers.bzl", "JavaLibraryInfo")++Aapt2LinkInfo = record(+ # "APK" containing resources to be used by the Android binary+ primary_resources_apk = Artifact,+ # proguard config needed to retain used resources+ proguard_config_file = Artifact,+ # R.txt containing all the linked resources+ r_dot_txt = Artifact,+)++PrebuiltNativeLibraryDir = record(+ raw_target = TargetLabel,+ dir = Artifact, # contains subdirectories for different ABIs.+ for_primary_apk = bool,+ is_asset = bool,+)++ExopackageDexInfo = record(+ metadata = Artifact,+ directory = Artifact,+)++ExopackageNativeInfo = record(+ metadata = Artifact,+ directory = Artifact,+)++ExopackageResourcesInfo = record(+ assets = Artifact | None,+ assets_hash = Artifact | None,+ res = Artifact,+ res_hash = Artifact,+)++RDotJavaInfo = record(+ identifier = str,+ library_info = JavaLibraryInfo,+ source_zipped = Artifact,+)++AndroidBinaryNativeLibsInfo = record(+ prebuilt_native_library_dirs = list[PrebuiltNativeLibraryDir],+ # Indicates which shared lib producing targets are included in the binary. Used by instrumentation tests+ # to exclude those from the test apk.+ shared_libraries = list[TargetLabel],+ exopackage_info = [ExopackageNativeInfo, None],+ root_module_native_lib_assets = list[Artifact],+ non_root_module_native_lib_assets = list[Artifact],+ native_libs_for_primary_apk = list[Artifact],+ generated_java_code = list[Artifact],+ unstripped_shared_libraries = [Artifact, None],+ # Artifacts that must be produced for the binary to be valid. Threaded into+ # the apk's validation_deps_outputs, so a failing check fails the build.+ validation_outputs = list[Artifact],+)++AndroidBinaryResourcesInfo = record(+ # Optional information about resources that should be exopackaged+ exopackage_info = [ExopackageResourcesInfo, None],+ # manifest to be used by the APK+ manifest = Artifact,+ # per-module manifests (packaged as assets)+ module_manifests = list[Artifact],+ # per-module assets APKs (for .aabs only)+ module_assets = Artifact | None,+ # zip containing any strings packaged as assets+ packaged_string_assets = Artifact | None,+ # "APK" containing resources to be used by the Android binary+ primary_resources_apk = Artifact,+ # proguard config needed to retain used resources+ proguard_config_file = Artifact,+ # R.java jars containing all the linked resources+ r_dot_java_infos = list[RDotJavaInfo],+ # directory containing filtered string resources files+ string_source_map = Artifact | None,+ # directory containing filtered string resources files for Voltron language packs+ voltron_string_source_map = Artifact | None,+ # list of jars that could contain resources that should be packaged into the APK+ jar_files_that_may_contain_resources = list[Artifact],+ # The resource infos that are used in this APK+ unfiltered_resource_infos = list, # list[AndroidResourceInfo]+)++# Information about an `android_build_config`+BuildConfigField = record(+ type = str,+ name = str,+ value = str,+)++AndroidBuildConfigInfo = provider(+ # @unsorted-dict-items+ fields = {+ "package": str,+ "build_config_fields": list[BuildConfigField],+ "values_file": provider_field(Artifact | None, default = None),+ },+)++# Information about an `android_manifest`+AndroidManifestInfo = provider(+ fields = {+ "manifest": provider_field(Artifact),+ "merge_report": provider_field(Artifact),+ },+)++AndroidApkInfo = provider(+ fields = {+ "apk": provider_field(Artifact),+ "manifest": provider_field(Artifact),+ "materialized_artifacts": provider_field(list[Artifact]),+ "unstripped_shared_libraries": provider_field(Artifact | None, default = None),+ },+)++AndroidPreprocessedJavaClassesInfo = provider(+ fields = {+ "input_dir": provider_field(Artifact),+ "materialized_artifacts_dir": provider_field(Artifact),+ },+)++# Exopackage secondary-dex dir (metadata.txt + secondary-N.dex.jar) so android_instrumentation_test+# can push it to the device. Only set when the apk is built with exopackage secondary_dex mode.+AndroidApkExopackageInfo = provider(+ fields = {+ "secondary_dex_directory": provider_field(Artifact),+ },+)++AndroidAabInfo = provider(+ fields = {+ "aab": provider_field(Artifact),+ "manifest": provider_field(Artifact),+ "materialized_artifacts": provider_field(list[Artifact]),+ "unstripped_shared_libraries": provider_field(Artifact | None, default = None),+ },+)++AndroidDerivedApkInfo = provider(+ fields = {+ "apk": provider_field(Artifact),+ },+)++AndroidBinaryPrimaryPlatformInfo = provider(+ fields = {+ "primary_platform": provider_field(typing.Any, default = None), # str+ },+)++AndroidApkUnderTestInfo = provider(+ # @unsorted-dict-items+ fields = {+ "java_packaging_deps": provider_field(typing.Any, default = None), # set(TargetLabel)+ "keystore": provider_field(typing.Any, default = None), # "KeystoreInfo"+ "manifest_entries": provider_field(typing.Any, default = None), # dict+ "min_sdk_version": provider_field(typing.Any, default = None), # int+ "platform_configurations": provider_field(typing.Any, default = None), # [str]+ "platforms": provider_field(typing.Any, default = None), # [str]+ "prebuilt_native_library_dirs": provider_field(typing.Any, default = None), # set(TargetLabel)+ "primary_platform": provider_field(typing.Any, default = None), # str+ "resource_infos": provider_field(typing.Any, default = None), # set(TargetLabel)+ "r_dot_java_packages": provider_field(typing.Any, default = None), # set(str)+ "shared_libraries": provider_field(typing.Any, default = None), # set(TargetLabel)+ # Merge map delegate+ "native_library_merge_code_generator": provider_field(typing.Any, default = None),+ "native_library_merge_glue": provider_field(typing.Any, default = None),+ "native_library_merge_linker_args_all": provider_field(typing.Any, default = None),+ "native_library_merge_map": provider_field(typing.Any, default = None),+ "native_library_merge_non_asset_libs": provider_field(typing.Any, default = False),+ "native_library_merge_linker_args": provider_field(typing.Any, default = None),+ "native_library_merge_sequence": provider_field(typing.Any, default = None),+ "native_library_merge_sequence_blocklist": provider_field(typing.Any, default = None),+ },+)++AndroidInstrumentationApkInfo = provider(+ fields = {+ "apk_under_test": provider_field(typing.Any, default = None), # "artifact"+ "is_self_instrumenting": provider_field(bool, default = False),+ },+)++KeystoreInfo = provider(+ # @unsorted-dict-items+ fields = {+ "store": provider_field(Artifact),+ "properties": provider_field(Artifact),+ },+)++ManifestInfo = record(+ target_label = TargetLabel,+ manifest = Artifact,+)++def _artifacts(value: ManifestInfo):+ return value.manifest++AndroidBuildConfigInfoTSet = transitive_set()+AndroidDepsTSet = transitive_set()+ManifestTSet = transitive_set(args_projections = {"artifacts": _artifacts})+PrebuiltNativeLibraryDirTSet = transitive_set()+ResourceInfoTSet = transitive_set()++DepsInfo = record(+ name = TargetLabel,+ deps = list[TargetLabel],+ for_primary_apk = bool,+)++AndroidPackageableInfo = provider(+ # @unsorted-dict-items+ fields = {+ "target_label": provider_field(typing.Any, default = None), # "target_label"+ "build_config_infos": provider_field(typing.Any, default = None), # ["AndroidBuildConfigInfoTSet", None]+ "deps": provider_field(typing.Any, default = None), # ["AndroidDepsTSet", None]+ "manifests": provider_field(typing.Any, default = None), # ["ManifestTSet", None]+ "prebuilt_native_library_dirs": provider_field(typing.Any, default = None), # ["PrebuiltNativeLibraryDirTSet", None]+ "resource_infos": provider_field(typing.Any, default = None), # ["AndroidResourceInfoTSet", None]+ },+)++RESOURCE_PRIORITY_NORMAL = "normal"+RESOURCE_PRIORITY_LOW = "low"++# Information about an `android_resource`+AndroidResourceInfo = provider(+ # @unsorted-dict-items+ fields = {+ # Target that produced this provider+ "raw_target": provider_field(typing.Any, default = None), # TargetLabel+ # output of running `aapt2_compile` on the resources, if resources are present+ "aapt2_compile_output": provider_field(Artifact | None, default = None),+ # locales that should always be included in the APK for this resource+ "allowlisted_locales": provider_field(typing.Any, default = []), # List+ # if False, then the "res" are not affected by the strings-as-assets resource filter+ "allow_strings_as_assets_resource_filtering": provider_field(typing.Any, default = None), # bool+ # assets defined by this rule. May be empty+ "assets": provider_field(list[Artifact], default = []),+ # manifest file used by the resources, if resources are present+ "manifest_file": provider_field(Artifact | None, default = None),+ # the package specified by the android_resource rule itself+ "specified_r_dot_java_package": provider_field(typing.Any, default = None), # str | None+ # package used for R.java, if resources are present+ "r_dot_java_package": provider_field(Artifact | None, default = None),+ # resources defined by this rule. May be empty+ "res": provider_field(Artifact | None, default = None),+ # whether this resource contains non-XML resources+ "unused_resource_dep_validation_has_non_xml_resources": provider_field(bool, default = False),+ # priority of the resources, may be 'low' or 'normal'+ "res_priority": provider_field(typing.Any, default = None), # str+ # symbols defined by the resources, if resources are present+ "text_symbols": provider_field(Artifact | None, default = None),+ },+)++# `AndroidResourceInfos` that are exposed via `exported_deps`+ExportedAndroidResourceInfo = provider(+ fields = {+ "resource_infos": provider_field(typing.Any, default = None), # ["AndroidResourceInfo"]+ },+)++DexFilesInfo = record(+ primary_dex = Artifact,+ primary_dex_class_names = Artifact | None,+ root_module_bootstrap_dex_dirs = list[Artifact],+ root_module_secondary_dex_dirs = list[Artifact],+ non_root_module_secondary_dex_dirs = list[Artifact],+ secondary_dex_exopackage_info = [ExopackageDexInfo, None],+ proguard_text_files_path = Artifact | None,+)++ExopackageInfo = record(+ secondary_dex_info = [ExopackageDexInfo, None],+ native_library_info = [ExopackageNativeInfo, None],+ resources_info = [ExopackageResourcesInfo, None],+)++AndroidLibraryIntellijInfo = provider(+ # @unsorted-dict-items+ doc = "Information about android library that is required for Intellij project generation",+ fields = {+ "android_resource_deps": provider_field(typing.Any, default = None), # ["AndroidResourceInfo"]+ "dummy_r_dot_java": provider_field(Artifact | None, default = None),+ },+)++AndroidResourceRDotInfo = provider(+ # @unsorted-dict-items+ doc = "Exposes the compiled R.jar for android_prebuilt_aar and android_resource targets",+ fields = {+ "dummy_r_dot_java": provider_field(Artifact | None, default = None),+ },+)++def merge_android_packageable_info(+ label: Label,+ actions: AnalysisActions,+ deps: list[Dependency],+ build_config_info: [AndroidBuildConfigInfo, None] = None,+ manifest: Artifact | None = None,+ prebuilt_native_library_dir: [PrebuiltNativeLibraryDir, None] = None,+ resource_info: [AndroidResourceInfo, None] = None,+ for_primary_apk: bool = False,+) -> AndroidPackageableInfo:+ android_packageable_deps = filter(None, [x.get(AndroidPackageableInfo) for x in deps])++ build_config_infos = _get_transitive_set(+ actions,+ filter(None, [dep.build_config_infos for dep in android_packageable_deps]),+ build_config_info,+ AndroidBuildConfigInfoTSet,+ )++ deps = _get_transitive_set(+ actions,+ filter(None, [dep.deps for dep in android_packageable_deps]),+ DepsInfo(+ name = label.raw_target(),+ deps = [dep.target_label for dep in android_packageable_deps],+ for_primary_apk = for_primary_apk,+ ),+ AndroidDepsTSet,+ )++ manifests = _get_transitive_set(+ actions,+ filter(None, [dep.manifests for dep in android_packageable_deps]),+ ManifestInfo(+ target_label = label.raw_target(),+ manifest = manifest,+ )+ if manifest+ else None,+ ManifestTSet,+ )++ prebuilt_native_library_dirs = _get_transitive_set(+ actions,+ filter(None, [dep.prebuilt_native_library_dirs for dep in android_packageable_deps]),+ prebuilt_native_library_dir,+ PrebuiltNativeLibraryDirTSet,+ )++ resource_infos = _get_transitive_set(+ actions,+ filter(None, [dep.resource_infos for dep in android_packageable_deps]),+ resource_info,+ ResourceInfoTSet,+ )++ return AndroidPackageableInfo(+ target_label = label.raw_target(),+ build_config_infos = build_config_infos,+ deps = deps,+ manifests = manifests,+ prebuilt_native_library_dirs = prebuilt_native_library_dirs,+ resource_infos = resource_infos,+ )++def _get_transitive_set(+ actions: AnalysisActions, children: list[TransitiveSet], node: typing.Any, transitive_set_definition: TransitiveSetDefinition+) -> [TransitiveSet, None]:+ kwargs = {}+ if children:+ kwargs["children"] = children+ if node:+ kwargs["value"] = node++ return actions.tset(transitive_set_definition, **kwargs) if kwargs else None++def merge_exported_android_resource_info(exported_deps: list[Dependency]) -> ExportedAndroidResourceInfo:+ exported_android_resource_infos = []+ for exported_dep in exported_deps:+ exported_resource_info = exported_dep.get(ExportedAndroidResourceInfo)+ if exported_resource_info:+ exported_android_resource_infos += exported_resource_info.resource_infos++ android_resource = exported_dep.get(AndroidResourceInfo)+ if android_resource:+ exported_android_resource_infos.append(android_resource)++ return ExportedAndroidResourceInfo(resource_infos = dedupe(exported_android_resource_infos))++def get_all_android_packageable_targets(deps: list[Dependency]) -> list[TargetLabel]:+ android_packageable_infos = filter(None, [dep.get(AndroidPackageableInfo) for dep in deps])+ android_deps_tsets = filter(None, [dep.deps for dep in android_packageable_infos])+ return [deps_info.name for android_deps_tset in android_deps_tsets for deps_info in android_deps_tset.traverse()]
@@ -0,0 +1,199 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//java:java_providers.bzl", "derive_compiling_deps_wrapper", "get_global_code_info", "get_java_packaging_info")+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")+load("@prelude//utils:argfile.bzl", "argfile")+load("@prelude//utils:expect.bzl", "expect")+load(+ ":android_providers.bzl",+ "AndroidResourceInfo",+ "AndroidResourceRDotInfo",+ "ExportedAndroidResourceInfo",+ "RESOURCE_PRIORITY_NORMAL",+ "merge_android_packageable_info",+)+load(":android_toolchain.bzl", "AndroidToolchainInfo")+load(":r_dot_java.bzl", "get_dummy_r_dot_java")++JAVA_PACKAGE_FILENAME = "java_package.txt"++def _convert_to_artifact_dir(ctx: AnalysisContext, attr: [Dependency, dict, Artifact, None], attr_name: str) -> Artifact | None:+ if isinstance(attr, Dependency):+ expect(len(attr[DefaultInfo].default_outputs) == 1, "Expect one default output from build dep of attr {}!".format(attr_name))+ return attr[DefaultInfo].default_outputs[0]+ elif type(attr) == "dict":+ return None if len(attr) == 0 else ctx.actions.symlinked_dir(attr_name, attr, has_content_based_path = True)+ else:+ return attr++def android_resource_impl(ctx: AnalysisContext) -> list[Provider]:+ if ctx.attrs._build_only_native_code:+ return [DefaultInfo()]++ sub_targets = {}+ providers = []+ default_output = None++ res = _convert_to_artifact_dir(ctx, ctx.attrs.res, "res")+ asset = _convert_to_artifact_dir(ctx, ctx.attrs.assets, "assets")+ assets = [asset] if asset else []+ unused_resource_dep_validation_has_non_xml_resources = ctx.attrs.unused_resource_dep_validation_has_non_xml_resources+ if unused_resource_dep_validation_has_non_xml_resources == None:+ unused_resource_dep_validation_has_non_xml_resources = ctx.attrs.res != None+ unused_resource_dep_validation_has_non_xml_resources = unused_resource_dep_validation_has_non_xml_resources or bool(assets) or ctx.attrs.manifest != None++ if res:+ aapt2_compile_output = aapt2_compile(ctx, res, ctx.attrs._android_toolchain[AndroidToolchainInfo])++ sub_targets["aapt2_compile"] = [DefaultInfo(default_output = aapt2_compile_output)]++ r_dot_txt_output = get_text_symbols(ctx, res, ctx.attrs.deps)+ default_output = r_dot_txt_output++ r_dot_java_package = _get_package(ctx, ctx.attrs.package, ctx.attrs.manifest)+ resource_info = AndroidResourceInfo(+ raw_target = ctx.label.raw_target(),+ aapt2_compile_output = aapt2_compile_output,+ allowlisted_locales = ctx.attrs.allowlisted_locales,+ allow_strings_as_assets_resource_filtering = not ctx.attrs.has_whitelisted_strings,+ assets = assets,+ manifest_file = ctx.attrs.manifest,+ specified_r_dot_java_package = ctx.attrs.package,+ r_dot_java_package = r_dot_java_package,+ res = res,+ res_priority = RESOURCE_PRIORITY_NORMAL,+ text_symbols = r_dot_txt_output,+ unused_resource_dep_validation_has_non_xml_resources = unused_resource_dep_validation_has_non_xml_resources,+ )+ else:+ resource_info = AndroidResourceInfo(+ raw_target = ctx.label.raw_target(),+ aapt2_compile_output = None,+ allowlisted_locales = ctx.attrs.allowlisted_locales,+ allow_strings_as_assets_resource_filtering = not ctx.attrs.has_whitelisted_strings,+ assets = assets,+ manifest_file = ctx.attrs.manifest,+ specified_r_dot_java_package = None,+ r_dot_java_package = None,+ res = None,+ res_priority = RESOURCE_PRIORITY_NORMAL,+ text_symbols = None,+ unused_resource_dep_validation_has_non_xml_resources = unused_resource_dep_validation_has_non_xml_resources,+ )+ providers.append(resource_info)+ providers.append(merge_android_packageable_info(ctx.label, ctx.actions, ctx.attrs.deps, manifest = ctx.attrs.manifest, resource_info = resource_info))+ providers.append(get_java_packaging_info(ctx, ctx.attrs.deps))++ # Generate R.jar for autodeps support if we have resources+ if res and resource_info.text_symbols:+ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]+ dummy_r_dot_java_info = get_dummy_r_dot_java(+ ctx,+ android_toolchain.merge_android_resources[RunInfo],+ [resource_info],+ )+ android_resource_r_dot_info = AndroidResourceRDotInfo(+ dummy_r_dot_java = dummy_r_dot_java_info.library_output.abi,+ )+ providers.append(android_resource_r_dot_info)++ providers.append(DefaultInfo(default_output = default_output, sub_targets = sub_targets))+ compiling_deps = derive_compiling_deps_wrapper(ctx.actions, None, ctx.attrs.deps)+ providers.append(+ get_global_code_info(+ ctx,+ ctx.attrs.deps,+ ctx.attrs.deps,+ None,+ compiling_deps,+ [compiling_deps] if compiling_deps else [],+ ctx.attrs._java_toolchain[JavaToolchainInfo].global_code_config,+ )+ )++ return providers++def aapt2_compile(+ ctx: AnalysisContext, resources_dir: Artifact, android_toolchain: AndroidToolchainInfo, skip_crunch_pngs: bool = False, identifier: [str, None] = None+) -> Artifact:+ aapt2_command = [cmd_args(android_toolchain.aapt2)]+ aapt2_command.append("compile")+ aapt2_command.append("--legacy")+ if skip_crunch_pngs:+ aapt2_command.append("--no-crunch")+ aapt2_command.extend(["--dir", resources_dir])+ aapt2_output = ctx.actions.declare_output(+ "{}_resources.flata".format(identifier) if identifier else "resources.flata",+ has_content_based_path = True,+ )+ aapt2_command.extend(["-o", aapt2_output.as_output()])++ ctx.actions.run(cmd_args(aapt2_command), category = "aapt2_compile", identifier = identifier, allow_cache_upload = True)++ return aapt2_output++def _get_package(ctx: AnalysisContext, package: [str, None], manifest: Artifact | None) -> Artifact:+ if package:+ return ctx.actions.write(JAVA_PACKAGE_FILENAME, package, has_content_based_path = True)+ else:+ expect(manifest != None, "if package is not declared then a manifest must be")+ return extract_package_from_manifest(ctx, manifest)++def extract_package_from_manifest(ctx: AnalysisContext, manifest: Artifact) -> Artifact:+ r_dot_java_package = ctx.actions.declare_output(JAVA_PACKAGE_FILENAME, has_content_based_path = True)+ extract_package_cmd = cmd_args(+ ctx.attrs._android_toolchain[AndroidToolchainInfo].manifest_utils[RunInfo],+ "--manifest-path",+ manifest,+ "--package-output",+ r_dot_java_package.as_output(),+ )++ ctx.actions.run(extract_package_cmd, category = "android_extract_package")++ return r_dot_java_package++def get_text_symbols(ctx: AnalysisContext, res: Artifact, deps: list[Dependency], identifier: [str, None] = None):+ mini_aapt_cmd = cmd_args(ctx.attrs._android_toolchain[AndroidToolchainInfo].mini_aapt[RunInfo])++ mini_aapt_cmd.add(["--resource-paths", res])++ dep_symbols = _get_dep_symbols(deps)+ dep_symbol_paths_file = argfile(+ actions = ctx.actions,+ name = "{}_dep_symbol_paths_file".format(identifier) if identifier else "dep_symbol_paths_file",+ args = dep_symbols,+ has_content_based_path = True,+ )++ mini_aapt_cmd.add(["--dep-symbol-paths", dep_symbol_paths_file])++ text_symbols = ctx.actions.declare_output("{}_R.txt".format(identifier) if identifier else "R.txt", has_content_based_path = True)+ mini_aapt_cmd.add(["--output-path", text_symbols.as_output()])++ ctx.actions.run(mini_aapt_cmd, category = "mini_aapt", identifier = identifier)++ return text_symbols++def _get_dep_symbols(deps: list[Dependency]) -> list[Artifact]:+ dep_symbols = []+ for dep in deps:+ android_resource_info = dep.get(AndroidResourceInfo)+ exported_android_resource_info = dep.get(ExportedAndroidResourceInfo)+ expect(+ android_resource_info != None or exported_android_resource_info != None,+ "Dependencies of `android_resource` rules should be `android_resource`s or `android_library`s ({})",+ dep,+ )+ if android_resource_info and android_resource_info.text_symbols:+ dep_symbols.append(android_resource_info.text_symbols)+ if exported_android_resource_info:+ dep_symbols += [resource_info.text_symbols for resource_info in exported_android_resource_info.resource_infos if resource_info.text_symbols]++ return dedupe(dep_symbols)
@@ -0,0 +1,83 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++AndroidPlatformInfo = provider(+ fields = {+ "name": provider_field(typing.Any, default = None),+ }+)++AidlToolchainInfo = provider(+ fields = {+ "aidl": provider_field(typing.Any, default = None),+ "framework_aidl_file": provider_field(typing.Any, default = None),+ }+)++AndroidToolchainInfo = provider(+ fields = {+ "aapt2": provider_field(typing.Any, default = None),+ "aapt2_filter_resources": provider_field(typing.Any, default = None),+ "aar_builder": provider_field(typing.Any, default = None),+ "adb": provider_field(typing.Any, default = None),+ "android_bootclasspath": provider_field(typing.Any, default = None),+ "android_bootclasspath_snapshots": provider_field(typing.Any, default = []),+ "android_error_handler": provider_field(typing.Any, default = None),+ "android_jar": provider_field(typing.Any, default = None),+ "android_optional_jars": provider_field(typing.Any, default = None),+ "apk_builder": provider_field(typing.Any, default = None),+ "apk_module_graph": provider_field(typing.Any, default = None),+ "app_without_resources_stub": provider_field(typing.Any, default = None),+ "build_info_generator": provider_field(typing.Any, default = None),+ "bundle_apks_builder": provider_field(typing.Any, default = None),+ "bundle_builder": provider_field(typing.Any, default = None),+ "collect_perfetto": provider_field(typing.Any, default = None),+ "combine_native_library_dirs": provider_field(typing.Any, default = None),+ "consolidate_class_names": provider_field(typing.Any, default = None),+ "copy_string_resources": provider_field(typing.Any, default = None),+ "cross_module_native_deps_check": provider_field(typing.Any, default = None),+ "d8_command": provider_field(typing.Any, default = None),+ "duplicate_class_checker": provider_field(typing.Any, default = None),+ "exo_resources_rewriter": provider_field(typing.Any, default = None),+ "filter_dex_class_names": provider_field(typing.Any, default = None),+ "filter_prebuilt_native_library_dir": provider_field(typing.Any, default = None),+ "filter_resources": provider_field(typing.Any, default = None),+ # @oss-disable[end= ]: "gatorade_mergemap_tool": provider_field(typing.Any, default = None),+ "generate_build_config": provider_field(typing.Any, default = None),+ "generate_manifest": provider_field(typing.Any, default = None),+ "installer": provider_field(typing.Any, default = None),+ "instrumentation_test_can_run_locally": provider_field(typing.Any, default = None),+ "instrumentation_test_runner_classpath": provider_field(typing.Any, default = None),+ "instrumentation_test_runner_main_class": provider_field(typing.Any, default = None),+ "jar_splitter_command": provider_field(typing.Any, default = None),+ "jdk_system_image": provider_field(typing.Any, default = None),+ "jni_onload_check": provider_field(typing.Any, default = None),+ "manifest_utils": provider_field(typing.Any, default = None),+ "merge_android_resource_sources": provider_field(typing.Any, default = None),+ "merge_android_resources": provider_field(typing.Any, default = None),+ "merge_assets": provider_field(typing.Any, default = None),+ "mergemap_tool": provider_field(typing.Any, default = None),+ "mini_aapt": provider_field(typing.Any, default = None),+ "multi_dex_command": provider_field(typing.Any, default = None),+ "native_libs_as_assets_metadata": provider_field(typing.Any, default = None),+ "optimized_proguard_config": provider_field(typing.Any, default = None),+ "p7zip": provider_field(typing.Any, default = None),+ "package_meta_inf_version_files": provider_field(typing.Any, default = None),+ "package_strings_as_assets": provider_field(typing.Any, default = None),+ "proguard_config": provider_field(typing.Any, default = None),+ "proguard_jar": provider_field(typing.Any, default = None),+ "r_dot_java_weight_factor": provider_field(typing.Any, default = None),+ "replace_application_id_placeholders": provider_field(typing.Any, default = None),+ "secondary_dex_compression_command": provider_field(typing.Any, default = None),+ "secondary_dex_weight_limit": provider_field(typing.Any, default = None),+ "sort_pre_dexed_files": provider_field(typing.Any),+ "target_stats_tools": provider_field(typing.Any, default = None),+ "unpack_aar": provider_field(typing.Any, default = None),+ "zipalign": provider_field(typing.Any, default = None),+ },+)
@@ -0,0 +1,251 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:genrule.bzl", "process_genrule")+load("@prelude//android:android_apk.bzl", "get_install_info")+load(+ "@prelude//android:android_providers.bzl",+ "AndroidAabInfo",+ "AndroidApkInfo",+ "AndroidApkUnderTestInfo",+ "AndroidDerivedApkInfo",+ "AndroidPreprocessedJavaClassesInfo",+ "KeystoreInfo",+)+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//android:bundletool_util.bzl", "derive_universal_apk")+load("@prelude//android:native_build_commands.bzl", "GATORADE_PHASE_SUBTARGETS")+load("@prelude//java:class_to_srcs.bzl", "JavaClassToSourceMapInfo")+load("@prelude//utils:expect.bzl", "expect")++# Native-library debug sub-targets forwarded through the apk_genrule wrapper only if present on the+# wrapped android_apk/android_aab. These exist only in certain configurations (e.g. relinked_libs+# and native_merge_debug require the relinker or native merging). Always-present sub-targets like+# native_libs, linker_commands and native_build_commands are forwarded in the required set below.+_OPTIONAL_NATIVE_LIB_SUBTARGETS = [+ "gatorade_phase_evidence",+ "native_merge_debug",+ "relinked_libs",+ "relinked_libs_manifest",+ "relinker_extra_outputs",+ "unrelinked_libs",+]++def _forward_optional_native_lib_subtargets(input_subtargets: dict) -> dict:+ return {name: [input_subtargets[name][DefaultInfo]] for name in _OPTIONAL_NATIVE_LIB_SUBTARGETS if name in input_subtargets}++# The top-level Gatorade-phase sub-targets (`TARGET[early_gatorade]` etc.) are always present on the+# wrapped android_apk/android_aab, so forward them in the required set at every wrapper site.+def _forward_gatorade_phase_subtargets(input_subtargets: dict) -> dict:+ return {name: [input_subtargets[name][DefaultInfo]] for name in GATORADE_PHASE_SUBTARGETS}++def apk_genrule_impl(ctx: AnalysisContext) -> list[Provider]:+ expect((ctx.attrs.apk == None) != (ctx.attrs.aab == None), "Exactly one of 'apk' and 'aab' must be specified")++ input_android_apk_under_test_info = None+ input_android_apk_subtargets = None+ input_android_apk_template_placeholder_info = None+ input_android_aab_subtargets = None+ input_preprocessed_java_classes_info = None+ if ctx.attrs.apk != None:+ # TODO(T104150125) The underlying APK should not have exopackage enabled+ input_android_apk_info = ctx.attrs.apk[AndroidApkInfo]+ expect(input_android_apk_info != None, "'apk' attribute must be an Android APK!")+ input_apk = input_android_apk_info.apk+ input_manifest = input_android_apk_info.manifest+ input_materialized_artifacts = input_android_apk_info.materialized_artifacts+ input_unstripped_shared_libraries = input_android_apk_info.unstripped_shared_libraries+ input_android_apk_under_test_info = ctx.attrs.apk[AndroidApkUnderTestInfo]+ input_android_apk_subtargets = ctx.attrs.apk[DefaultInfo].sub_targets+ input_android_apk_template_placeholder_info = ctx.attrs.apk[TemplatePlaceholderInfo].keyed_variables+ if AndroidPreprocessedJavaClassesInfo in ctx.attrs.apk:+ input_preprocessed_java_classes_info = ctx.attrs.apk[AndroidPreprocessedJavaClassesInfo]++ env_vars = {+ "APK": cmd_args(input_apk),+ }+ else:+ input_android_aab_info = ctx.attrs.aab[AndroidAabInfo]+ expect(input_android_aab_info != None, "'aab' attribute must be an Android Bundle!")++ # It's not an APK, but buck1 does this so we do it too for compatibility+ input_apk = input_android_aab_info.aab+ input_manifest = input_android_aab_info.manifest+ input_materialized_artifacts = input_android_aab_info.materialized_artifacts+ input_android_aab_subtargets = ctx.attrs.aab[DefaultInfo].sub_targets+ input_unstripped_shared_libraries = input_android_aab_info.unstripped_shared_libraries+ if AndroidPreprocessedJavaClassesInfo in ctx.attrs.aab:+ input_preprocessed_java_classes_info = ctx.attrs.aab[AndroidPreprocessedJavaClassesInfo]++ env_vars = {+ "AAB": cmd_args(input_apk),+ }++ genrule_providers = process_genrule(+ ctx,+ ctx.attrs.out,+ ctx.attrs.outs,+ env_vars,+ other_outputs = input_materialized_artifacts,+ genrule_error_handler = ctx.attrs._android_toolchain[AndroidToolchainInfo].android_error_handler,+ )++ genrule_default_info = filter(lambda x: isinstance(x, DefaultInfo), genrule_providers)++ expect(+ len(genrule_default_info) == 1,+ "Expecting a single DefaultInfo, but got {}",+ genrule_default_info,+ )++ genrule_default_output = genrule_default_info[0].default_outputs[0]+ genrule_default_output_is_aab = genrule_default_output.extension == ".aab"+ genrule_default_output_is_apk = genrule_default_output.extension == ".apk"++ expect(+ genrule_default_output_is_aab or genrule_default_output_is_apk,+ "apk_genrule must output a '.apk' or '.aab' file, but got {}",+ genrule_default_info,+ )++ if ctx.attrs.aab:+ if genrule_default_output_is_aab:+ output_aab_info = AndroidAabInfo(+ aab = genrule_default_output,+ manifest = input_manifest,+ materialized_artifacts = input_materialized_artifacts,+ unstripped_shared_libraries = input_unstripped_shared_libraries,+ )+ output_apk = None+ else:+ output_aab_info = None+ output_apk = genrule_default_output++ if ctx.attrs.use_derived_apk:+ expect(genrule_default_output_is_aab, "Default genrule output must end in '.aab' if use_derived_apk is True.")++ output_apk = derive_universal_apk(+ ctx = ctx,+ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo],+ app_bundle = genrule_default_output,+ keystore = ctx.attrs.keystore[KeystoreInfo] if ctx.attrs.keystore else None,+ )+ default_providers = [+ DefaultInfo(+ default_output = output_apk,+ other_outputs = input_materialized_artifacts + genrule_default_info[0].other_outputs,+ sub_targets = {+ "aab": [+ DefaultInfo(+ default_outputs = [genrule_default_output],+ )+ ],+ "linker_argsfiles": [input_android_aab_subtargets["linker_argsfiles"][DefaultInfo]],+ "linker_commands": [input_android_aab_subtargets["linker_commands"][DefaultInfo]],+ "native_build_commands": [input_android_aab_subtargets["native_build_commands"][DefaultInfo]],+ "native_libs": [input_android_aab_subtargets["native_libs"][DefaultInfo]],+ "unstripped_native_libraries": [input_android_aab_subtargets["unstripped_native_libraries"][DefaultInfo]],+ "unstripped_native_libraries_files": [input_android_aab_subtargets["unstripped_native_libraries_files"][DefaultInfo]],+ "unstripped_native_libraries_json": [input_android_aab_subtargets["unstripped_native_libraries_json"][DefaultInfo]],+ }+ | _forward_gatorade_phase_subtargets(input_android_aab_subtargets)+ | _forward_optional_native_lib_subtargets(input_android_aab_subtargets),+ ),+ AndroidDerivedApkInfo(+ apk = output_apk,+ ),+ ] + filter(lambda x: not isinstance(x, DefaultInfo), genrule_providers)+ else:+ sub_targets = {k: [v[DefaultInfo]] for k, v in genrule_default_info[0].sub_targets.items()}+ sub_targets.update(+ {+ "linker_argsfiles": [input_android_aab_subtargets["linker_argsfiles"][DefaultInfo]],+ "linker_commands": [input_android_aab_subtargets["linker_commands"][DefaultInfo]],+ "native_build_commands": [input_android_aab_subtargets["native_build_commands"][DefaultInfo]],+ "native_libs": [input_android_aab_subtargets["native_libs"][DefaultInfo]],+ "unstripped_native_libraries": [input_android_aab_subtargets["unstripped_native_libraries"][DefaultInfo]],+ "unstripped_native_libraries_files": [input_android_aab_subtargets["unstripped_native_libraries_files"][DefaultInfo]],+ "unstripped_native_libraries_json": [input_android_aab_subtargets["unstripped_native_libraries_json"][DefaultInfo]],+ }+ | _forward_gatorade_phase_subtargets(input_android_aab_subtargets)+ | _forward_optional_native_lib_subtargets(input_android_aab_subtargets)+ )+ default_providers = [+ DefaultInfo(+ default_output = genrule_default_output,+ other_outputs = genrule_default_info[0].other_outputs,+ sub_targets = sub_targets,+ ),+ ] + filter(lambda x: not isinstance(x, DefaultInfo), genrule_providers)++ else:+ sub_targets = {k: [v[DefaultInfo]] for k, v in genrule_default_info[0].sub_targets.items()}+ sub_targets.update(+ {+ "classpath": [input_android_apk_subtargets["classpath"][DefaultInfo]],+ "classpath_targets": [input_android_apk_subtargets["classpath_targets"][DefaultInfo]],+ "linker_argsfiles": [input_android_apk_subtargets["linker_argsfiles"][DefaultInfo]],+ "linker_commands": [input_android_apk_subtargets["linker_commands"][DefaultInfo]],+ "manifest": [input_android_apk_subtargets["manifest"][DefaultInfo]],+ "native_build_commands": [input_android_apk_subtargets["native_build_commands"][DefaultInfo]],+ "native_libs": [input_android_apk_subtargets["native_libs"][DefaultInfo]],+ "unstripped_native_libraries": [input_android_apk_subtargets["unstripped_native_libraries"][DefaultInfo]],+ "unstripped_native_libraries_files": [input_android_apk_subtargets["unstripped_native_libraries_files"][DefaultInfo]],+ "unstripped_native_libraries_json": [input_android_apk_subtargets["unstripped_native_libraries_json"][DefaultInfo]],+ }+ | _forward_gatorade_phase_subtargets(input_android_apk_subtargets)+ | _forward_optional_native_lib_subtargets(input_android_apk_subtargets)+ )+ expect(+ len(filter(lambda x: isinstance(x, TemplatePlaceholderInfo), genrule_providers)) == 0,+ "TemplatePlaceholderInfo from genrule_providers needs to be merged",+ )+ templace_placeholder_info = TemplatePlaceholderInfo(+ keyed_variables = {+ "classpath": input_android_apk_template_placeholder_info["classpath"],+ "classpath_including_targets_with_no_output": input_android_apk_template_placeholder_info["classpath_including_targets_with_no_output"],+ },+ )+ expect(genrule_default_output_is_apk, "apk_genrule output must end in '.apk'")+ output_apk = genrule_default_output+ output_aab_info = None+ default_providers = [+ DefaultInfo(+ default_output = output_apk,+ other_outputs = genrule_default_info[0].other_outputs,+ sub_targets = sub_targets,+ ),+ templace_placeholder_info,+ ] + filter(lambda x: not isinstance(x, DefaultInfo), genrule_providers)++ class_to_src_map = [ctx.attrs.apk[JavaClassToSourceMapInfo]] if (ctx.attrs.apk and JavaClassToSourceMapInfo in ctx.attrs.apk) else []++ if output_apk:+ apk_providers = [+ AndroidApkInfo(+ apk = output_apk,+ manifest = input_manifest,+ materialized_artifacts = input_materialized_artifacts,+ unstripped_shared_libraries = input_unstripped_shared_libraries,+ ),+ get_install_info(+ ctx,+ output_apk = output_apk,+ manifest = input_manifest,+ exopackage_info = None,+ ),+ ]+ else:+ apk_providers = []++ aab_providers = filter(None, [output_aab_info])+ apk_under_test_providers = filter(None, [input_android_apk_under_test_info])++ preprocessed_java_classes_providers = filter(None, [input_preprocessed_java_classes_info])++ return default_providers + apk_providers + aab_providers + apk_under_test_providers + preprocessed_java_classes_providers + class_to_src_map
@@ -0,0 +1,15 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++def is_build_only_native_code():+ return select(+ {+ "DEFAULT": False,+ "prelude//android/constraints:maybe_build_only_native_code[build_only_native_code]": True,+ },+ )
@@ -0,0 +1,41 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//android:android_providers.bzl", "KeystoreInfo") # @unused used as type+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")++def derive_universal_apk(ctx: AnalysisContext, android_toolchain: AndroidToolchainInfo, app_bundle: Artifact, keystore: [KeystoreInfo, None]) -> Artifact:+ output_apk = ctx.actions.declare_output("universal.apk", has_content_based_path = False)++ bundle_apks_builder_args = cmd_args([+ android_toolchain.bundle_apks_builder[RunInfo],+ "--input-bundle",+ app_bundle,+ "--p7zip",+ android_toolchain.p7zip,+ "--aapt2",+ android_toolchain.aapt2,+ "--zipalign",+ android_toolchain.zipalign[RunInfo],+ "--output-apk",+ output_apk.as_output(),+ ])++ if keystore:+ bundle_apks_builder_args.add(+ cmd_args([+ "--keystore",+ keystore.store,+ "--keystore-properties",+ keystore.properties,+ ])+ )++ ctx.actions.run(bundle_apks_builder_args, category = "bundle_build", identifier = "build_universal_apk")++ return output_apk
@@ -0,0 +1,204 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//android:cpu_filters.bzl", "ALL_CPU_FILTERS", "CPU_FILTER_FOR_DEFAULT_PLATFORM", "CPU_FILTER_FOR_PRIMARY_PLATFORM")+load("@prelude//android:min_sdk_version.bzl", "get_min_sdk_version_constraint_value_name", "get_min_sdk_version_range")+load("@prelude//cfg/modifier:name.bzl", "cfg_name")+load("@prelude//utils:expect.bzl", "expect")++# Android binaries (APKs or AABs) can be built for one or more different platforms. buck2 supports+# building Android binaries for arm32, arm64, x86, and x86_64. The platform(s) that we are building+# for are specified by the `cpu_filters` attribute on the binary rule.++# In order to build our native libraries for the correct platform(s), we do a (split) transition+# (https://www.internalfb.com/intern/staticdocs/buck2/docs/rule_authors/configuration_transitions)+# on the `deps` of the binary, and have each of the resulting configured sub-graphs be responsible+# for building the native libraries for one of the specified platforms.++# We always create an "arm64" configured sub-graph and use it to build the non-native libraries (so+# that we get cache hits for the non-native libraries even if we're building for different+# platforms). We only use the "arm64" native libraries if it is one of the specified platforms. We+# "throw away" the non-native libraries for all other configured sub-graphs.++_REFS = {+ "arm64": "config//cpu/constraints:arm64",+ "armv7": "config//cpu/constraints:arm32",+ "build_only_native_code": "prelude//android/constraints:maybe_build_only_native_code[build_only_native_code]",+ "building_android_binary": "prelude//os:building_android_binary",+ "cpu": "config//cpu/constraints:cpu",+ "maybe_build_only_native_code": "prelude//android/constraints:maybe_build_only_native_code",+ "maybe_building_android_binary": "prelude//os:maybe_building_android_binary",+ "min_sdk_version": "prelude//android/constraints:min_sdk_version",+ "x86": "config//cpu/constraints:x86_32",+ "x86_64": "config//cpu/constraints:x86_64",+}++_DEFAULT_PLATFORM = read_root_config("android", "primary_platform_for_build", None)+if _DEFAULT_PLATFORM:+ _REFS["default_platform"] = _DEFAULT_PLATFORM++for min_sdk in get_min_sdk_version_range():+ constraint_value_name = get_min_sdk_version_constraint_value_name(min_sdk)+ _REFS[constraint_value_name] = "prelude//android/constraints:{}".format(constraint_value_name)++def _cpu_split_transition_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> dict[str, PlatformInfo]:+ cpu_filters = attrs.cpu_filters or ALL_CPU_FILTERS+ if attrs._is_force_single_cpu:+ cpu_filters = [CPU_FILTER_FOR_PRIMARY_PLATFORM]+ elif attrs._is_force_single_default_cpu:+ cpu_filters = ["default"]++ return _cpu_split_transition(+ platform,+ refs,+ cpu_filters,+ attrs.min_sdk_version,+ )++def _cpu_split_transition(platform: PlatformInfo, refs: struct, cpu_filters: list[str], min_sdk_version: [int, None]) -> dict[str, PlatformInfo]:+ cpu = refs.cpu+ x86 = refs.x86[ConstraintValueInfo]+ x86_64 = refs.x86_64[ConstraintValueInfo]+ armv7 = refs.armv7[ConstraintValueInfo]+ arm64 = refs.arm64[ConstraintValueInfo]++ if len(cpu_filters) == 1 and cpu_filters[0] == "default":+ default_platform = getattr(refs, "default_platform", None)+ expect(+ default_platform != None,+ "Cannot specify 'is_force_single_default_cpu' but not specify a default platform!",+ )++ default = default_platform[PlatformInfo]++ # Use `cfg_name` function from modifier resolution so that we get the same cfg as default cfg+ # of android libraries.+ default = PlatformInfo(+ label = cfg_name(default.configuration),+ configuration = default.configuration,+ )+ return {CPU_FILTER_FOR_DEFAULT_PLATFORM: default}++ expect(CPU_FILTER_FOR_PRIMARY_PLATFORM == "arm64")+ cpu_name_to_cpu_constraint = {"arm64": arm64}+ for cpu_filter in cpu_filters:+ if cpu_filter == "x86":+ cpu_name_to_cpu_constraint["x86"] = x86+ elif cpu_filter == "armv7":+ cpu_name_to_cpu_constraint["armv7"] = armv7+ elif cpu_filter == "x86_64":+ cpu_name_to_cpu_constraint["x86_64"] = x86_64+ elif cpu_filter == "arm64":+ # Always included as the primary platform+ pass+ else:+ fail("Unexpected cpu_filter: {}".format(cpu_filter))++ base_constraints = {+ constraint_setting_label: constraint_setting_value+ for (constraint_setting_label, constraint_setting_value) in platform.configuration.constraints.items()+ if constraint_setting_label != cpu[ConstraintSettingInfo].label+ and constraint_setting_label != refs.maybe_build_only_native_code[ConstraintSettingInfo].label+ }++ base_constraints[refs.maybe_building_android_binary[ConstraintSettingInfo].label] = refs.building_android_binary[ConstraintValueInfo]++ if min_sdk_version:+ base_constraints[refs.min_sdk_version[ConstraintSettingInfo].label] = _get_min_sdk_constraint_value(min_sdk_version, refs)++ new_configs = {}+ for platform_name, cpu_constraint in cpu_name_to_cpu_constraint.items():+ updated_constraints = dict(base_constraints)+ updated_constraints[refs.cpu[ConstraintSettingInfo].label] = cpu_constraint+ if len(new_configs) > 0:+ updated_constraints[refs.maybe_build_only_native_code[ConstraintSettingInfo].label] = refs.build_only_native_code[ConstraintValueInfo]++ cfg_info = ConfigurationInfo(+ constraints = updated_constraints,+ values = platform.configuration.values,+ )++ # Use `cfg_name` function from modifier resolution so that we get the same cfg as default cfg+ # of android libraries.+ new_configs[platform_name] = PlatformInfo(+ label = cfg_name(cfg_info),+ configuration = cfg_info,+ )++ return new_configs++def _cpu_transition_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> PlatformInfo:+ return _cpu_split_transition_impl(platform, refs, attrs).values()[0]++cpu_split_transition = transition(+ impl = _cpu_split_transition_impl,+ refs = _REFS,+ attrs = [+ "cpu_filters",+ "min_sdk_version",+ "_is_force_single_cpu",+ "_is_force_single_default_cpu",+ ],+ split = True,+)++# If our deps have been split-transitioned by CPU then we are already analyzing the dependency+# graph using the resulting configurations. If there are any other attributes on the same target+# that also need to analyze the dependency graph, then we want to use one of the configurations+# from the split transition so that we don't end up analyzing the graph again using a different+# configuration. This rule just picks the first configuration from the split-transition.+#+# This is used for the `manifest` attribute of `android_binary`.+cpu_transition = transition(+ impl = _cpu_transition_impl,+ refs = _REFS,+ attrs = [+ "cpu_filters",+ "min_sdk_version",+ "_is_force_single_cpu",+ "_is_force_single_default_cpu",+ ],+)++FORCE_SINGLE_CPU = read_root_config("buck2", "android_force_single_cpu") in ("True", "true")+FORCE_SINGLE_DEFAULT_CPU = read_root_config("buck2", "android_force_single_default_cpu") in ("True", "true")++# Common attributes required by any rule that uses cpu_transition or cpu_split_transition.+CPU_TRANSITION_ATTRS = {+ "_is_force_single_cpu": attrs.default_only(attrs.bool(default = FORCE_SINGLE_CPU)),+ "_is_force_single_default_cpu": attrs.default_only(attrs.bool(default = FORCE_SINGLE_DEFAULT_CPU)),+}++def get_deps_by_platform(ctx: AnalysisContext) -> dict[str, list[Dependency]]:+ deps_by_platform = {}+ for dep_dict in ctx.attrs.deps:+ for platform, dep in dep_dict.items():+ deps = deps_by_platform.get(platform, [])+ deps.append(dep)+ deps_by_platform[platform] = deps++ return deps_by_platform++def _get_min_sdk_constraint_value(min_sdk_version: int, refs: struct) -> ConstraintValueInfo:+ constraint_name = get_min_sdk_version_constraint_value_name(min_sdk_version)+ constraint = getattr(refs, constraint_name, None)+ if not constraint:+ fail("Unsupported min_sdk_version {}, please report!".format(min_sdk_version))++ return constraint[ConstraintValueInfo]++def _is_building_android_binary() -> Select:+ return select(+ {+ "DEFAULT": False,+ "prelude//os:building_android_binary": True,+ },+ )++def is_building_android_binary_attr() -> Attr:+ return attrs.default_only(attrs.bool(default = _is_building_android_binary()))
@@ -0,0 +1,56 @@+load("@prelude//android:min_sdk_version.bzl", "get_min_sdk_version_constraint_value_name", "get_min_sdk_version_range")+load("@prelude//configurations:constraint_alias.bzl", "constraint_with_aliases")+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("build_infra")++source_listing()++prelude = native # Avoid warnings and auto-formatters++constraint_with_aliases(+ name = "maybe_build_only_native_code",+ aliases = {+ "build_only_native_code": "build_only_native_code",+ },+ default = "unspecified",+ values = [+ "build_only_native_code",+ "unspecified",+ ],+ visibility = ["PUBLIC"],+)++constraint_with_aliases(+ name = "maybe_merge_native_libraries",+ aliases = {+ "merge_native_libraries": "merge_native_libraries",+ },+ default = "unspecified",+ values = [+ "merge_native_libraries",+ "unspecified",+ ],+ visibility = ["PUBLIC"],+)++prelude.filegroup(+ name = "files",+ srcs = glob(+ ["**"],+ ),+ visibility = ["PUBLIC"],+)++prelude.constraint_setting(+ name = "min_sdk_version",+ visibility = ["PUBLIC"],+)++[+ prelude.constraint_value(+ name = get_min_sdk_version_constraint_value_name(min_sdk),+ constraint_setting = ":min_sdk_version",+ )+ for min_sdk in get_min_sdk_version_range()+]
@@ -0,0 +1,25 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++CPU_FILTER_TO_ABI_DIRECTORY = {+ "arm64": "arm64-v8a",+ "armv7": "armeabi-v7a",+ "x86": "x86",+ "x86_64": "x86_64",+}++ALL_CPU_FILTERS = CPU_FILTER_TO_ABI_DIRECTORY.keys()++CPU_FILTER_FOR_DEFAULT_PLATFORM = "arm64"++# The "primary platform" is the one that we use for all+# the non-native targets. We keep this consistent regardless+# of which cpus the native libraries are built for so that+# we get cache hits for the non-native targets across all+# possible cpu filters.+CPU_FILTER_FOR_PRIMARY_PLATFORM = "arm64"
@@ -0,0 +1,975 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load("@prelude//android:android_providers.bzl", "DexFilesInfo", "ExopackageDexInfo")+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//android:voltron.bzl", "ROOT_MODULE", "get_apk_module_graph_info", "get_root_module_only_apk_module_graph_info", "is_root_module")+load("@prelude//java:dex.bzl", "DexLibraryInfo", "get_dex_produced_from_java_library")+load("@prelude//java:dex_toolchain.bzl", "DexToolchainInfo")+load("@prelude//java:java_library.bzl", "compile_to_jar")+load("@prelude//utils:argfile.bzl", "argfile", "at_argfile")+load("@prelude//utils:expect.bzl", "expect")+load("@prelude//utils:utils.bzl", "flatten")++# Android builds use a tool called `d8` to compile Java bytecode is DEX (Dalvik EXecutable)+# bytecode that runs on Android devices. Our Android builds have two distinct ways of+# doing that:+# 1) With pre-dexing enabled (this is the most common case for debug builds). That means that+# d8 runs on every individual .jar file (to produce a .jar.dex file), and then at the APK+# level we run d8 again to combine all the individual .jar.dex files.+# 2) With pre-dexing disabled (this is the case if it is explicitly disabled, we are running+# proguard, or we preprocess the java classes at the APK level). This means that we run+# d8 at the APK level on all the .jar files.+#+# The .dex files that we package into the APK consist of a single classes.dex "primary DEX"+# file, and N secondary DEX files. The classes that are put into the primary DEX are those+# that are required at startup, and are specified via `primary_dex_patterns` (classes which+# match one of those patterns are put into the primary DEX).+#+# The primary DEX is always stored in the root directory of the APK as `classes.dex`.+#+# We have 4 different ways of storing our secondary DEX files, which are specified via the+# `dex_compression` attribute:+# 1) `raw` compression. This means that we create `classes2.dex`, `classes3.dex`, ...,+# `classesN.dex` and store each of them in the root directory of the APK.+# 2) `raw_subdir` compression. We store each secondary DEX file uncompressed at+# `assets/secondary-program-dex-jars/secondary-I.dex`. This is like `raw` in+# the sense that secondary DEX files are included in the APK without+# additional compression. However, those raw DEXes are written to the+# secondary dex subdirectory instead of to the root directory of the APK.+# 3) `jar` compression. For each secondary DEX file, we put a `classes.dex` entry into a+# JAR file, and store it as an asset at `assets/secondary-program-dex-jars/secondary-I.dex.jar`+# 4) `xzs` compression. We do the same as `jar` compression, then concatenate all the jars+# together and do `xz` compression on the result to produce a single+# `assets/secondary-program-dex-jars/secondary.dex.jar.xzs`.+#+# For all compression types, we also package a `assets/secondary-program-dex-jars/metadata.txt`,+# which has an entry for each secondary DEX file:+# <secondary DEX file name> <sha1 hash of secondary DEX> <canary class name>+#+# A "canary class" is a Java class that we add to every secondary DEX. It is a known class that+# can be used for DEX verification when loading the DEX on a device.+#+# For compression types other than raw, we also include a metadata file per secondary DEX, which+# consists of a single line of the form:+# jar:<size of secondary dex jar (in bytes)> dex:<size of uncompressed dex file (in bytes)>+#+# If an APK has Voltron modules, then we produce a separate group of secondary DEX files for each+# module, and we put them into `assets/<module_name>` instead of `assets/secondary-program-dex-jars`.+# We produce a `metadata.txt` file for each Voltron module.++_DEX_MERGE_OPTIONS = ["--no-desugar", "--no-optimize"]++SplitDexMergeConfig = record(+ dex_compression = str,+ primary_dex_patterns = list[str],+ secondary_dex_weight_limit_bytes = int,+)++def _get_dex_compression(ctx: AnalysisContext) -> str:+ is_exopackage_enabled_for_secondary_dexes = _is_exopackage_enabled_for_secondary_dex(ctx)+ default_dex_compression = "jar" if is_exopackage_enabled_for_secondary_dexes else "raw"+ dex_compression = getattr(ctx.attrs, "dex_compression", None) or default_dex_compression+ expect(+ dex_compression in ["raw", "raw_subdir", "jar", "xzs"],+ "Only 'raw', 'raw_subdir', 'jar' and 'xzs' dex compression are supported at this time!",+ )++ return dex_compression++def get_split_dex_merge_config(ctx: AnalysisContext, android_toolchain: AndroidToolchainInfo) -> SplitDexMergeConfig:+ secondary_dex_weight_limit = getattr(ctx.attrs, "secondary_dex_weight_limit", None) or android_toolchain.secondary_dex_weight_limit+ return SplitDexMergeConfig(+ dex_compression = _get_dex_compression(ctx),+ primary_dex_patterns = ctx.attrs.primary_dex_patterns,+ secondary_dex_weight_limit_bytes = secondary_dex_weight_limit,+ )++def get_single_primary_dex(+ ctx: AnalysisContext,+ android_toolchain: AndroidToolchainInfo,+ java_library_jars: list[Artifact],+ is_optimized: bool = False,+ classpath_jars: list[Artifact] = [],+) -> DexFilesInfo:+ expect(+ not _is_exopackage_enabled_for_secondary_dex(ctx),+ "It doesn't make sense to enable secondary dex exopackage for single dex builds!",+ )+ d8_cmd = cmd_args(android_toolchain.d8_command[RunInfo])++ output_dex_file = ctx.actions.declare_output("classes.dex", has_content_based_path = False)+ d8_cmd.add(["--output-dex-file", output_dex_file.as_output()])++ jar_to_dex_file = argfile(actions = ctx.actions, name = "jar_to_dex_file.txt", args = java_library_jars)+ d8_cmd.add(["--files-to-dex-list", jar_to_dex_file])+ if classpath_jars:+ classpath_file = argfile(actions = ctx.actions, name = "classpath_jars.txt", args = classpath_jars)+ d8_cmd.add(["--classpath-files", classpath_file])++ d8_cmd.add(["--android-jar", android_toolchain.android_jar])+ if not is_optimized:+ d8_cmd.add("--no-optimize")++ ctx.actions.run(+ d8_cmd,+ category = "get_single_primary_dex",+ identifier = "{}:{}".format(ctx.label.package, ctx.label.name),+ allow_cache_upload = True,+ error_handler = android_toolchain.android_error_handler,+ )++ return DexFilesInfo(+ primary_dex = output_dex_file,+ root_module_bootstrap_dex_dirs = [],+ root_module_secondary_dex_dirs = [],+ non_root_module_secondary_dex_dirs = [],+ secondary_dex_exopackage_info = None,+ proguard_text_files_path = None,+ primary_dex_class_names = None,+ )++def get_multi_dex(+ ctx: AnalysisContext,+ android_toolchain: AndroidToolchainInfo,+ input_artifacts_to_owners: dict[Artifact, TargetLabel],+ primary_dex_patterns: list[str],+ proguard_configuration_output_file: Artifact | None = None,+ proguard_mapping_output_file: Artifact | None = None,+ is_optimized: bool = False,+ apk_module_graph_file: Artifact | None = None,+ enable_bootstrap_dexes = False,+ multidex_min_api: str | None = None,+ pre_dexed_inputs: bool = False,+ classpath_jars: list[Artifact] = [],+) -> DexFilesInfo:+ expect(+ not _is_exopackage_enabled_for_secondary_dex(ctx),+ "secondary dex exopackage can only be enabled on pre-dexed builds!",+ )+ expect(+ not pre_dexed_inputs or (multidex_min_api and int(multidex_min_api) > 21),+ "Pre-dexed native multidex inputs require multidex_min_api > 21",+ )+ expect(+ not pre_dexed_inputs or not primary_dex_patterns,+ "Pre-dexed native multidex inputs cannot honor primary_dex_patterns, because D8 rejects a main-dex list above min SDK 21",+ )+ primary_dex_file = ctx.actions.declare_output("classes.dex", has_content_based_path = False)+ primary_dex_class_names = ctx.actions.declare_output("primary_dex_class_names.txt", has_content_based_path = False)+ root_module_secondary_dex_output_dir = ctx.actions.declare_output("root_module_secondary_dex_output_dir", dir = True, has_content_based_path = False)+ secondary_dex_dir = ctx.actions.declare_output("secondary_dex_output_dir", dir = True, has_content_based_path = False)++ # dynamic actions are not valid with no input, but it's easier to use the same code regardless,+ # so just create an empty input.+ inputs = (+ [apk_module_graph_file]+ if apk_module_graph_file+ else [ctx.actions.write("empty_artifact_for_multi_dex_dynamic_action", [], has_content_based_path = False)]+ )+ outputs = [primary_dex_file, primary_dex_class_names, root_module_secondary_dex_output_dir, secondary_dex_dir]+ root_module_bootstrap_dex_output_dir = None+ if enable_bootstrap_dexes:+ root_module_bootstrap_dex_output_dir = ctx.actions.declare_output("root_module_bootstrap_dex_output_dir", dir = True, has_content_based_path = False)+ outputs.append(root_module_bootstrap_dex_output_dir)++ def do_multi_dex(ctx: AnalysisContext, artifacts, outputs):+ apk_module_graph_info = (+ get_apk_module_graph_info(ctx, apk_module_graph_file, artifacts) if apk_module_graph_file else get_root_module_only_apk_module_graph_info()+ )+ target_to_module_mapping_function = apk_module_graph_info.target_to_module_mapping_function+ module_to_inputs = {}+ for input_artifact, owner in input_artifacts_to_owners.items():+ module = target_to_module_mapping_function(str(owner))+ module_to_inputs.setdefault(module, []).append(input_artifact)++ secondary_dex_dir_srcs = {}+ all_inputs = flatten(module_to_inputs.values())+ all_inputs_list = argfile(actions = ctx.actions, name = "all_inputs_classpath.txt", args = all_inputs + classpath_jars)+ classpath_jars_list = argfile(actions = ctx.actions, name = "classpath_jars.txt", args = classpath_jars) if classpath_jars else None+ for module, module_inputs in module_to_inputs.items():+ multi_dex_cmd = cmd_args(android_toolchain.multi_dex_command[RunInfo])+ secondary_dex_compression_cmd = cmd_args(android_toolchain.secondary_dex_compression_command[RunInfo])++ uncompressed_secondary_dex_output_dir = ctx.actions.declare_output(+ "uncompressed_secondary_dex_output_dir_for_module_{}".format(module), dir = True, has_content_based_path = False+ )+ multi_dex_cmd.add("--secondary-dex-output-dir", uncompressed_secondary_dex_output_dir.as_output())+ secondary_dex_compression_cmd.add("--raw-secondary-dexes-dir", uncompressed_secondary_dex_output_dir)+ if is_root_module(module):+ primary_dex_patterns_file = ctx.actions.write("primary_dex_patterns", primary_dex_patterns, has_content_based_path = True)++ if pre_dexed_inputs:+ expect(+ not getattr(ctx.attrs, "minimize_primary_dex_size", False) and not enable_bootstrap_dexes,+ "Pre-dexed native multidex inputs do not support primary dex sculpting",+ )+ inputs_to_dex = module_inputs+ elif getattr(ctx.attrs, "minimize_primary_dex_size", False) or enable_bootstrap_dexes:+ primary_dex_inputs, inputs_to_dex = _get_primary_dex_and_secondary_dex_jars(+ ctx,+ module_inputs,+ input_artifacts_to_owners,+ primary_dex_patterns_file,+ proguard_configuration_output_file,+ proguard_mapping_output_file,+ android_toolchain,+ )++ primary_dex_input_file = argfile(actions = ctx.actions, name = "primary_dex_inputs_for_root_module.txt", args = primary_dex_inputs)+ multi_dex_cmd.add("--primary-dex-files-to-dex-list", primary_dex_input_file)+ multi_dex_cmd.add("--minimize-primary-dex")++ # Tells the multidex command to allow primary dex pattern matches to be spread across several dex files if needed+ if enable_bootstrap_dexes:+ multi_dex_cmd.add("--enable-bootstrap-dexes")+ multi_dex_cmd.add("--bootstrap-dex-output-dir", outputs[root_module_bootstrap_dex_output_dir].as_output())+ secondary_dex_compression_cmd.add("--bootstrap-dexes-dir", outputs[root_module_bootstrap_dex_output_dir])+ else:+ inputs_to_dex = module_inputs+ multi_dex_cmd.add("--primary-dex-patterns-path", primary_dex_patterns_file)++ multi_dex_cmd.add("--primary-dex", outputs[primary_dex_file].as_output())+ multi_dex_cmd.add("--primary-dex-class-names", outputs[primary_dex_class_names].as_output())+ secondary_dex_compression_cmd.add("--secondary-dex-output-dir", outputs[root_module_secondary_dex_output_dir].as_output())+ else:+ secondary_dex_dir_for_module = ctx.actions.declare_output(+ "secondary_dex_output_dir_for_module_{}".format(module), dir = True, has_content_based_path = False+ )+ secondary_dex_subdir = secondary_dex_dir_for_module.project(_get_secondary_dex_subdir(module))+ secondary_dex_dir_srcs[_get_secondary_dex_subdir(module)] = secondary_dex_subdir+ secondary_dex_compression_cmd.add(+ "--module-deps",+ ctx.actions.write(+ "module_deps_for_{}".format(module), apk_module_graph_info.module_to_module_deps_function(module), has_content_based_path = False+ ),+ )+ secondary_dex_compression_cmd.add("--secondary-dex-output-dir", secondary_dex_dir_for_module.as_output())+ inputs_to_dex = module_inputs+ if not pre_dexed_inputs:+ if is_root_module(module):+ if classpath_jars_list:+ multi_dex_cmd.add("--classpath-files", classpath_jars_list)+ else:+ multi_dex_cmd.add("--classpath-files", all_inputs_list)++ multi_dex_cmd.add("--module", module)+ multi_dex_cmd.add("--canary-class-name", apk_module_graph_info.module_to_canary_class_name_function(module))+ secondary_dex_compression_cmd.add("--module", module)+ secondary_dex_compression_cmd.add("--canary-class-name", apk_module_graph_info.module_to_canary_class_name_function(module))++ inputs_to_dex_file = argfile(actions = ctx.actions, name = "inputs_to_dex_file_for_module_{}.txt".format(module), args = inputs_to_dex)+ multi_dex_cmd.add("--files-to-dex-list", inputs_to_dex_file)+ if pre_dexed_inputs:+ multi_dex_cmd.add("--pre-dexed-inputs")++ multi_dex_cmd.add("--android-jar", android_toolchain.android_jar)+ if multidex_min_api:+ multi_dex_cmd.add("--min-sdk-version", multidex_min_api)++ if not is_optimized:+ multi_dex_cmd.add("--no-optimize")++ if proguard_configuration_output_file:+ multi_dex_cmd.add("--proguard-configuration-file", proguard_configuration_output_file)+ multi_dex_cmd.add("--proguard-mapping-file", proguard_mapping_output_file)++ ctx.actions.run(+ multi_dex_cmd,+ category = "multi_dex",+ identifier = "{}:{}_module_{}".format(ctx.label.package, ctx.label.name, module),+ allow_cache_upload = True,+ error_handler = android_toolchain.android_error_handler,+ )++ secondary_dex_compression_cmd.add("--compression", _get_dex_compression(ctx))+ secondary_dex_compression_cmd.add("--xz-compression-level", str(getattr(ctx.attrs, "xz_compression_level", 4)))++ ctx.actions.run(+ secondary_dex_compression_cmd,+ category = "secondary_dex_compression",+ identifier = "{}:{}_module_{}".format(ctx.label.package, ctx.label.name, module),+ allow_cache_upload = True,+ error_handler = android_toolchain.android_error_handler,+ )++ ctx.actions.symlinked_dir(outputs[secondary_dex_dir], secondary_dex_dir_srcs)++ ctx.actions.dynamic_output(dynamic = inputs, inputs = [], outputs = [o.as_output() for o in outputs], f = do_multi_dex)++ return DexFilesInfo(+ primary_dex = primary_dex_file,+ root_module_bootstrap_dex_dirs = [root_module_bootstrap_dex_output_dir] if root_module_bootstrap_dex_output_dir else [],+ root_module_secondary_dex_dirs = [root_module_secondary_dex_output_dir],+ non_root_module_secondary_dex_dirs = [secondary_dex_dir],+ secondary_dex_exopackage_info = None,+ proguard_text_files_path = None,+ primary_dex_class_names = primary_dex_class_names,+ )++def _get_primary_dex_and_secondary_dex_jars(+ ctx: AnalysisContext,+ jars: list[Artifact],+ java_library_jars_to_owners: dict[Artifact, TargetLabel],+ primary_dex_patterns_file: Artifact,+ proguard_configuration_output_file: Artifact | None,+ proguard_mapping_output_file: Artifact | None,+ android_toolchain: AndroidToolchainInfo,+) -> (list[Artifact], list[Artifact]):+ primary_dex_jars = []+ secondary_dex_jars = []+ for jar in jars:+ jar_splitter_cmd = cmd_args(android_toolchain.jar_splitter_command[RunInfo])+ owner = java_library_jars_to_owners[jar]+ identifier = "{}/{}/{}".format(owner.package, owner.name, jar.short_path)+ primary_dex_jar = ctx.actions.declare_output("root_module_primary_dex_jars/{}".format(identifier), has_content_based_path = True)+ secondary_dex_jar = ctx.actions.declare_output("root_module_secondary_dex_jars/{}".format(identifier), has_content_based_path = True)+ jar_splitter_cmd.add([+ "--input-jar",+ jar,+ "--primary-dex-patterns",+ primary_dex_patterns_file,+ "--primary-dex-classes-jar",+ primary_dex_jar.as_output(),+ "--secondary-dex-classes-jar",+ secondary_dex_jar.as_output(),+ ])+ if proguard_configuration_output_file:+ jar_splitter_cmd.add("--proguard-configuration-file", proguard_configuration_output_file)+ jar_splitter_cmd.add("--proguard-mapping-file", proguard_mapping_output_file)++ ctx.actions.run(+ jar_splitter_cmd,+ category = "jar_splitter",+ identifier = identifier,+ allow_cache_upload = True,+ error_handler = android_toolchain.android_error_handler,+ )++ primary_dex_jars.append(primary_dex_jar)+ secondary_dex_jars.append(secondary_dex_jar)++ return primary_dex_jars, secondary_dex_jars++def merge_to_single_dex(ctx: AnalysisContext, android_toolchain: AndroidToolchainInfo, pre_dexed_libs: list[DexLibraryInfo]) -> DexFilesInfo:+ expect(+ not _is_exopackage_enabled_for_secondary_dex(ctx),+ "It doesn't make sense to enable secondary dex exopackage for single dex builds!",+ )+ output_dex_file = ctx.actions.declare_output("classes.dex", has_content_based_path = False)+ pre_dexed_artifacts_to_dex_file = ctx.actions.declare_output("pre_dexed_artifacts_to_dex_file.txt", has_content_based_path = False)+ pre_dexed_artifacts = [pre_dexed_lib.dex for pre_dexed_lib in pre_dexed_libs if pre_dexed_lib.dex != None]+ _merge_dexes(ctx.actions, android_toolchain, output_dex_file, pre_dexed_artifacts, pre_dexed_artifacts_to_dex_file)++ return DexFilesInfo(+ primary_dex = output_dex_file,+ root_module_bootstrap_dex_dirs = [],+ root_module_secondary_dex_dirs = [],+ non_root_module_secondary_dex_dirs = [],+ secondary_dex_exopackage_info = None,+ proguard_text_files_path = None,+ primary_dex_class_names = None,+ )++DexInputWithSpecifiedClasses = record(+ lib = DexLibraryInfo,+ dex_class_names = list[str],+)++DexInputsWithClassNamesAndWeightEstimatesFile = record(+ libs = list[DexLibraryInfo],+ weight_estimate_and_filtered_class_names_file = Artifact,+)++# When using jar compression, the secondary dex directory consists of N secondary dex jars, each+# of which has a corresponding .meta file (the secondary_dex_metadata_file) containing a single+# line of the form:+# jar:<size of secondary dex jar (in bytes)> dex:<size of uncompressed dex file (in bytes)>+#+# It also contains a metadata.txt file, which consists on N lines, one for each secondary dex+# jar. Those lines consist of:+# <secondary dex file name> <sha1 hash of secondary dex> <canary class>+#+# We write the line that needs to be added to metadata.txt for this secondary dex jar to+# secondary_dex_metadata_line, and we use the secondary_dex_canary_class_name for the+# <canary class>.+#+# When we have finished building all of the secondary dexes, we read each of the+# secondary_dex_metadata_line artifacts and write them to a single metadata.txt file.+# We do that for raw compression too, since it also has a metadata.txt file.+SecondaryDexMetadataConfig = record(+ secondary_dex_compression = str,+ secondary_dex_metadata_path = [str, None],+ secondary_dex_metadata_file = Artifact | None,+ secondary_dex_metadata_line = Artifact,+ secondary_dex_canary_class_name = str,+)++def _get_secondary_dex_jar_metadata_config(+ actions: AnalysisActions, secondary_dex_path: str, module: str, module_to_canary_class_name_function: typing.Callable, index: int+) -> SecondaryDexMetadataConfig:+ secondary_dex_metadata_path = secondary_dex_path + ".meta"+ return SecondaryDexMetadataConfig(+ secondary_dex_compression = "jar",+ secondary_dex_metadata_path = secondary_dex_metadata_path,+ secondary_dex_metadata_file = actions.declare_output(secondary_dex_metadata_path, has_content_based_path = False),+ secondary_dex_metadata_line = actions.declare_output("metadata_line_artifacts/{}/{}".format(module, index + 1), has_content_based_path = False),+ secondary_dex_canary_class_name = _get_fully_qualified_canary_class_name(module, module_to_canary_class_name_function, index + 1),+ )++def _get_secondary_dex_raw_metadata_config(+ actions: AnalysisActions, module: str, module_to_canary_class_name_function: typing.Callable, index: int+) -> SecondaryDexMetadataConfig:+ return SecondaryDexMetadataConfig(+ secondary_dex_compression = "raw",+ secondary_dex_metadata_path = None,+ secondary_dex_metadata_file = None,+ secondary_dex_metadata_line = actions.declare_output("metadata_line_artifacts/{}/{}".format(module, index + 1), has_content_based_path = False),+ secondary_dex_canary_class_name = _get_fully_qualified_canary_class_name(module, module_to_canary_class_name_function, index + 1),+ )++def _get_filter_dex_batch_size() -> int:+ return 100++def _filter_pre_dexed_libs(+ actions: AnalysisActions,+ android_toolchain: AndroidToolchainInfo,+ primary_dex_patterns_file: Artifact,+ pre_dexed_libs: list[DexLibraryInfo],+ batch_number: int,+) -> DexInputsWithClassNamesAndWeightEstimatesFile:+ weight_estimate_and_filtered_class_names_file = actions.declare_output(+ "class_names_and_weight_estimates_for_batch_{}".format(batch_number), has_content_based_path = False+ )++ filter_dex_cmd_args = cmd_args([+ "--primary-dex-patterns",+ primary_dex_patterns_file,+ "--dex-target-identifiers",+ [lib.identifier for lib in pre_dexed_libs],+ "--class-names",+ [lib.class_names for lib in pre_dexed_libs],+ "--weight-estimates",+ [lib.weight_estimate for lib in pre_dexed_libs],+ "--ref-counts",+ [lib.ref_count for lib in pre_dexed_libs],+ "--synthetic-contexts",+ [lib.synthetic_contexts for lib in pre_dexed_libs],+ "--output",+ weight_estimate_and_filtered_class_names_file.as_output(),+ ])++ filter_dex_cmd = cmd_args([+ android_toolchain.filter_dex_class_names[RunInfo],+ at_argfile(+ actions = actions,+ name = "filter_dex_cmd_args_{}".format(batch_number),+ args = filter_dex_cmd_args,+ ),+ ])+ actions.run(+ filter_dex_cmd,+ category = "filter_dex",+ identifier = "batch_{}".format(batch_number),+ allow_cache_upload = True,+ error_handler = android_toolchain.android_error_handler,+ )++ return DexInputsWithClassNamesAndWeightEstimatesFile(+ libs = pre_dexed_libs, weight_estimate_and_filtered_class_names_file = weight_estimate_and_filtered_class_names_file+ )++_SortedPreDexedInputs = record(+ module = str,+ primary_dex_inputs = list[list[DexInputWithSpecifiedClasses]],+ secondary_dex_inputs = list[list[DexInputWithSpecifiedClasses]],+)++def write_metadata_dot_txts_impl(+ actions: AnalysisActions, metadata_lines: list[str], metadata_line_artifacts: list[ArtifactValue], metadata_dot_txt_output: OutputArtifact+):+ actions.write(metadata_dot_txt_output, metadata_lines + [a.read_string().strip() for a in metadata_line_artifacts])+ return []++_write_metadata_dot_txts_dynamic_action = dynamic_actions(+ impl = write_metadata_dot_txts_impl,+ attrs = {+ "metadata_dot_txt_output": dynattrs.output(),+ "metadata_line_artifacts": dynattrs.list(dynattrs.artifact_value()),+ "metadata_lines": dynattrs.list(dynattrs.value(str)),+ },+)++def merge_to_split_dex(+ ctx: AnalysisContext,+ android_toolchain: AndroidToolchainInfo,+ pre_dexed_libs: list[DexLibraryInfo],+ split_dex_merge_config: SplitDexMergeConfig,+ apk_module_graph_file: Artifact | None = None,+ enable_bootstrap_dexes: bool = False,+) -> DexFilesInfo:+ is_exopackage_enabled_for_secondary_dex = _is_exopackage_enabled_for_secondary_dex(ctx)+ if is_exopackage_enabled_for_secondary_dex:+ supported_dex_compression = ["jar", "raw"]+ expect(+ split_dex_merge_config.dex_compression in supported_dex_compression,+ "Exopackage can only be enabled for secondary dexes when the dex compression is {}, but the dex compression is '{}'".format(+ supported_dex_compression, split_dex_merge_config.dex_compression+ ),+ )+ primary_dex_patterns_file = ctx.actions.write("primary_dex_patterns_file", split_dex_merge_config.primary_dex_patterns, has_content_based_path = False)++ pre_dexed_libs_with_class_names_and_weight_estimates_files = []++ batch_size = _get_filter_dex_batch_size()+ for batch_number, start_index in enumerate(range(0, len(pre_dexed_libs), batch_size)):+ end_index = min(start_index + batch_size, len(pre_dexed_libs))+ pre_dexed_libs_with_class_names_and_weight_estimates_files.append(+ _filter_pre_dexed_libs(+ ctx.actions,+ android_toolchain,+ primary_dex_patterns_file,+ pre_dexed_libs[start_index:end_index],+ batch_number,+ ),+ )++ # Create lib metadata mapping: identifier -> owner target label.+ # This is used by the sort tool to determine which module each lib belongs to.+ lib_metadata = {}+ for lib in pre_dexed_libs:+ if lib.dex:+ lib_metadata[lib.identifier] = str(lib.dex.owner.raw_target())+ lib_metadata_file = ctx.actions.write_json("pre_dexed_libs_metadata.json", lib_metadata, has_content_based_path = False)++ filter_dex_output_files = [input.weight_estimate_and_filtered_class_names_file for input in pre_dexed_libs_with_class_names_and_weight_estimates_files]+ dex_plan_file = ctx.actions.declare_output("dex_plan.json", has_content_based_path = False)+ sort_cmd = cmd_args([+ android_toolchain.sort_pre_dexed_files[RunInfo],+ "--lib-metadata",+ lib_metadata_file,+ "--weight-limit",+ str(split_dex_merge_config.secondary_dex_weight_limit_bytes),+ "--output",+ dex_plan_file.as_output(),+ ])+ sort_cmd.add("--filter-dex-outputs")+ sort_cmd.add(filter_dex_output_files)+ if apk_module_graph_file:+ sort_cmd.add("--module-graph")+ sort_cmd.add(apk_module_graph_file)+ if enable_bootstrap_dexes:+ sort_cmd.add("--enable-bootstrap-dexes")+ ctx.actions.run(+ sort_cmd,+ category = "sort_pre_dexed_files",+ allow_cache_upload = True,+ )++ input_artifacts = [dex_plan_file]+ if apk_module_graph_file:+ input_artifacts.append(apk_module_graph_file)+ primary_dex_artifact_list = ctx.actions.declare_output("pre_dexed_artifacts_for_primary_dex.txt", has_content_based_path = False)+ primary_dex_output = ctx.actions.declare_output("classes.dex", has_content_based_path = False)+ primary_dex_class_names_list = ctx.actions.declare_output("primary_dex_class_names_list.txt", has_content_based_path = False)+ root_module_bootstrap_dexes_dir = ctx.actions.declare_output("root_module_bootstrap_dexes_dir", dir = True, has_content_based_path = False)+ root_module_secondary_dexes_dir = ctx.actions.declare_output("root_module_secondary_dexes_dir", dir = True, has_content_based_path = False)+ root_module_secondary_dexes_subdir = root_module_secondary_dexes_dir.project(_get_secondary_dex_subdir(ROOT_MODULE))+ root_module_secondary_dexes_metadata = root_module_secondary_dexes_dir.project(paths.join(_get_secondary_dex_subdir(ROOT_MODULE), "metadata.txt"))+ non_root_module_secondary_dexes_dir = ctx.actions.declare_output("non_root_module_secondary_dexes_dir", dir = True, has_content_based_path = False)++ outputs = [+ primary_dex_output,+ primary_dex_artifact_list,+ primary_dex_class_names_list,+ root_module_bootstrap_dexes_dir,+ root_module_secondary_dexes_dir,+ non_root_module_secondary_dexes_dir,+ ]++ def merge_pre_dexed_libs(ctx: AnalysisContext, artifacts, outputs):+ # We still need the module graph info for metadata.txt generation (module deps).+ apk_module_graph_info = (+ get_apk_module_graph_info(ctx, apk_module_graph_file, artifacts) if apk_module_graph_file else get_root_module_only_apk_module_graph_info()+ )+ module_to_canary_class_name_function = apk_module_graph_info.module_to_canary_class_name_function++ plan = artifacts[dex_plan_file].read_json()++ # Build a lookup from identifier to DexLibraryInfo for resolving dex artifacts.+ libs_by_id = {}+ for batch in pre_dexed_libs_with_class_names_and_weight_estimates_files:+ for lib in batch.libs:+ libs_by_id[lib.identifier] = lib++ def resolve_plan_groups(groups):+ resolved = []+ class_names_list = []+ for group in groups:+ inputs_for_group = []+ for lib_id in group["lib_ids"]:+ inputs_for_group.append(+ DexInputWithSpecifiedClasses(+ lib = libs_by_id[lib_id],+ dex_class_names = [], # class names come from the plan+ )+ )+ resolved.append(inputs_for_group)+ class_names_list.append(group["class_names"])+ return resolved, class_names_list++ sorted_pre_dexed_inputs = []+ plan_class_names = {}+ for module_plan in plan["modules"]:+ module = module_plan["module"]+ primary_groups, primary_class_names_list = resolve_plan_groups(module_plan["primary_groups"])+ secondary_groups, secondary_class_names_list = resolve_plan_groups(module_plan["secondary_groups"])++ sorted_pre_dexed_inputs.append(+ _SortedPreDexedInputs(+ module = module,+ primary_dex_inputs = primary_groups,+ secondary_dex_inputs = secondary_groups,+ )+ )++ for i, class_names in enumerate(primary_class_names_list):+ plan_class_names[("primary", module, i)] = class_names+ for i, class_names in enumerate(secondary_class_names_list):+ plan_class_names[("secondary", module, i)] = class_names++ root_module_secondary_dexes_for_symlinking = {}+ root_module_bootstrap_dexes_for_symlinking = {}+ non_root_module_secondary_dexes_for_symlinking = {}+ metadata_line_artifacts_by_module = {}+ metadata_dot_txt_files_by_module = {}+ base_apk_dex_files_count = 0++ for sorted_pre_dexed_input in sorted_pre_dexed_inputs:+ module = sorted_pre_dexed_input.module+ secondary_dexes_for_symlinking = (+ root_module_secondary_dexes_for_symlinking if is_root_module(module) else non_root_module_secondary_dexes_for_symlinking+ )++ # Unpack since primary_dex_inputs is a list of lists (which may be a single list for status-quo behaviors)+ primary_dex_inputs = sorted_pre_dexed_input.primary_dex_inputs[0] if sorted_pre_dexed_input.primary_dex_inputs else []+ additional_base_apk_dex_inputs = sorted_pre_dexed_input.primary_dex_inputs[1:]+ pre_dexed_artifacts = [primary_dex_input.lib.dex for primary_dex_input in primary_dex_inputs if primary_dex_input.lib.dex]+ if pre_dexed_artifacts:+ expect(is_root_module(module), "module {} should not have a primary dex!".format(module))+ primary_class_names = plan_class_names[("primary", module, 0)]+ ctx.actions.write(+ outputs[primary_dex_class_names_list].as_output(),+ primary_class_names,+ )++ _merge_dexes(+ ctx.actions,+ android_toolchain,+ outputs[primary_dex_output],+ pre_dexed_artifacts,+ outputs[primary_dex_artifact_list],+ class_names_to_include = primary_dex_class_names_list,+ )+ base_apk_dex_files_count += 1++ # If primary dex classes were spread to many based on weight, merge additional dex files here.+ for bootstrap_idx, bootstrap_dex_input_list in enumerate(additional_base_apk_dex_inputs):+ this_dex_number = base_apk_dex_files_count + 1+ bootstrap_class_names = plan_class_names[("primary", module, bootstrap_idx + 1)]+ bootstrap_dex_class_list = ctx.actions.write(+ "class_list_for_bootstrap_dex_{}.txt".format(this_dex_number),+ bootstrap_class_names,+ has_content_based_path = False,+ )++ # Figure out the name of this file and prepare its location for symlinking in final output dir.+ dex_file_name = "classes{}.dex".format(this_dex_number)+ bootstrap_dex_artifact_list = ctx.actions.declare_output(+ "pre_dexed_artifacts_for_bootstrap_dex_{}.txt".format(this_dex_number), has_content_based_path = False+ )+ bootstrap_dex_output = ctx.actions.declare_output(dex_file_name, has_content_based_path = False)+ root_module_bootstrap_dexes_for_symlinking[dex_file_name] = bootstrap_dex_output+ bootstrap_dex_artifacts = [bootstrap_dex_input.lib.dex for bootstrap_dex_input in bootstrap_dex_input_list]++ _merge_dexes(+ ctx.actions,+ android_toolchain,+ bootstrap_dex_output,+ bootstrap_dex_artifacts,+ bootstrap_dex_artifact_list,+ class_names_to_include = bootstrap_dex_class_list,+ )+ base_apk_dex_files_count += 1++ else:+ expect(+ not is_root_module(module),+ "No primary dex classes were specified! Please add primary_dex_patterns to ensure that at least one class exists in the primary dex.",+ )++ secondary_dex_inputs = sorted_pre_dexed_input.secondary_dex_inputs+ raw_secondary_dexes_for_compressing = {}+ for i in range(len(secondary_dex_inputs)):+ if split_dex_merge_config.dex_compression in ["jar", "raw", "raw_subdir"]:+ if split_dex_merge_config.dex_compression == "jar":+ secondary_dex_path = _get_secondary_dex_subdir_path(i, module)+ secondary_dex_metadata_config = _get_secondary_dex_jar_metadata_config(+ ctx.actions, secondary_dex_path, module, module_to_canary_class_name_function, i+ )+ secondary_dexes_for_symlinking[secondary_dex_metadata_config.secondary_dex_metadata_path] = (+ secondary_dex_metadata_config.secondary_dex_metadata_file+ )+ else:+ secondary_dex_path = _get_raw_secondary_dex_path(+ i,+ module,+ base_apk_dex_files_count,+ is_exopackage_enabled_for_secondary_dex or split_dex_merge_config.dex_compression == "raw_subdir",+ )+ secondary_dex_metadata_config = _get_secondary_dex_raw_metadata_config(ctx.actions, module, module_to_canary_class_name_function, i)++ secondary_dex_output = ctx.actions.declare_output(secondary_dex_path, has_content_based_path = False)+ secondary_dexes_for_symlinking[secondary_dex_path] = secondary_dex_output+ metadata_line_artifacts_by_module.setdefault(module, []).append(secondary_dex_metadata_config.secondary_dex_metadata_line)+ else:+ secondary_dex_name = _get_raw_secondary_dex_name(i, module, base_apk_dex_files_count)+ secondary_dex_output = ctx.actions.declare_output("{}/{}".format(module, secondary_dex_name), has_content_based_path = False)+ raw_secondary_dexes_for_compressing[secondary_dex_name] = secondary_dex_output+ secondary_dex_metadata_config = None++ this_dex_number = i + (base_apk_dex_files_count + 1 if is_root_module(module) else 2)+ secondary_dex_artifact_list = ctx.actions.declare_output(+ "pre_dexed_artifacts_for_secondary_dex_{}_for_module_{}.txt".format(this_dex_number, module), has_content_based_path = False+ )++ canary_dex_input = _create_canary_class(+ ctx,+ i + 1,+ module,+ module_to_canary_class_name_function,+ ctx.attrs._dex_toolchain[DexToolchainInfo],+ )+ all_class_names = canary_dex_input.dex_class_names + plan_class_names[("secondary", module, i)]+ secondary_dex_class_list = ctx.actions.write(+ "class_list_for_secondary_dex_{}_for_module_{}.txt".format(this_dex_number, module),+ all_class_names,+ has_content_based_path = False,+ )+ pre_dexed_artifacts = [canary_dex_input.lib.dex] if canary_dex_input.lib.dex else []+ pre_dexed_artifacts.extend([dex_input.lib.dex for dex_input in secondary_dex_inputs[i] if dex_input.lib.dex])++ _merge_dexes(+ ctx.actions,+ android_toolchain,+ secondary_dex_output,+ pre_dexed_artifacts,+ secondary_dex_artifact_list,+ class_names_to_include = secondary_dex_class_list,+ secondary_dex_metadata_config = secondary_dex_metadata_config,+ )++ if split_dex_merge_config.dex_compression in ["jar", "raw", "raw_subdir"]:+ metadata_dot_txt_path = "{}/metadata.txt".format(_get_secondary_dex_subdir(module))+ metadata_dot_txt_file = ctx.actions.declare_output(metadata_dot_txt_path, has_content_based_path = False)+ secondary_dexes_for_symlinking[metadata_dot_txt_path] = metadata_dot_txt_file+ metadata_dot_txt_files_by_module[module] = metadata_dot_txt_file+ else:+ raw_secondary_dexes_dir = ctx.actions.symlinked_dir(+ "raw_secondary_dexes_dir_for_module_{}".format(module), raw_secondary_dexes_for_compressing, has_content_based_path = False+ )+ secondary_dex_dir_for_module = ctx.actions.declare_output("secondary_dexes_dir_for_{}".format(module), dir = True, has_content_based_path = False)+ secondary_dex_subdir = secondary_dex_dir_for_module.project(_get_secondary_dex_subdir(module))++ multi_dex_cmd = cmd_args(android_toolchain.secondary_dex_compression_command[RunInfo])+ multi_dex_cmd.add("--secondary-dex-output-dir", secondary_dex_dir_for_module.as_output())+ multi_dex_cmd.add("--raw-secondary-dexes-dir", raw_secondary_dexes_dir)+ multi_dex_cmd.add("--compression", _get_dex_compression(ctx))+ multi_dex_cmd.add("--xz-compression-level", str(ctx.attrs.xz_compression_level))+ multi_dex_cmd.add("--module", module)+ multi_dex_cmd.add("--canary-class-name", module_to_canary_class_name_function(module))+ if not is_root_module(module):+ multi_dex_cmd.add(+ "--module-deps",+ ctx.actions.write(+ "module_deps_for_{}".format(module), apk_module_graph_info.module_to_module_deps_function(module), has_content_based_path = False+ ),+ )++ ctx.actions.run(+ multi_dex_cmd,+ category = "multi_dex_from_raw_dexes",+ identifier = "{}:{}_module_{}".format(ctx.label.package, ctx.label.name, module),+ allow_cache_upload = True,+ error_handler = android_toolchain.android_error_handler,+ )++ secondary_dexes_for_symlinking[_get_secondary_dex_subdir(module)] = secondary_dex_subdir++ for voltron_module, metadata_dot_txt in metadata_dot_txt_files_by_module.items():+ metadata_line_artifacts = metadata_line_artifacts_by_module[voltron_module]+ expect(metadata_line_artifacts != None, "Should have metadata lines!")++ metadata_lines = [".id {}".format(voltron_module)]+ metadata_lines.extend([".requires {}".format(module_dep) for module_dep in apk_module_graph_info.module_to_module_deps_function(voltron_module)])+ if split_dex_merge_config.dex_compression == "raw" and is_root_module(voltron_module) and not is_exopackage_enabled_for_secondary_dex:+ metadata_lines.append(".root_relative")+ ctx.actions.dynamic_output_new(+ _write_metadata_dot_txts_dynamic_action(+ metadata_dot_txt_output = metadata_dot_txt.as_output(),+ metadata_line_artifacts = metadata_line_artifacts,+ metadata_lines = metadata_lines,+ ),+ )++ ctx.actions.symlinked_dir(+ outputs[root_module_secondary_dexes_dir],+ root_module_secondary_dexes_for_symlinking,+ )+ ctx.actions.symlinked_dir(+ outputs[root_module_bootstrap_dexes_dir],+ root_module_bootstrap_dexes_for_symlinking,+ )+ ctx.actions.symlinked_dir(+ outputs[non_root_module_secondary_dexes_dir],+ non_root_module_secondary_dexes_for_symlinking,+ )++ ctx.actions.dynamic_output(dynamic = input_artifacts, inputs = [], outputs = [o.as_output() for o in outputs], f = merge_pre_dexed_libs)++ if is_exopackage_enabled_for_secondary_dex:+ root_module_secondary_dex_dirs = []+ secondary_dex_exopackage_info = ExopackageDexInfo(+ metadata = root_module_secondary_dexes_metadata,+ directory = root_module_secondary_dexes_subdir,+ )+ else:+ root_module_secondary_dex_dirs = [root_module_secondary_dexes_dir]+ secondary_dex_exopackage_info = None++ return DexFilesInfo(+ primary_dex = primary_dex_output,+ root_module_bootstrap_dex_dirs = [root_module_bootstrap_dexes_dir],+ root_module_secondary_dex_dirs = root_module_secondary_dex_dirs,+ non_root_module_secondary_dex_dirs = [non_root_module_secondary_dexes_dir],+ secondary_dex_exopackage_info = secondary_dex_exopackage_info,+ proguard_text_files_path = None,+ primary_dex_class_names = primary_dex_class_names_list,+ )++def _merge_dexes(+ actions: AnalysisActions,+ android_toolchain: AndroidToolchainInfo,+ output_dex_file: Artifact,+ pre_dexed_artifacts: list[Artifact],+ pre_dexed_artifacts_file: Artifact,+ class_names_to_include: Artifact | None = None,+ secondary_output_dex_file: Artifact | None = None,+ secondary_dex_metadata_config: [SecondaryDexMetadataConfig, None] = None,+):+ d8_cmd = cmd_args(android_toolchain.d8_command[RunInfo])+ d8_cmd.add(["--output-dex-file", output_dex_file.as_output()])++ pre_dexed_artifacts_to_dex_file = argfile(actions = actions, name = pre_dexed_artifacts_file, args = pre_dexed_artifacts)+ d8_cmd.add(["--files-to-dex-list", pre_dexed_artifacts_to_dex_file])++ d8_cmd.add(["--android-jar", android_toolchain.android_jar])+ d8_cmd.add(_DEX_MERGE_OPTIONS)++ if class_names_to_include:+ d8_cmd.add(["--primary-dex-class-names-path", class_names_to_include])++ if secondary_output_dex_file:+ d8_cmd.add(["--secondary-output-dex-file", secondary_output_dex_file.as_output()])++ if secondary_dex_metadata_config:+ d8_cmd.add(["--secondary-dex-compression", secondary_dex_metadata_config.secondary_dex_compression])+ if secondary_dex_metadata_config.secondary_dex_metadata_file:+ d8_cmd.add(["--secondary-dex-metadata-file", secondary_dex_metadata_config.secondary_dex_metadata_file.as_output()])+ d8_cmd.add(["--secondary-dex-metadata-line", secondary_dex_metadata_config.secondary_dex_metadata_line.as_output()])+ d8_cmd.add(["--secondary-dex-canary-class-name", secondary_dex_metadata_config.secondary_dex_canary_class_name])++ actions.run(+ d8_cmd,+ category = "merge_dexes",+ identifier = output_dex_file.short_path,+ allow_cache_upload = True,+ error_handler = android_toolchain.android_error_handler,+ )++def _get_raw_secondary_dex_name(index: int, module: str, base_apk_dex_count: int) -> str:+ # Root module begins at 2 (primary classes.dex is 1)+ # Non-root module begins at 1 (classes.dex)+ if is_root_module(module):+ return "classes{}.dex".format(index + base_apk_dex_count + 1)+ elif index == 0:+ return "classes.dex"+ else:+ return "classes{}.dex".format(index + 1)++def _get_raw_secondary_dex_path(index: int, module: str, base_apk_dex_count: int, store_raw_secondary_dexes_in_secondary_dex_subdir: bool):+ if is_root_module(module):+ if store_raw_secondary_dexes_in_secondary_dex_subdir:+ return _get_secondary_dex_subdir_path(index, module, "dex")+ return _get_raw_secondary_dex_name(index, module, base_apk_dex_count)+ else:+ return "assets/{}/{}".format(module, _get_raw_secondary_dex_name(index, module, base_apk_dex_count))++def _get_secondary_dex_subdir_path(index: int, module: str, suffix: str = "dex.jar"):+ return "{}/{}-{}.{}".format(+ _get_secondary_dex_subdir(module),+ "secondary" if is_root_module(module) else module,+ index + 1,+ suffix,+ )++def _get_secondary_dex_subdir(module: str):+ return "assets/{}".format("secondary-program-dex-jars" if is_root_module(module) else module)++# We create "canary" classes and add them to each secondary dex jar to ensure each jar has a class+# that can be safely loaded on any system. This class is used during secondary dex verification.+_CANARY_FULLY_QUALIFIED_CLASS_NAME_TEMPLATE = "{}.dex{}.Canary"+_CANARY_FILE_NAME_TEMPLATE = "canary_classes/{}/dex{}/Canary.java"+_CANARY_CLASS_PACKAGE_TEMPLATE = "package {}.dex{};\n"+_CANARY_CLASS_INTERFACE_DEFINITION = "public interface Canary {}"++def _create_canary_class(+ ctx: AnalysisContext, index: int, module: str, module_to_canary_class_name_function: typing.Callable, dex_toolchain: DexToolchainInfo+) -> DexInputWithSpecifiedClasses:+ prefix = module_to_canary_class_name_function(module)+ index_string = str(index)+ if len(index_string) == 1:+ index_string = "0" + index_string+ canary_class_java_file = ctx.actions.write(+ _CANARY_FILE_NAME_TEMPLATE.format(prefix, index_string),+ [_CANARY_CLASS_PACKAGE_TEMPLATE.format(prefix, index_string), _CANARY_CLASS_INTERFACE_DEFINITION],+ has_content_based_path = True,+ )+ canary_class_jar = ctx.actions.declare_output(+ "canary_classes/{}/canary_jar_{}.jar".format(prefix, index_string),+ has_content_based_path = True,+ )+ compile_to_jar(ctx, [canary_class_java_file], output = canary_class_jar, actions_identifier = "{}_canary_class{}".format(prefix, index_string))++ dex_library_info = get_dex_produced_from_java_library(ctx, dex_toolchain = dex_toolchain, jar_to_dex = canary_class_jar)++ return DexInputWithSpecifiedClasses(+ lib = dex_library_info,+ dex_class_names = [_get_fully_qualified_canary_class_name(module, module_to_canary_class_name_function, index).replace(".", "/") + ".class"],+ )++def _get_fully_qualified_canary_class_name(module: str, module_to_canary_class_name_function: typing.Callable, index: int) -> str:+ prefix = module_to_canary_class_name_function(module)+ index_string = str(index)+ if len(index_string) == 1:+ index_string = "0" + index_string+ return _CANARY_FULLY_QUALIFIED_CLASS_NAME_TEMPLATE.format(prefix, index_string)++def _is_exopackage_enabled_for_secondary_dex(ctx: AnalysisContext) -> bool:+ return "secondary_dex" in getattr(ctx.attrs, "exopackage_modes", [])
@@ -0,0 +1,134 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")++# Number of batches to split the class name files into.+# This reduces the number of hidden inputs from 40K+ files to NUM_BATCHES files.+_NUM_BATCHES = 32++def check_for_duplicate_classes_for_pre_dexed_libs(ctx: AnalysisContext, target_name_to_class_name_mapping: dict[str, Artifact]) -> Artifact:+ """+ Check for duplicate class names across pre-dexed libraries.++ To optimize performance, this function:+ 1. Splits the class name files into batches+ 2. Consolidates each batch into a single JSON file+ 3. Runs the duplicate class checker on the consolidated files++ This reduces the number of hidden inputs from O(N) individual files to+ O(NUM_BATCHES) consolidated files, significantly improving action+ materialization time in remote execution.+ """+ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]++ # Convert to list for batching+ items = list(target_name_to_class_name_mapping.items())+ num_items = len(items)++ if num_items == 0:+ # No class names to check, just create empty validation output+ validation_output = ctx.actions.declare_output("validation_output.txt", has_content_based_path = False)+ ctx.actions.write(validation_output, "No duplicate class names found")+ return validation_output++ # Calculate batch size+ batch_size = max(1, (num_items + _NUM_BATCHES - 1) // _NUM_BATCHES)++ # Create consolidated files for each batch+ consolidated_files = []+ for batch_idx in range(0, num_items, batch_size):+ batch_end = min(batch_idx + batch_size, num_items)+ batch_items = items[batch_idx:batch_end]+ batch_mapping = {k: v for k, v in batch_items}++ batch_num = batch_idx // batch_size+ consolidated_file = _consolidate_class_names_batch(+ ctx,+ android_toolchain,+ batch_mapping,+ batch_num,+ )+ consolidated_files.append(consolidated_file)++ # Run duplicate class checker on consolidated files+ validation_output = ctx.actions.declare_output("validation_output.txt", has_content_based_path = False)+ consolidated_files_list = ctx.actions.declare_output("consolidated_files_list.txt", has_content_based_path = False)+ ctx.actions.write(+ consolidated_files_list,+ consolidated_files,+ )++ ctx.actions.run(+ cmd_args(+ android_toolchain.duplicate_class_checker[RunInfo],+ "--mode",+ "pre-dexed-libs",+ "--validation-output",+ validation_output.as_output(),+ "--consolidated-files-list",+ consolidated_files_list,+ hidden = consolidated_files,+ ),+ category = "check_duplicate_classes_pre_dexed_libs",+ allow_cache_upload = True,+ )+ return validation_output++def _consolidate_class_names_batch(+ ctx: AnalysisContext, android_toolchain: AndroidToolchainInfo, target_name_to_class_name_mapping: dict[str, Artifact], batch_num: int+) -> Artifact:+ """Consolidate a batch of class name files into a single JSON file."""+ input_mapping_file = ctx.actions.declare_output(+ "consolidate_batch_{}_input.json".format(batch_num),+ has_content_based_path = False,+ )+ ctx.actions.write_json(input_mapping_file, target_name_to_class_name_mapping)++ consolidated_output = ctx.actions.declare_output(+ "consolidated_class_names_batch_{}.json".format(batch_num),+ has_content_based_path = False,+ )++ ctx.actions.run(+ cmd_args(+ android_toolchain.consolidate_class_names[RunInfo],+ "--input-mapping-file",+ input_mapping_file,+ "--output-file",+ consolidated_output.as_output(),+ hidden = target_name_to_class_name_mapping.values(),+ ),+ category = "consolidate_class_names",+ identifier = "batch_{}".format(batch_num),+ allow_cache_upload = True,+ )+ return consolidated_output++def check_for_duplicate_classes_for_non_pre_dexed_jars(ctx: AnalysisContext, jar_to_owning_target_mapping: dict[Artifact, TargetLabel]) -> Artifact:+ validation_output = ctx.actions.declare_output("validation_output.txt", has_content_based_path = False)+ jar_to_owning_target_map_file = ctx.actions.declare_output("jar_to_owning_target_map_file.txt", has_content_based_path = False)+ ctx.actions.write_json(+ jar_to_owning_target_map_file,+ jar_to_owning_target_mapping,+ )++ ctx.actions.run(+ cmd_args(+ ctx.attrs._android_toolchain[AndroidToolchainInfo].duplicate_class_checker[RunInfo],+ "--mode",+ "non-pre-dexed-jars",+ "--jar-to-owning-target-map-file",+ jar_to_owning_target_map_file,+ "--validation-output",+ validation_output.as_output(),+ hidden = jar_to_owning_target_mapping.keys(),+ ),+ category = "check_duplicate_classes_non_pre_dexed_jars",+ )+ return validation_output
@@ -0,0 +1,31 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//utils:expect.bzl", "expect")++SECONDARY_DEX = 1+NATIVE_LIBRARY = 2+RESOURCES = 4+MODULES = 8+ARCH64 = 16++def get_exopackage_flags(exopackage_modes: list[str]) -> int:+ expect("modules" not in exopackage_modes, "Modular exopackage is not supported!")+ flags = 0++ for name, flag in [+ ("secondary_dex", SECONDARY_DEX),+ ("native_library", NATIVE_LIBRARY),+ ("resources", RESOURCES),+ ("modules", MODULES),+ ("arch64", ARCH64),+ ]:+ if name in exopackage_modes:+ flags += flag++ return flags
@@ -0,0 +1,80 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")+load(":android_toolchain.bzl", "AidlToolchainInfo")++_AidlSourceInfo = provider(+ fields = {+ "srcs": provider_field(typing.Any, default = None),+ }+)++def gen_aidl_impl(ctx: AnalysisContext) -> list[Provider]:+ aidl_toolchain = ctx.attrs._aidl_toolchain[AidlToolchainInfo]+ aidl_cmd = cmd_args(+ [aidl_toolchain.aidl]+ + ["-p", aidl_toolchain.framework_aidl_file]+ + ["-I", ctx.attrs.import_path]+ + [a for path in ctx.attrs.import_paths for a in ["-I", path]],+ # We need the `aidl_srcs` files - otherwise the search on the `import_path` won't find anything.+ hidden = ctx.attrs.aidl_srcs,+ )++ # Allow gen_aidl rules to depend on other gen_aidl rules, and make the source files from the+ # deps accessible in this context. This is an alternative to adding dependent files in+ # aidl_srcs.+ dep_srcs = []+ for dep in ctx.attrs.deps:+ source_info = dep.get(_AidlSourceInfo)+ if source_info != None:+ dep_srcs += source_info.srcs+ else:+ warning("`{}` dependency `{}` is not a `gen_aidl` rule and will be ignored".format(ctx.label, dep.label))++ aidl_cmd.add(cmd_args(hidden = dep_srcs))++ aidl_out = ctx.actions.declare_output("aidl_output", dir = True, has_content_based_path = True)+ aidl_cmd.add("-o", aidl_out.as_output())+ aidl_cmd.add(ctx.attrs.aidl)++ # Aidl does not create any output for parcelables. Therefore, we always initialize the output+ # directory so that we don't get an "Action failed to produce outputs" error.+ if ctx.attrs._exec_os_type[OsLookup].os == Os("windows"):+ sh_cmd = cmd_args([+ cmd_args(["cmd.exe", "/c", cmd_args([aidl_out.as_output()], format = "if not exist {} md {}")]),+ "&&",+ aidl_cmd,+ ])+ else:+ sh_cmd = cmd_args([+ "sh",+ "-c",+ "mkdir -p $1 && $2",+ "--",+ aidl_out.as_output(),+ cmd_args(aidl_cmd, delimiter = " "),+ ])++ ctx.actions.run(sh_cmd, category = "aidl")++ # Put the generated Java files into a zip file to be used as srcs to other rules.+ java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]+ jar_cmd = cmd_args(java_toolchain.jar)+ jar_cmd.add("-cfM")+ out = ctx.actions.declare_output("{}_aidl_java_output.src.zip".format(ctx.attrs.name), has_content_based_path = True)+ jar_cmd.add(out.as_output())+ jar_cmd.add(aidl_out)++ ctx.actions.run(jar_cmd, category = "aidl_jar")++ return [+ DefaultInfo(default_output = out),+ _AidlSourceInfo(srcs = [ctx.attrs.aidl] + ctx.attrs.aidl_srcs + dep_srcs),+ ]
@@ -0,0 +1,19 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(":android_providers.bzl", "KeystoreInfo")++def keystore_impl(ctx: AnalysisContext) -> list[Provider]:+ sub_targets = {}+ sub_targets["keystore"] = [DefaultInfo(default_output = ctx.attrs.store)]+ sub_targets["properties"] = [DefaultInfo(default_output = ctx.attrs.properties)]++ return [+ KeystoreInfo(store = ctx.attrs.store, properties = ctx.attrs.properties),+ DefaultInfo(default_outputs = [ctx.attrs.store, ctx.attrs.properties], sub_targets = sub_targets),+ ]
@@ -0,0 +1,16 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++_MIN_SDK_VERSION = 19+_MAX_SDK_VERSION = 36++def get_min_sdk_version_constraint_value_name(min_sdk: int) -> str:+ return "min_sdk_version_{}".format(min_sdk)++def get_min_sdk_version_range() -> range:+ return range(_MIN_SDK_VERSION, _MAX_SDK_VERSION)
@@ -0,0 +1,124 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# Shared schema for the [native_build_commands] sub-target, used by both+# android_binary_native_library_rules.bzl and meta_only/gatorade.bzl. This lives in a leaf module+# because gatorade.bzl is loaded by android_binary_native_library_rules.bzl and so cannot import the+# entry helper back from there.++# Whether to capture per-source compile commands (the expensive [native_build_commands][compile]+# kind). Off by default; enable with `-c cxx.emit_native_build_commands=true`. Follows the+# FORCE_SINGLE_CPU config-backed-attr pattern. Single source of truth for both the cxx_library attr+# that carries compile commands onto the linkable graph (rules_impl.bzl) and the app-side compile+# emission (android_binary_native_library_rules.bzl).+EMIT_NATIVE_BUILD_COMMANDS = read_root_config("cxx", "emit_native_build_commands") in ("True", "true")++# Command "kinds" collected by the [native_build_commands] sub-target. Each kind also gets its own+# filtered sub-target, e.g. `TARGET[native_build_commands][relink]`. Note `mergemap` (the one+# whole-graph merge-map PLAN computation) is distinct from `merge` (the per-soname merge link that+# combines constituent libraries), and `link` is reserved for a plain per-library link on apps that+# neither merge nor relink.+NATIVE_BUILD_COMMAND_KINDS = [+ "compile",+ "mergemap",+ "merge",+ "link",+ "relink",+ "early_gatorade",+ "middle_gatorade",+ "late_gatorade",+ "bolt",+]++# The Gatorade phases exposed as top-level product sub-targets on Android app targets: building+# `TARGET[early_gatorade]` runs that phase and outputs the artifacts its gatorade invocation(s)+# produce, as a directory (like [native_libs]). Kept in this leaf module as the single source of+# truth for both the app rule that registers them and apk_genrule.bzl that forwards them through the+# redex/repack/resign wrapper. (Unrelated to NATIVE_BUILD_COMMAND_KINDS above, which is the separate+# [native_build_commands] JSON schema; these names coincide with those Gatorade kinds only by+# convention.)+GATORADE_PHASE_SUBTARGETS = [+ "early_gatorade",+ "middle_gatorade",+ "late_gatorade",+]++# One entry in the [native_build_commands] JSON. `argv` is embedded as an ArgLike via+# write_json(with_inputs = False) so an entry renders its command without materializing the produced+# artifact, and `argsfile` lets a consumer expand the full flag list when the argv references an+# @argsfile. This shape is intentionally its own thing, not a compile_commands.json entry nor the+# [linker_commands] shape: it spans compile/link/merge/relink/gatorade/bolt uniformly, so consumers+# should key off `kind` rather than assume any single tool's schema.+#+# `argv` must not contain any `.as_output()` reference: write_json cannot re-serialize an output+# artifact, and doing so would also make this entry's writer a second producer of that artifact.+# Pass the plain output artifact instead.+#+# Field notes:+# - `argv`: for link/merge/relink/bolt/gatorade kinds this is the real executed command. For+# kind=compile it is the compile_commands.json-style invocation (compiler + @argsfile + source),+# NOT the exact object-producing action (it omits `-o`, LTO/bitcode flavor flags, dep-file and+# compiler-wrapper args); it mirrors what comp_db.bzl emits for a source. Use it to reproduce a+# representative compile, not to byte-match the build action.+# - `soname`: for per-library kinds, the FINAL shipped/merged soname the command contributes to.+# Best-effort for kind=compile: the compile->merged-soname map is built from each merged lib's+# PRIMARY constituents (matching shared_object_targets.txt), so an object that lands in a merged+# .so only as a non-primary / transitively-linked-static constituent is reported under its own+# `pre_merge_soname` rather than the merged soname. Split groups and late-gatorade code motion also+# make it approximate — cross-reference the app's merge.map / shared_object_targets.txt when an+# authoritative object->soname mapping is needed. None for whole-graph steps (e.g. compute_mergemap).+# - `pre_merge_soname`: for kind=compile, the per-cxx_library (pre-merge) soname the object was+# built for; None for other kinds.+# - `output`: the produced artifact's short_path for link/merge/relink/bolt/gatorade kinds; for+# kind=compile it is the compiled SOURCE path (the produced object is not available here — the+# full per-source attribution lives in `identifier`).+# - `argsfile`: the @argsfile the command references, if any. The sub-target MATERIALIZES it on disk+# for the link-family (merge/link/relink/bolt) and compile kinds, so a consumer that builds+# TARGET[native_build_commands] (or a per-kind filter) can read the flags. Gatorade argsfiles+# (early's input-containers list, late codegen and tmp-link) are recorded by PATH only, not+# materialized by the sub-target — build the app itself to obtain those files on disk.+def native_build_command_entry(kind, category, arch, soname, output, argv, argsfile = None, identifier = None, pre_merge_soname = None):+ if kind not in NATIVE_BUILD_COMMAND_KINDS:+ fail("native_build_command_entry: unknown kind {!r}; expected one of {}".format(kind, NATIVE_BUILD_COMMAND_KINDS))+ return {+ "arch": arch,+ "argsfile": argsfile,+ "argv": argv,+ "category": category,+ "identifier": identifier,+ "kind": kind,+ "output": output,+ "pre_merge_soname": pre_merge_soname,+ "soname": soname,+ }++# Record a link-family entry (link/merge/relink/bolt) for a LinkedObject, deduplicating the identical+# guard+append that otherwise gets copy-pasted at every capture site. No-op when recording is off+# (native_cmd_entries == None) or the object carries no reified linker command (prebuilt copies,+# pre-bolt/late-gatorade dummy objects, and DistLTO all have none). `linked_object` is accepted+# untyped to keep this a leaf module (no prelude/linking import); it must expose the LinkedObject+# fields `output`, `linker_command`, and `linker_argsfile`.+#+# Intentionally NOT built on linking's make_link_command_debug_output: that helper also requires an+# argsfile and drops the command otherwise, which would silently lose links that inline all flags —+# unacceptable for a capture-everything sub-target. Here argsfile is optional (recorded as None).+def record_link_command(native_cmd_entries, kind, arch, soname, linked_object, category = "cxx_link", pre_merge_soname = None):+ if native_cmd_entries == None or not linked_object.linker_command:+ return+ native_cmd_entries.append(+ native_build_command_entry(+ kind = kind,+ category = category,+ arch = arch,+ soname = soname,+ output = linked_object.output.short_path,+ argv = linked_object.linker_command,+ argsfile = linked_object.linker_argsfile,+ pre_merge_soname = pre_merge_soname,+ ),+ )
@@ -0,0 +1,39 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//android:android_providers.bzl",+ "PrebuiltNativeLibraryDir",+ "merge_android_packageable_info",+)++def prebuilt_native_library_impl(ctx: AnalysisContext) -> list[Provider]:+ if ctx.attrs.is_asset and ctx.attrs.has_wrap_script:+ fail("Cannot use `is_asset` and `has_wrap_script` in the same rule")++ prebuilt_native_library_dir = PrebuiltNativeLibraryDir(+ raw_target = ctx.label.raw_target(),+ dir = ctx.attrs.native_libs,+ for_primary_apk = ctx.attrs.has_wrap_script,+ is_asset = ctx.attrs.is_asset,+ )+ android_packageable_info = merge_android_packageable_info(+ ctx.label,+ ctx.actions,+ ctx.attrs.deps,+ prebuilt_native_library_dir = prebuilt_native_library_dir,+ )+ return [+ # Buck1 copies the input directory and returns it as the output path. We don't+ # copy; we could just return the input directory itself as the output path, but+ # we're avoiding that (due to potential confusion from the output path being an+ # input directory) until we have an actual need for prebuilt_native_library+ # having an output path.+ DefaultInfo(),+ android_packageable_info,+ ]
@@ -0,0 +1,84 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//android:android_providers.bzl", "AndroidPreprocessedJavaClassesInfo")+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//android:util.bzl", "EnhancementContext")+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")+load("@prelude//java/utils:java_more_utils.bzl", "get_path_separator_for_exec_os")+load("@prelude//utils:expect.bzl", "expect")++def get_preprocessed_java_classes(+ enhance_ctx: EnhancementContext,+ input_jars: dict[Artifact, TargetLabel],+) -> (dict[Artifact, TargetLabel], AndroidPreprocessedJavaClassesInfo | None):+ if not input_jars:+ return {}, None++ ctx = enhance_ctx.ctx++ input_srcs = {}+ output_jars_to_owners = {}+ output_dir = ctx.actions.declare_output("preprocessed_java_classes/output_dir", has_content_based_path = False)+ input_jars_to_owners = {}++ for i, (input_jar, target_label) in enumerate(input_jars.items()):+ expect(input_jar.extension == ".jar", "Expected {} to have extension .jar!".format(input_jar))+ jar_name = "{}_{}".format(i, input_jar.basename)+ input_srcs[jar_name] = input_jar+ input_jars_to_owners[jar_name] = target_label+ output_jar = output_dir.project(jar_name)+ output_jars_to_owners[output_jar] = target_label++ input_dir = ctx.actions.symlinked_dir("preprocessed_java_classes/input_dir", input_srcs, has_content_based_path = False)+ input_jars_map = ctx.actions.write_json("preprocessed_java_classes/input_jars_map.json", input_jars_to_owners, has_content_based_path = False)+ materialized_artifacts_dir = ctx.actions.declare_output("preprocessed_java_classes/materialized_artifacts", has_content_based_path = False)++ android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]+ env = {+ "ANDROID_BOOTCLASSPATH": cmd_args(+ android_toolchain.android_bootclasspath + android_toolchain.android_optional_jars,+ delimiter = get_path_separator_for_exec_os(ctx),+ ),+ "IN_JARS_DIR": cmd_args(input_dir),+ "IN_JARS_MAP": cmd_args(input_jars_map),+ "MATERIALIZED_ARTIFACTS_DIR": materialized_artifacts_dir.as_output(),+ "OUT_JARS_DIR": output_dir.as_output(),+ "PREPROCESS": ctx.attrs.preprocess_java_classes_bash,+ "ZIP_SCRUBBER": ctx.attrs._java_toolchain[JavaToolchainInfo].zip_scrubber,+ }++ output_jars = output_jars_to_owners.keys()+ output_jars_file = ctx.actions.write("preprocessed_java_classes/output_jars.txt", output_jars, has_content_based_path = False)++ preprocess_cmd = [+ "/usr/bin/env",+ "bash",+ "-c",+ # Note: ZIP_SCRUBBER might expand to multiple words, so no quoting there.+ 'mkdir -p "$OUT_JARS_DIR" && mkdir -p "$MATERIALIZED_ARTIFACTS_DIR" && eval "$PREPROCESS" && $ZIP_SCRUBBER --paths-to-scrub "$@"',+ "--",+ output_jars_file,+ ]++ preprocess_cmd = cmd_args(+ preprocess_cmd,+ hidden = [output_jar.as_output() for output_jar in output_jars]+ + [dep[DefaultInfo].default_outputs + dep[DefaultInfo].other_outputs for dep in ctx.attrs.preprocess_java_classes_deps],+ )++ ctx.actions.run(preprocess_cmd, env = env, category = "preprocess_java_classes")++ enhance_ctx.debug_output("preprocess_java_classes_input_dir", input_dir)+ enhance_ctx.debug_output("preprocess_java_classes_input_jars_map", input_jars_map)+ enhance_ctx.debug_output("preprocess_java_classes_materialized_artifacts_dir", materialized_artifacts_dir)++ return output_jars_to_owners, AndroidPreprocessedJavaClassesInfo(+ input_dir = input_dir,+ materialized_artifacts_dir = materialized_artifacts_dir,+ )
@@ -0,0 +1,206 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//android:android_providers.bzl", "AndroidResourceInfo", "RDotJavaInfo")+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//java:java_library.bzl", "compile_to_jar")+load("@prelude//java:java_providers.bzl", "JavaLibraryInfo", "single_library_compiling_deps")+load("@prelude//utils:argfile.bzl", "argfile")++RDotJavaSourceCode = record(+ r_dot_java_source_code_dir = Artifact,+ r_dot_java_source_code_zipped = Artifact,+ strings_source_code_dir = Artifact | None,+ strings_source_code_zipped = Artifact | None,+ ids_source_code_dir = Artifact | None,+ ids_source_code_zipped = Artifact | None,+)++def get_dummy_r_dot_java(ctx: AnalysisContext, merge_android_resources_tool: RunInfo, android_resources: list[AndroidResourceInfo]) -> JavaLibraryInfo:+ r_dot_java_source_code = _generate_r_dot_java_source_code(ctx, merge_android_resources_tool, android_resources, "dummy_r_dot_java")+ return _compile_r_dot_java(+ ctx,+ r_dot_java_source_code.r_dot_java_source_code_zipped,+ "dummy_r_dot_java",+ ).library_info++def generate_r_dot_javas(+ ctx: AnalysisContext,+ merge_android_resources_tool: RunInfo,+ android_resources: list[AndroidResourceInfo],+ banned_duplicate_resource_types: list[str],+ uber_r_dot_txt_files: list[Artifact],+ override_symbols_paths: list[Artifact],+ duplicate_resources_allowlist: Artifact | None,+ referenced_resources_lists: list[Artifact],+ generate_strings_and_ids_separately: [bool, None] = True,+ remove_classes: list[str] = [],+) -> list[RDotJavaInfo]:+ if not android_resources:+ # d8 will fail if its input contains no classes. Rather than add empty input handling in multiple places,+ # like buck1 we just generate a stub class if we have no resources. This will be stripped from release+ # builds and have minimal impact on debug builds.+ return [+ _compile_r_dot_java(+ ctx,+ ctx.attrs._android_toolchain[AndroidToolchainInfo].app_without_resources_stub,+ "main_r_dot_java",+ ),+ ]++ r_dot_java_source_code = _generate_r_dot_java_source_code(+ ctx,+ merge_android_resources_tool,+ android_resources,+ "r_dot_java",+ generate_strings_and_ids_separately = generate_strings_and_ids_separately,+ force_final_resources_ids = True,+ banned_duplicate_resource_types = banned_duplicate_resource_types,+ uber_r_dot_txt_files = uber_r_dot_txt_files,+ override_symbols_paths = override_symbols_paths,+ duplicate_resources_allowlist = duplicate_resources_allowlist,+ referenced_resources_lists = referenced_resources_lists,+ )++ library_infos = [+ _compile_r_dot_java(+ ctx,+ r_dot_java_source_code.r_dot_java_source_code_zipped,+ "main_r_dot_java",+ remove_classes = remove_classes,+ ),+ ]+ if generate_strings_and_ids_separately:+ library_infos += [+ _compile_r_dot_java(+ ctx,+ r_dot_java_source_code.strings_source_code_zipped,+ "strings_r_dot_java",+ remove_classes = remove_classes + [".R$"],+ ),+ _compile_r_dot_java(+ ctx,+ r_dot_java_source_code.ids_source_code_zipped,+ "ids_r_dot_java",+ remove_classes = remove_classes + [".R$"],+ ),+ ]++ return library_infos++def _generate_r_dot_java_source_code(+ ctx: AnalysisContext,+ merge_android_resources_tool: RunInfo,+ android_resources: list[AndroidResourceInfo],+ identifier: str,+ force_final_resources_ids = False,+ generate_strings_and_ids_separately = False,+ banned_duplicate_resource_types: list[str] = [],+ uber_r_dot_txt_files: list[Artifact] = [],+ override_symbols_paths: list[Artifact] = [],+ duplicate_resources_allowlist: Artifact | None = None,+ referenced_resources_lists: list[Artifact] = [],+) -> RDotJavaSourceCode:+ merge_resources_cmd = cmd_args(merge_android_resources_tool)++ r_dot_txt_info = cmd_args()+ deduped_android_resources = set(+ [(android_resource.text_symbols, android_resource.r_dot_java_package, android_resource.raw_target) for android_resource in android_resources]+ )+ for text_symbols, r_dot_java_package, raw_target in deduped_android_resources:+ r_dot_txt_info.add(cmd_args([text_symbols, r_dot_java_package, raw_target], delimiter = " "))++ r_dot_txt_info_file = ctx.actions.write("r_dot_txt_info_file_for_{}.txt".format(identifier), r_dot_txt_info, has_content_based_path = True)+ merge_resources_cmd.add(["--symbol-file-info", r_dot_txt_info_file])+ merge_resources_cmd.add(+ cmd_args(+ hidden = [android_resource.r_dot_java_package for android_resource in android_resources]+ + [android_resource.text_symbols for android_resource in android_resources],+ )+ )++ output_dir = ctx.actions.declare_output("{}_source_code".format(identifier), dir = True, has_content_based_path = True)+ merge_resources_cmd.add(["--output-dir", output_dir.as_output()])+ output_dir_zipped = ctx.actions.declare_output("{}.src.zip".format(identifier), has_content_based_path = True)+ merge_resources_cmd.add(["--output-dir-zipped", output_dir_zipped.as_output()])++ if generate_strings_and_ids_separately:+ strings_output_dir = ctx.actions.declare_output("strings_source_code", dir = True, has_content_based_path = True)+ merge_resources_cmd.add(["--strings-output-dir", strings_output_dir.as_output()])+ strings_output_dir_zipped = ctx.actions.declare_output("strings.src.zip", has_content_based_path = True)+ merge_resources_cmd.add(["--strings-output-dir-zipped", strings_output_dir_zipped.as_output()])+ ids_output_dir = ctx.actions.declare_output("ids_source_code", dir = True, has_content_based_path = True)+ merge_resources_cmd.add(["--ids-output-dir", ids_output_dir.as_output()])+ ids_output_dir_zipped = ctx.actions.declare_output("ids.src.zip", has_content_based_path = True)+ merge_resources_cmd.add(["--ids-output-dir-zipped", ids_output_dir_zipped.as_output()])+ else:+ strings_output_dir = None+ strings_output_dir_zipped = None+ ids_output_dir = None+ ids_output_dir_zipped = None++ if force_final_resources_ids:+ merge_resources_cmd.add("--force-final-resource-ids")++ if len(banned_duplicate_resource_types) > 0:+ banned_duplicate_resource_types_file = ctx.actions.write(+ "banned_duplicate_resource_types_file", banned_duplicate_resource_types, has_content_based_path = True+ )+ merge_resources_cmd.add(["--banned-duplicate-resource-types", banned_duplicate_resource_types_file])++ if len(uber_r_dot_txt_files) > 0:+ uber_r_dot_txt_files_list = argfile(actions = ctx.actions, name = "uber_r_dot_txt_files_list", args = uber_r_dot_txt_files, has_content_based_path = True)+ merge_resources_cmd.add(["--uber-r-dot-txt", uber_r_dot_txt_files_list])++ if len(override_symbols_paths) > 0:+ override_symbols_paths_list = argfile(actions = ctx.actions, name = "override_symbols_paths_list", args = override_symbols_paths, has_content_based_path = True)+ merge_resources_cmd.add(["--override-symbols", override_symbols_paths_list])++ if duplicate_resources_allowlist != None:+ merge_resources_cmd.add(["--duplicate-resource-allowlist-path", duplicate_resources_allowlist])++ if referenced_resources_lists:+ referenced_resources_file = argfile(+ actions = ctx.actions, name = "referenced_resources_lists", args = referenced_resources_lists, has_content_based_path = True+ )+ merge_resources_cmd.add(["--referenced-resources-lists", referenced_resources_file])++ ctx.actions.run(merge_resources_cmd, category = "r_dot_java_merge_resources", identifier = identifier)++ return RDotJavaSourceCode(+ r_dot_java_source_code_dir = output_dir,+ r_dot_java_source_code_zipped = output_dir_zipped,+ strings_source_code_dir = strings_output_dir,+ strings_source_code_zipped = strings_output_dir_zipped,+ ids_source_code_dir = ids_output_dir,+ ids_source_code_zipped = ids_output_dir_zipped,+ )++def _compile_r_dot_java(ctx: AnalysisContext, r_dot_java_source_code_zipped: Artifact, identifier: str, remove_classes: list[str] = []) -> RDotJavaInfo:+ r_dot_java_out = ctx.actions.declare_output("{}.jar".format(identifier), has_content_based_path = True)+ outputs = compile_to_jar(+ ctx,+ output = r_dot_java_out,+ actions_identifier = identifier,+ javac_tool = None,+ srcs = [r_dot_java_source_code_zipped],+ remove_classes = remove_classes,+ required_for_source_only_abi = True,+ )++ library_output = outputs.classpath_entry++ return RDotJavaInfo(+ identifier = identifier,+ library_info = JavaLibraryInfo(+ compiling_deps = single_library_compiling_deps(ctx.actions, library_output),+ library_output = library_output,+ output_for_classpath_macro = library_output.full_library,+ ),+ source_zipped = r_dot_java_source_code_zipped,+ )
@@ -0,0 +1,448 @@+# Buck2 Android Prelude++## 1. 🧭 Overview++The Buck2 Android Prelude is a comprehensive build system for Android+applications and libraries within Meta's Buck2 build system. It provides a+complete set of build rules, toolchain integrations, and utilities for building+Android APKs, AABs (Android App Bundles), libraries, and running tests.++### Key Features++- **Complete Android Build Pipeline**: From Java/Kotlin source code to signed+ APKs and AABs+- **Multi-DEX Support**: Advanced DEX file splitting and optimization with+ multiple compression strategies+- **Resource Processing**: AAPT2-based resource compilation and linking with+ R.java generation+- **Native Library Integration**: Support for native libraries across multiple+ CPU architectures+- **Exopackage Support**: Dynamic loading of DEX files, native libraries, and+ resources for faster development+- **Voltron Modularity**: Support for modular Android applications with dynamic+ feature modules+- **Testing Framework**: Comprehensive testing support including instrumentation+ tests and Robolectric+- **Toolchain Integration**: Deep integration with Android SDK tools, ProGuard,+ and D8/R8++### Technologies Used++- **Language**: Starlark (Buck2's build language), Python (utility tools), Java+ (toolchain components)+- **Framework**: Buck2 build system with Android SDK integration+- **Tools**: AAPT2, D8/R8, ProGuard, Android SDK tools, zipalign+- **Infrastructure**: Remote execution support, caching, and distributed builds++---++## 2. 🧱 High-Level Architecture Diagram++```mermaid+graph TB+ subgraph "Build Rules Layer"+ APK[android_apk]+ LIB[android_library]+ RES[android_resource]+ AAR[android_aar]+ BUNDLE[android_bundle]+ TEST[android_instrumentation_test]+ end++ subgraph "Processing Layer"+ DEX[DEX Processing<br/>dex_rules.bzl]+ RESOURCES[Resource Processing<br/>aapt2_link.bzl]+ NATIVE[Native Library<br/>Processing]+ MANIFEST[Manifest<br/>Processing]+ end++ subgraph "Provider Layer"+ PROVIDERS[Android Providers<br/>android_providers.bzl]+ JAVA_PROVIDERS[Java Providers]+ end++ subgraph "Toolchain Layer"+ ANDROID_TC[Android Toolchain<br/>android_toolchain.bzl]+ JAVA_TC[Java Toolchain]+ DEX_TC[DEX Toolchain]+ end++ subgraph "Utility Tools"+ PY_TOOLS[Python Tools<br/>tools/]+ JAVA_TOOLS[Java Tools]+ end++ subgraph "External Dependencies"+ ANDROID_SDK[Android SDK]+ AAPT2[AAPT2]+ D8[D8/R8]+ PROGUARD[ProGuard]+ end++ APK --> DEX+ APK --> RESOURCES+ APK --> NATIVE+ APK --> MANIFEST++ LIB --> JAVA_PROVIDERS+ RES --> RESOURCES++ DEX --> PROVIDERS+ RESOURCES --> PROVIDERS+ NATIVE --> PROVIDERS++ PROVIDERS --> ANDROID_TC+ ANDROID_TC --> ANDROID_SDK+ ANDROID_TC --> AAPT2+ ANDROID_TC --> D8+ ANDROID_TC --> PROGUARD++ DEX --> PY_TOOLS+ RESOURCES --> PY_TOOLS+ NATIVE --> PY_TOOLS+```++### Component Explanations++- **Build Rules Layer**: High-level build rules that developers use in their+ BUCK files+- **Processing Layer**: Core logic for transforming inputs (Java bytecode,+ resources, native libs) into Android-specific formats+- **Provider Layer**: Data structures that pass information between build rules+ and processing steps+- **Toolchain Layer**: Configuration and integration with external Android+ development tools+- **Utility Tools**: Python and Java utilities that perform specific processing+ tasks+- **External Dependencies**: Android SDK tools and third-party tools integrated+ into the build process++---++## 3. 🔎 Component Breakdown++### Component: Build Rules (`android.bzl`)++**Purpose**: Defines the main Android build rules that developers use in BUCK+files. Acts as the entry point and orchestrates the entire Android build+process.++**Key Elements**:++- `android_apk_impl`: Builds signed APK files from Java code, resources, and+ native libraries+- `android_library_impl`: Compiles Java/Kotlin code into libraries with+ Android-specific processing+- `android_resource_impl`: Processes Android resources (layouts, strings,+ drawables) using AAPT2+- `android_aar_impl`: Creates Android Archive (AAR) files for library+ distribution+- `android_bundle_impl`: Generates Android App Bundles (AAB) for Play Store+ distribution++**Depends On**:++- Internal: All processing modules, providers, toolchain configurations+- External: Android SDK, Java toolchain, native toolchains++### Component: Android Providers (`android_providers.bzl`)++**Purpose**: Defines data structures and providers that carry information+between different build rules and processing steps. Ensures type safety and+structured data flow.++**Key Elements**:++- `AndroidApkInfo`: Contains APK artifact, manifest, and metadata+- `AndroidResourceInfo`: Resource compilation outputs, R.java packages, AAPT2+ artifacts+- `AndroidBinaryNativeLibsInfo`: Native library directories, shared libraries,+ exopackage info+- `DexFilesInfo`: Primary and secondary DEX files with compression metadata+- `AndroidPackageableInfo`: Transitive dependency information for packaging++**Depends On**:++- Internal: Java providers, transitive set utilities+- External: Buck2 provider framework++### Component: DEX Processing (`dex_rules.bzl`)++**Purpose**: Handles conversion of Java bytecode to Android DEX format with+sophisticated multi-DEX splitting, compression, and optimization strategies.++**Key Elements**:++- `get_multi_dex()`: Creates primary and secondary DEX files with weight-based+ splitting+- `merge_to_split_dex()`: Merges pre-dexed libraries into split DEX+ configuration+- `get_single_primary_dex()`: Simple single DEX file generation for smaller apps+- DEX compression strategies: raw, jar, xz, xzs formats++**Depends On**:++- Internal: Android toolchain, Voltron module system, Java DEX utilities+- External: D8/R8 compiler, Android runtime++### Component: Resource Processing (`aapt2_link.bzl`, `android_resource.bzl`)++**Purpose**: Processes Android resources using AAPT2, generates R.java files,+handles resource merging and filtering.++**Key Elements**:++- `aapt2_link()`: Links compiled resources into APK-ready format+- Resource compilation and optimization+- R.java generation with package management+- Asset processing and filtering++**Depends On**:++- Internal: Android toolchain, manifest processing+- External: AAPT2, Android SDK++### Component: Android Toolchain (`android_toolchain.bzl`)++**Purpose**: Configures and provides access to all Android SDK tools and+utilities needed for the build process.++**Key Elements**:++- `AndroidToolchainInfo`: Provider containing all tool references+- Tool configurations: aapt2, d8_command, zipalign, adb, aidl+- Build configuration: android_jar, proguard_jar, framework files+- Utility tools: apk_builder, bundle_builder, duplicate_class_checker++**Depends On**:++- Internal: None (leaf component)+- External: Android SDK, build tools, platform tools++### Component: Python Utility Tools (`tools/`)++**Purpose**: Provides specialized Python scripts for various Android build+processing tasks that require complex logic or file manipulation.++**Key Elements**:++- `duplicate_class_checker.py`: Validates no duplicate classes in DEX files+- `filter_dex.py`: Filters DEX files based on patterns and weight limits+- `unpack_aar.py`: Extracts and processes AAR file contents+- `combine_native_library_dirs.py`: Merges native library directories+- `native_libs_as_assets_metadata.py`: Generates metadata for native libraries+ stored as assets++**Depends On**:++- Internal: Build system file I/O+- External: Python standard library, zipfile, json modules++### Component: Testing Framework (`android_instrumentation_test.bzl`, `robolectric_test.bzl`)++**Purpose**: Provides comprehensive testing capabilities for Android+applications including on-device instrumentation tests and JVM-based Robolectric+tests.++**Key Elements**:++- `android_instrumentation_test_impl`: On-device testing with APK installation+- `robolectric_test_impl`: Fast JVM-based testing with Android framework+ simulation+- Test APK generation and signing+- Test runner integration and result processing++**Depends On**:++- Internal: APK building, Android toolchain, Java testing framework+- External: Android testing framework, Robolectric, ADB++---++## 4. 🔁 Data Flow & Call Flow Examples++### Example Flow: APK Build Process++**Description**: Complete end-to-end process of building a signed APK from+source code, resources, and dependencies. This represents the most common and+comprehensive workflow in the Android build system.++**Sequence Diagram**:++```mermaid+sequenceDiagram+ participant Dev as Developer+ participant Buck as Buck2 Engine+ participant APK as android_apk_impl+ participant Binary as get_binary_info+ participant DEX as DEX Processing+ participant RES as Resource Processing+ participant Tools as Android Tools+ participant SDK as Android SDK++ Dev->>Buck: buck build //app:my_app+ Buck->>APK: Execute android_apk rule+ APK->>Binary: get_binary_info(ctx)++ par Parallel Processing+ Binary->>DEX: Process Java bytecode to DEX+ DEX->>Tools: Run D8 compiler+ Tools->>SDK: Execute d8 command+ SDK-->>Tools: DEX files + metadata+ Tools-->>DEX: Compiled DEX artifacts+ DEX-->>Binary: DexFilesInfo+ and+ Binary->>RES: Process Android resources+ RES->>Tools: Run AAPT2 compile/link+ Tools->>SDK: Execute aapt2 commands+ SDK-->>Tools: Compiled resources APK+ Tools-->>RES: Resource artifacts + R.java+ RES-->>Binary: AndroidBinaryResourcesInfo+ end++ Binary-->>APK: Complete binary info+ APK->>Tools: build_apk() with all artifacts+ Tools->>SDK: Run apk_builder + zipalign+ SDK-->>Tools: Signed APK+ Tools-->>APK: Final APK artifact+ APK-->>Buck: APK + install info+ Buck-->>Dev: Build complete+```++### Example Flow: Multi-DEX Processing++**Description**: Process of splitting Java bytecode into primary and secondary+DEX files based on patterns and weight limits, with support for different+compression strategies.++**Sequence Diagram**:++```mermaid+sequenceDiagram+ participant Build as Build Rule+ participant MultiDex as get_multi_dex+ participant Filter as filter_dex_class_names+ participant D8 as D8 Tool+ participant Compress as Compression Tool++ Build->>MultiDex: Java library JARs + patterns+ MultiDex->>Filter: Filter classes by primary_dex_patterns+ Filter-->>MultiDex: Primary vs secondary class lists++ par Primary DEX+ MultiDex->>D8: Compile primary classes+ D8-->>MultiDex: classes.dex+ and Secondary DEX Processing+ loop For each secondary DEX+ MultiDex->>D8: Compile secondary classes batch+ D8-->>MultiDex: classes2.dex, classes3.dex, etc.+ MultiDex->>Compress: Apply compression (jar/xz/xzs)+ Compress-->>MultiDex: Compressed secondary DEX+ end+ end++ MultiDex-->>Build: DexFilesInfo with all DEX files+```++---++## 5. 🗃️ Data Models (Entities)++### Entity: AndroidApkInfo++- **Provider**: AndroidApkInfo+- **Fields**:+ - `apk: Artifact` – The final signed APK file+ - `manifest: Artifact` – Processed AndroidManifest.xml+ - `materialized_artifacts: list[Artifact]` – All build artifacts for debugging+ - `unstripped_shared_libraries: Artifact` – Debug symbols for native libraries++- **Relations**:+ - Used by installation and testing rules+ - Contains references to all build artifacts++- **Notes**: Primary output provider for android_apk and android_binary rules++### Entity: AndroidResourceInfo++- **Provider**: AndroidResourceInfo+- **Fields**:+ - `raw_target: TargetLabel` – Target that produced this resource+ - `aapt2_compile_output: Artifact` – Compiled resource artifacts from AAPT2+ - `res: Artifact` – Raw resource directory or mapping+ - `assets: Artifact` – Asset files directory or mapping+ - `r_dot_java_package: str` – Package name for R.java generation+ - `text_symbols: Artifact` – Symbol definitions for resource linking+ - `manifest_file: Artifact` – Associated AndroidManifest.xml++- **Relations**:+ - Aggregated by AndroidPackageableInfo+ - Used by resource linking process+ - Referenced by APK and AAR generation++- **Notes**: Represents processed Android resources with AAPT2 compilation+ outputs++### Entity: DexFilesInfo++- **Record**: DexFilesInfo+- **Fields**:+ - `primary_dex: Artifact` – Main classes.dex file+ - `primary_dex_class_names: Artifact` – List of classes in primary DEX+ - `root_module_secondary_dex_dirs: list[Artifact]` – Secondary DEX directories+ for root module+ - `non_root_module_secondary_dex_dirs: list[Artifact]` – Secondary DEX for+ feature modules+ - `secondary_dex_exopackage_info: ExopackageDexInfo` – Exopackage metadata for+ dynamic loading+ - `proguard_text_files_path: Artifact` – ProGuard mapping files++- **Relations**:+ - Used by APK building process+ - Contains exopackage information for dynamic loading+ - References ProGuard optimization outputs++- **Notes**: Central data structure for DEX file management with multi-DEX and+ exopackage support++### Entity: AndroidPackageableInfo++- **Provider**: AndroidPackageableInfo+- **Fields**:+ - `target_label: TargetLabel` – Target producing this info+ - `build_config_infos: AndroidBuildConfigInfoTSet` – Transitive build+ configurations+ - `deps: AndroidDepsTSet` – Transitive dependency information+ - `manifests: ManifestTSet` – Transitive manifest files+ - `resource_infos: ResourceInfoTSet` – Transitive resource information+ - `prebuilt_native_library_dirs: PrebuiltNativeLibraryDirTSet` – Transitive+ native libraries++- **Relations**:+ - Aggregates information from all transitive dependencies+ - Used by binary rules for packaging decisions+ - Contains transitive sets for efficient dependency management++- **Notes**: Core provider for dependency aggregation using Buck2's transitive+ set system++### Entity: AndroidToolchainInfo++- **Provider**: AndroidToolchainInfo+- **Fields**:+ - `aapt2: RunInfo` – AAPT2 resource compiler tool+ - `d8_command: RunInfo` – D8 DEX compiler+ - `android_jar: Artifact` – Android SDK JAR file+ - `apk_builder: RunInfo` – APK assembly and signing tool+ - `zipalign: RunInfo` – APK optimization tool+ - `proguard_jar: Artifact` – ProGuard obfuscation tool+ - `duplicate_class_checker: RunInfo` – Validation tool for duplicate classes+ - `installer: RunInfo` – APK installation tool++- **Relations**:+ - Used by all Android build rules+ - Provides access to external Android SDK tools+ - Configured by toolchain setup rules++- **Notes**: Central configuration point for all Android development tools and+ SDK integration
@@ -0,0 +1,115 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Extra relinker outputs support (e.g., LLVM stats).++Reads from ctx.attrs.extra_relinker_outputs attribute (not buck config directly).+Buck config is read at macro level and translated to attribute value.+"""++load("@prelude//linking:link_info.bzl", "ExtraLinkerOutputs")+load("@prelude//utils:arglike.bzl", "ArgLike") # @unused Used as a type++def _llvm_stats_outputs_factory(output_path: str) -> typing.Callable:+ """Factory for relinker LLVM stats outputs."""++ def factory(ctx: AnalysisContext) -> ExtraLinkerOutputs:+ stats_file = ctx.actions.declare_output(output_path + ".stats", has_content_based_path = False)+ return ExtraLinkerOutputs(+ artifacts = {"llvm-stats": stats_file},+ providers = {"llvm-stats": [DefaultInfo(default_output = stats_file)]},+ )++ return factory++def _llvm_stats_flags_factory() -> typing.Callable:+ """Factory for relinker LLVM stats linker flags."""++ def factory(_ctx: AnalysisContext, outputs: dict[str, Artifact]) -> list[ArgLike]:+ return [+ cmd_args(outputs["llvm-stats"].as_output(), format = "-Wl,-plugin-opt=stats-file={}"),+ ]++ return factory++def _preinline_ir_outputs_factory(output_path: str) -> typing.Callable:+ """Factory for the relinker pre-inline IR (.ll) output."""++ def factory(ctx: AnalysisContext) -> ExtraLinkerOutputs:+ ir_file = ctx.actions.declare_output(output_path + ".preinline.ll", has_content_based_path = False)+ return ExtraLinkerOutputs(+ artifacts = {"preinline-ir": ir_file},+ providers = {"preinline-ir": [DefaultInfo(default_output = ir_file)]},+ )++ return factory++def _preinline_ir_flags_factory() -> typing.Callable:+ """Factory for the relinker pre-inline IR linker flags.++ Threads the gator `-full-lto-postlink-preinline-ir-dump=<file>` mllvm option+ into the LTO backend. `.as_output()` is what registers the linker-written+ file as a tracked, materializable buck output (a bare `-Wl,-mllvm` string+ would be discarded by RE)."""++ def factory(_ctx: AnalysisContext, outputs: dict[str, Artifact]) -> list[ArgLike]:+ return [+ cmd_args(+ outputs["preinline-ir"].as_output(),+ format = "-Wl,-mllvm,-full-lto-postlink-preinline-ir-dump={}",+ ),+ ]++ return factory++def _get_extra_relinker_output_types(ctx: AnalysisContext) -> list[str]:+ """Get list of enabled extra relinker output types from attribute."""+ return getattr(ctx.attrs, "extra_relinker_outputs", [])++def get_extra_relinker_args(ctx: AnalysisContext, output_path: str, soname: str = "") -> dict[str, typing.Any]:+ """Get extra linker outputs factory dict for all enabled relinker outputs.++ `soname` scopes the (multi-GB) pre-inline IR dump: when `preinline_ir_sonames`+ is set, only libraries in that allowlist emit the dump output+flag, so a whole+ -app build does not dump every library. An empty allowlist keeps legacy+ behavior (every relinked library dumps)."""+ output_types = _get_extra_relinker_output_types(ctx)+ allowlist = getattr(ctx.attrs, "preinline_ir_sonames", [])+ if allowlist and "preinline-ir" in output_types and soname not in allowlist:+ output_types = [t for t in output_types if t != "preinline-ir"]+ if not output_types:+ return {}++ def combined_outputs_factory(ctx: AnalysisContext) -> ExtraLinkerOutputs:+ artifacts = {}+ providers = {}+ for output_type in output_types:+ if output_type == "llvm-stats":+ result = _llvm_stats_outputs_factory(output_path)(ctx)+ artifacts |= result.artifacts+ providers |= result.providers+ elif output_type == "preinline-ir":+ result = _preinline_ir_outputs_factory(output_path)(ctx)+ artifacts |= result.artifacts+ providers |= result.providers+ return ExtraLinkerOutputs(artifacts = artifacts, providers = providers)++ def combined_flags_factory(ctx: AnalysisContext, outputs: dict[str, Artifact]) -> list[ArgLike]:+ flags = []+ for output_type in output_types:+ if output_type == "llvm-stats":+ flags += _llvm_stats_flags_factory()(ctx, outputs)+ elif output_type == "preinline-ir":+ flags += _preinline_ir_flags_factory()(ctx, outputs)+ return flags++ return {+ "extra_linker_outputs_factory": combined_outputs_factory,+ "extra_linker_outputs_flags_factory": combined_flags_factory,+ }
@@ -0,0 +1,158 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//android:android_binary_resources_rules.bzl", "get_android_binary_resources_info")+load("@prelude//android:android_library.bzl", "android_target_stats", "build_android_library", "optional_jars")+load("@prelude//android:android_providers.bzl", "merge_android_packageable_info")+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//java:java_providers.bzl", "JavaLibraryInfo")+load("@prelude//java:java_test.bzl", "build_junit_test")+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")+load("@prelude//test:inject_test_run_info.bzl", "inject_test_run_info")+load("@prelude//utils:expect.bzl", "expect")++def _target_build_file_path(target):+ cell = "" if target.cell in ["", "fbsource"] else target.cell + "/"+ package = target.package + "/" if target.package else ""+ return cell + package + "BUCK"++def robolectric_test_impl(ctx: AnalysisContext) -> list[Provider]:+ if ctx.attrs._build_only_native_code:+ return [DefaultInfo()]++ extra_cmds = []++ # Force robolectric to only use local dependency resolution.+ extra_cmds.append("-Drobolectric.offline=true")+ if ctx.attrs.robolectric_runtime_dependency:+ runtime_dependencies_dir = ctx.attrs.robolectric_runtime_dependency+ elif ctx.attrs.robolectric_runtime_dependencies:+ runtime_dependencies_dir = ctx.actions.symlinked_dir(+ "runtime_dependencies",+ {runtime_dep.basename: runtime_dep for runtime_dep in ctx.attrs.robolectric_runtime_dependencies},+ has_content_based_path = False,+ )+ else:+ runtime_dependencies_dir = None++ if runtime_dependencies_dir:+ extra_cmds.append(cmd_args(runtime_dependencies_dir, format = "-Drobolectric.dependency.dir={}"))++ all_packaging_deps = ctx.attrs.deps + ctx.attrs.exported_deps + ctx.attrs.runtime_deps+ android_packageable_info = merge_android_packageable_info(ctx.label, ctx.actions, all_packaging_deps)+ resources_info = get_android_binary_resources_info(+ ctx,+ all_packaging_deps,+ android_packageable_info,+ java_packaging_deps = [], # Only used for third-party jar resources, which we don't care about here.+ use_proto_format = False,+ referenced_resources_lists = [],+ generate_strings_and_ids_separately = False,+ aapt2_preferred_density = ctx.attrs.preferred_density_for_binary_resources,+ manifest_entries = ctx.attrs.manifest_entries,+ )++ resource_source_map = None+ resource_source_map_jar = ctx.attrs.env.get("ROBOLECTRIC_RESOURCE_SOURCE_MAP_JAR")+ if resource_source_map_jar:+ resource_infos = [resource for resource in resources_info.unfiltered_resource_infos if resource.res != None]+ resource_dirs = [cmd_args([resource.res, _target_build_file_path(resource.raw_target)], delimiter = "\t") for resource in resource_infos]+ resource_dirs_file = ctx.actions.write("resource_source_map_resource_dirs", resource_dirs, has_content_based_path = False)+ asset_infos = [+ (asset, _target_build_file_path(resource.raw_target)) for resource in resources_info.unfiltered_resource_infos for asset in resource.assets+ ]+ asset_dirs = [cmd_args([asset, owner_build_file], delimiter = "\t") for asset, owner_build_file in asset_infos]+ asset_dirs_file = ctx.actions.write("resource_source_map_asset_dirs", asset_dirs, has_content_based_path = False)+ resource_source_map = ctx.actions.declare_output("resource_source_map.tsv", has_content_based_path = False)+ resource_source_map_cmd = cmd_args([+ ctx.attrs._java_toolchain[JavaToolchainInfo].java[RunInfo],+ "-jar",+ resource_source_map_jar,+ "--resource-dirs",+ resource_dirs_file,+ "--asset-dirs",+ asset_dirs_file,+ "--output",+ resource_source_map.as_output(),+ ])+ resource_source_map_cmd.add(cmd_args(hidden = [resource.res for resource in resource_infos] + [asset for asset, _ in asset_infos]))+ ctx.actions.run(resource_source_map_cmd, category = "robolectric_resource_source_map", allow_cache_upload = True)++ test_config_properties_file = ctx.actions.write(+ "test_config.properties",+ [+ # Replace \ with \\ for Windows compatibility+ cmd_args(["android_resource_apk", resources_info.primary_resources_apk], delimiter = "=", replace_regex = ("\\\\\\b", "\\\\")),+ cmd_args(["android_merged_manifest", resources_info.manifest], delimiter = "=", replace_regex = ("\\\\\\b", "\\\\")),+ ]+ + (+ [cmd_args(["robolectric_resource_source_map", resource_source_map], delimiter = "=", replace_regex = ("\\\\\\b", "\\\\"))]+ if resource_source_map+ else []+ ),+ has_content_based_path = False,+ )++ # Robolectric looks for a file named /com/android/tools/test_config.properties on the classpath+ test_config_symlinked_dir = ctx.actions.symlinked_dir(+ "test_config_symlinked_dir", {"com/android/tools/test_config.properties": test_config_properties_file}, has_content_based_path = False+ )+ test_config_properties_jar = ctx.actions.declare_output("test_config_properties.jar", has_content_based_path = False)+ jar_cmd = cmd_args([+ ctx.attrs._java_toolchain[JavaToolchainInfo].jar,+ "-cfM", # -c: create new archive, -f: specify the file name, -M: do not create a manifest+ test_config_properties_jar.as_output(),+ "-C",+ test_config_symlinked_dir,+ ".",+ ])+ ctx.actions.run(jar_cmd, category = "test_config_properties_jar_cmd")+ extra_cmds.append(cmd_args(hidden = [resources_info.primary_resources_apk, resources_info.manifest] + ([resource_source_map] if resource_source_map else [])))++ r_dot_javas = [r_dot_java.library_info for r_dot_java in resources_info.r_dot_java_infos if r_dot_java.library_info.library_output]+ expect(len(r_dot_javas) <= 1, "android_library only works with single R.java")++ target_stats_providers, extra_sub_targets = android_target_stats(ctx)+ if resource_source_map:+ extra_sub_targets["resource_source_map"] = [DefaultInfo(default_output = resource_source_map)]+ if r_dot_javas:+ r_dot_java = r_dot_javas[0]+ extra_sub_targets["r_dot_java"] = [DefaultInfo(default_output = r_dot_java.library_output.full_library)]+ else:+ r_dot_java = None+ java_providers, _ = build_android_library(ctx, r_dot_java = r_dot_java, extra_sub_targets = extra_sub_targets)++ extra_classpath_entries = [test_config_properties_jar] + ctx.attrs._android_toolchain[AndroidToolchainInfo].android_bootclasspath + optional_jars(ctx)+ extra_classpath_entries.extend([r_dot_java.library_output.full_library for r_dot_java in r_dot_javas])+ external_runner_test_info = build_junit_test(+ ctx,+ java_providers.java_library_info,+ java_providers.java_packaging_info,+ java_providers.class_to_src_map,+ extra_cmds = extra_cmds,+ extra_classpath_entries = extra_classpath_entries,+ )++ providers = inject_test_run_info(ctx, external_runner_test_info) + [+ java_providers.java_library_intellij_info,+ java_providers.java_packaging_info,+ java_providers.template_placeholder_info,+ java_providers.default_info,+ java_providers.class_to_src_map,+ java_providers.java_global_code_info,+ ]++ java_library_without_compiling_deps = JavaLibraryInfo(+ compiling_deps = None,+ library_output = java_providers.java_library_info.library_output,+ output_for_classpath_macro = java_providers.java_library_info.output_for_classpath_macro,+ )+ providers.append(java_library_without_compiling_deps)+ providers.extend(target_stats_providers)++ return providers
@@ -0,0 +1,133 @@+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("build_infra")++source_listing()++prelude = native # Avoid warnings and auto-formatters++prelude.python_bootstrap_binary(+ name = "duplicate_class_checker",+ main = "duplicate_class_checker.py",+ visibility = ["PUBLIC"],+ deps = [+ "prelude//java/tools:utils_lib",+ ],+)++prelude.python_bootstrap_binary(+ name = "consolidate_class_names",+ main = "consolidate_class_names.py",+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "unpack_aar",+ main = "unpack_aar.py",+ visibility = ["PUBLIC"],+ deps = [+ "prelude//java/tools:utils_lib",+ ],+)++prelude.python_bootstrap_binary(+ name = "filter_dex",+ main = "filter_dex.py",+ visibility = ["PUBLIC"],+)++prelude.python_library(+ name = "filter_dex_lib",+ srcs = ["filter_dex.py"],+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "sort_pre_dexed_files",+ main = "sort_pre_dexed_files.py",+ visibility = ["PUBLIC"],+)++prelude.python_library(+ name = "sort_pre_dexed_files_lib",+ srcs = ["sort_pre_dexed_files.py"],+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "combine_native_library_dirs",+ main = "combine_native_library_dirs.py",+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "filter_prebuilt_native_library_dir",+ main = "filter_prebuilt_native_library_dir.py",+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "native_libs_as_assets_metadata",+ main = "native_libs_as_assets_metadata.py",+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "compute_merge_sequence",+ main = "merge_sequence.py",+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "filter_extra_resources",+ main = "filter_extra_resources.py",+ visibility = ["PUBLIC"],+ deps = [+ "prelude//java/tools:utils_lib",+ ],+)++prelude.zip_file(+ name = "app_without_resources_stub",+ srcs = ["com/facebook/buck_generated/AppWithoutResourcesStub.java"],+ out = "app_without_resources_stub.src.zip",+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "create_jdk_system_image",+ main = "create_jdk_system_image.py",+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "combine_apk_with_relinked_libs",+ main = "combine_apk_with_relinked_libs.py",+ visibility = ["PUBLIC"],+)++prelude.python_library(+ name = "combine_apk_with_relinked_libs_lib",+ srcs = ["combine_apk_with_relinked_libs.py"],+ visibility = ["PUBLIC"],+)++# Type checking target for Python tool scripts+prelude.python_library(+ name = "scripts-typing",+ srcs = [+ "combine_apk_with_relinked_libs.py",+ "combine_native_library_dirs.py",+ "consolidate_class_names.py",+ "create_jdk_system_image.py",+ "duplicate_class_checker.py",+ "filter_dex.py",+ "filter_extra_resources.py",+ "filter_prebuilt_native_library_dir.py",+ "merge_sequence.py",+ "native_libs_as_assets_metadata.py",+ "sort_pre_dexed_files.py",+ "unpack_aar.py",+ ],+ typing = True,+)
@@ -0,0 +1,13 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is dual-licensed under either the MIT license found in the+ * LICENSE-MIT file in the root directory of this source tree or the Apache+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory+ * of this source tree. You may select, at your option, one of the+ * above-listed licenses.+ */++package com.facebook.buck_generated;++final class AppWithoutResourcesStub {}
@@ -0,0 +1,192 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""Combine an APK/AAB with relinked native libraries.++Replaces the un-relinked .so files in the input APK/AAB with their+relinked counterparts. A JSON mapping file specifies which libraries+to replace, keyed by <abi>/<soname> (e.g. "arm64-v8a/libfoo.so").++The mapping is produced by the build system and consumed here, so the+script doesn't need to discover or infer what to replace.++Handles .so files at all possible packaging locations:+ - lib/<abi>/<soname> (standard)+ - assets/lib/<abi>/<soname> (asset libraries)+ - assets/<module>/lib/<abi>/<soname> (Voltron module libs)+ - assets/<module>/assets/<abi>/<soname> (Voltron module assets)+ - Inside nested ZIP/JAR files (module containers)++Usage:+ combine_apk_with_relinked_libs.py \+ --input input.apk \+ --relinked-libs-dir /path/to/relinked_libs \+ --mapping /path/to/mapping.json \+ --output output.apk+"""++import argparse+import io+import json+import os+import shutil+import zipfile+++def _build_relinked_lookup(+ mapping: list[str],+ relinked_libs_dir: str,+) -> dict[str, str]:+ """Build a lookup dict from the mapping list.++ Args:+ mapping: List of "<abi>/<soname>" strings from the build system.+ relinked_libs_dir: Base directory containing the relinked .so files.++ Returns:+ Dict mapping "<abi>/<soname>" to the absolute filesystem path.+ """+ lookup = {}+ for abi_soname in mapping:+ path = os.path.join(relinked_libs_dir, abi_soname)+ if not os.path.isfile(path):+ raise RuntimeError(+ "Relinked library not found: {} (expected at {})".format(+ abi_soname, path+ )+ )+ lookup[abi_soname] = path+ return lookup+++def _find_matching_key(+ zip_entry: str,+ relinked_lookup: dict[str, str],+) -> str | None:+ """Find the mapping key that matches a ZIP entry path.++ Keys are always <abi>/<soname> (exactly two path components), so we+ extract the last two components of the zip entry and do a direct+ dict lookup — O(1) per entry instead of O(M) linear scan.++ Note: suffix matching is intentional — the same <abi>/<soname> may appear+ at multiple packaging locations (lib/, assets/lib/, assets/<module>/lib/,+ etc.) and all occurrences should be replaced with the same relinked binary.+ """+ parts = zip_entry.rsplit("/", 2)+ if len(parts) >= 2:+ candidate = parts[-2] + "/" + parts[-1]+ if candidate in relinked_lookup:+ return candidate+ return None+++def _maybe_rebuild_inner_zip(+ inner_bytes: bytes,+ relinked_lookup: dict[str, str],+) -> tuple[bytes, set[str]] | None:+ """Rebuild a nested ZIP, replacing any .so entries with relinked versions.++ Returns a tuple of (rebuilt bytes, set of replaced keys) if any+ replacements were made, or None if the inner ZIP has no matching+ entries (or is not a valid ZIP). This avoids parsing the same ZIP+ twice (once to check, once to rebuild).+ """+ try:+ buf = io.BytesIO(inner_bytes)+ with zipfile.ZipFile(buf, "r") as zin:+ has_match = any(+ _find_matching_key(info.filename, relinked_lookup)+ for info in zin.infolist()+ )+ if not has_match:+ return None+ inner_replaced: set[str] = set()+ out = io.BytesIO()+ with zipfile.ZipFile(out, "w") as zout:+ for info in zin.infolist():+ key = _find_matching_key(info.filename, relinked_lookup)+ if key is not None:+ with open(relinked_lookup[key], "rb") as f:+ zout.writestr(info, f.read())+ inner_replaced.add(key)+ else:+ zout.writestr(info, zin.read(info.filename))+ return out.getvalue(), inner_replaced+ except zipfile.BadZipFile:+ return None+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="Replace .so files in an APK/AAB with relinked versions."+ )+ parser.add_argument(+ "--input",+ required=True,+ help="Path to the input APK/AAB",+ )+ parser.add_argument(+ "--relinked-libs-dir",+ required=True,+ help="Path to directory containing relinked .so files (structure: <abi>/<soname>)",+ )+ parser.add_argument(+ "--mapping",+ required=True,+ help="Path to JSON file listing <abi>/<soname> entries to replace",+ )+ parser.add_argument(+ "--output",+ required=True,+ help="Path to write the combined output APK/AAB",+ )+ args = parser.parse_args()++ with open(args.mapping) as f:+ mapping = json.load(f)++ relinked_lookup = _build_relinked_lookup(mapping, args.relinked_libs_dir)++ if not relinked_lookup:+ shutil.copy2(args.input, args.output)+ return++ replaced: set[str] = set()+ with zipfile.ZipFile(args.input, "r") as zin:+ with zipfile.ZipFile(args.output, "w") as zout:+ for info in zin.infolist():+ key = _find_matching_key(info.filename, relinked_lookup)+ if key is not None:+ with open(relinked_lookup[key], "rb") as f:+ data = f.read()+ zout.writestr(info, data)+ replaced.add(key)+ elif info.filename.endswith((".jar", ".zip")):+ inner_bytes = zin.read(info.filename)+ result = _maybe_rebuild_inner_zip(inner_bytes, relinked_lookup)+ if result is not None:+ rebuilt, inner_replaced = result+ zout.writestr(info, rebuilt)+ replaced.update(inner_replaced)+ else:+ zout.writestr(info, inner_bytes)+ else:+ zout.writestr(info, zin.read(info.filename))++ not_replaced = set(relinked_lookup.keys()) - replaced+ if not_replaced:+ raise RuntimeError(+ "Relinked libraries not found in input: {}".format(+ ", ".join(sorted(not_replaced))+ )+ )+++if __name__ == "__main__":+ main()
@@ -0,0 +1,97 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.+++import argparse+import hashlib+import os+from pathlib import Path+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="Combine the native libraries in different directories into a single symlink"+ )+ parser.add_argument(+ "--library-dirs",+ type=Path,+ nargs="+",+ help="Paths to the dirs that should be combined",+ required=True,+ )+ parser.add_argument(+ "--subdir",+ type=Path,+ help="The subdirectory inside the dirs to combine",+ )+ parser.add_argument(+ "--output-dir",+ type=Path,+ required=True,+ )+ parser.add_argument(+ "--metadata-file",+ type=Path,+ required=False,+ )+ parser.add_argument(+ "--pick-first",+ type=str,+ nargs="+",+ help="Library names to pick the first if duplicated",+ )+ args = parser.parse_args()++ metadata_lines = []++ args.output_dir.mkdir(parents=True)+ for library_dir in args.library_dirs:+ if args.subdir:+ library_dir = library_dir / args.subdir+ all_libs = library_dir.glob("**/*.s[o|h]")+ for lib in all_libs:+ relative_path = lib.relative_to(library_dir)+ output_path = args.output_dir / relative_path++ if output_path.exists():+ if (+ args.pick_first+ and os.path.basename(relative_path) in args.pick_first+ ):+ continue+ else:+ raise AssertionError(+ "Duplicate library name: {}! Source1: {}, source2: {}".format(+ output_path.name,+ os.path.realpath(output_path),+ lib,+ )+ )++ output_path.parent.mkdir(exist_ok=True, parents=True)+ relative_path_to_lib = os.path.relpath(+ os.path.realpath(lib),+ start=os.path.realpath(os.path.dirname(output_path)),+ )+ output_path.symlink_to(relative_path_to_lib)++ if args.metadata_file:+ with open(lib, "rb") as f:+ metadata_lines.append(+ "{} {}".format(+ relative_path, hashlib.sha1(f.read()).hexdigest()+ )+ )++ if args.metadata_file:+ with open(args.metadata_file, "w") as f:+ f.write("\n".join(metadata_lines))+++if __name__ == "__main__":+ main()
@@ -0,0 +1,103 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Consolidates multiple class name files into a single JSON file.++This tool reads a mapping of target names to class name file paths,+reads each file, and outputs a consolidated JSON containing all+class names directly. This reduces the number of file reads required+by downstream tools.++Additionally, this tool builds a reverse map (class -> target) to detect+duplicate classes within the batch. If duplicates are found, it fails fast+with an error message. This allows earlier detection of duplicate classes+compared to waiting for the global duplicate_class_checker.py to run.++Input format (JSON):+{+ "target_name1": "path/to/class_names1.txt",+ "target_name2": "path/to/class_names2.txt",+ ...+}++Output format (JSON):+{+ "target_name1": ["com/example/Class1", "com/example/Class2"],+ "target_name2": ["com/other/Class3"],+ ...+}+"""++import argparse+import json+from pathlib import Path+from typing import Dict, List+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="Consolidate multiple class name files into a single JSON file."+ )+ parser.add_argument(+ "--input-mapping-file",+ type=Path,+ required=True,+ help="JSON file mapping target names to class name file paths.",+ )+ parser.add_argument(+ "--output-file",+ type=Path,+ required=True,+ help="Output JSON file with consolidated class names.",+ )+ args = parser.parse_args()++ # Read the input mapping+ with open(args.input_mapping_file) as f:+ target_to_file_map: Dict[str, str] = json.load(f)++ # Read each class names file and build consolidated mapping+ # Also build reverse map to detect duplicates within this batch+ consolidated: Dict[str, List[str]] = {}+ class_to_target: Dict[str, str] = {}+ duplicates: Dict[str, List[str]] = {}++ for target_name, file_path in target_to_file_map.items():+ with open(file_path) as f:+ # Read class names, stripping whitespace+ class_names = [line.strip() for line in f if line.strip()]+ consolidated[target_name] = class_names++ # Check for duplicates within this batch+ # Skip inner classes and module-info (same filtering as duplicate_class_checker.py)+ for class_name in class_names:+ if "$" in class_name or "module-info" in class_name:+ continue+ if class_name in class_to_target:+ # Found a duplicate+ if class_name not in duplicates:+ duplicates[class_name] = [class_to_target[class_name]]+ duplicates[class_name].append(target_name)+ else:+ class_to_target[class_name] = target_name++ # Fail fast if duplicates found within this batch+ if duplicates:+ error_lines = ["Duplicate class names found within batch:"]+ for class_name, targets in sorted(duplicates.items()):+ error_lines.append(f" {class_name} exists in: {', '.join(targets)}")+ raise SystemExit("\n".join(error_lines))++ # Write consolidated output+ with open(args.output_file, "w") as f:+ json.dump(consolidated, f)+++if __name__ == "__main__":+ main()
@@ -0,0 +1,302 @@+#!/usr/bin/python3+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Converts core-for-system-modules.jar from Android SDK release to a Java system image+given to the --system flag for when compiling for Java target 9+.++This entire script is translated from Gradle:+https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:build-system/gradle-core/src/main/java/com/android/build/gradle/internal/dependency/JdkImageTransformDelegate.kt++See also the equivalent feature in Bazel Android build rules:+https://github.com/bazelbuild/rules_android/commit/20c8e5bef957a2334346490934bf3dc54942457c++New comments are marked with "META:"+"""++from __future__ import annotations++import argparse+import os+import re+import shutil+import subprocess+import sys+import tempfile+import zipfile+from pathlib import Path+from typing import List+++# META: Translation of ProcessBuilder. Note some tools print error to stdout so print both+# stdout+stderr on failure.+def run_subprocess(args: List[str]) -> bytes:+ try:+ return subprocess.check_output(args, stderr=subprocess.PIPE)+ except subprocess.CalledProcessError as e:+ print(f"Failed to run {args}: exit code={e.returncode}", file=sys.stderr)+ if e.stdout:+ print("stdout:", file=sys.stderr)+ print(e.stdout.decode("utf-8"), file=sys.stderr)+ if e.stderr:+ print("stderr:", file=sys.stderr)+ print(e.stderr.decode("utf-8"), file=sys.stderr)+ sys.exit(1)+++class JdkImageTransformDelegate:+ def __init__(+ self,+ system_modules_jar: Path,+ work_dir: Path,+ out_dir: Path,+ jdk_tools: JdkTools,+ ):+ self.system_modules_jar = system_modules_jar+ self.work_dir = work_dir+ self.out_dir = out_dir+ self.jdk_tools = jdk_tools++ def run(self):+ """+ Links a JDK Image from [system_modules_jar] in [out_dir], using [work_dir]+ for the output of any intermediate operations. This is done via the "jlink" tool+ as exposed by [jdk_tools].+ """++ # jlink takes a directory of JMOD files as inputs+ jmod_file = self.make_jmod_file()+ jmod_dir = jmod_file.parent++ self.jdk_tools.link_jmods_into_jdk_image(jmod_dir, "java.base", self.out_dir)++ copy_jrt_fs_jar(self.out_dir, self.jdk_tools)++ def make_module_descriptor_java(self) -> Path:+ """+ Creates a "module-info.java" file describing the contents of system_modules_jar+ """+ module_info_java_content = generate_module_descriptor(+ "java.base", [self.system_modules_jar]+ )+ module_info_java = self.work_dir / "module-info.java"+ with open(module_info_java, "w") as f:+ f.write(module_info_java_content)++ return module_info_java++ def make_module_info_class(self) -> Path:+ """+ Creates and compiles a "module-info.class" file describing the contents of system_modules_jar+ """+ module_info_java = self.make_module_descriptor_java()+ self.jdk_tools.compile_module_descriptor(+ module_info_java, self.system_modules_jar, self.work_dir+ )++ module_info_class = self.work_dir / "module-info.class"+ assert module_info_class.exists(), (+ f"Expected compiled module descriptor file to be created at {module_info_class}"+ )++ return module_info_class++ def make_module_jar(self, work_dir: Path) -> Path:+ """+ Creates a Modular Jar from [system_modules_jar] by compiling and adding a module descriptor+ """+ module_info_class = self.make_module_info_class()++ module_jar = work_dir / "module.jar"+ create_jar(+ self.jdk_tools.java,+ self.jdk_tools.jar_builder,+ module_info_class,+ [self.system_modules_jar],+ module_jar,+ )++ return module_jar++ def make_jmod_file(self) -> Path:+ module_name = "java.base"+ jlink_version = self.jdk_tools.jlink_version()+ jmod_dir = self.work_dir / "jmod"+ os.mkdir(jmod_dir)+ jmod_file = jmod_dir / f"{module_name}.jmod"++ module_jar = self.make_module_jar(self.work_dir)++ self.jdk_tools.create_jmod_from_modular_jar(+ jmod_file, jlink_version, module_jar+ )++ return jmod_file+++class JdkTools:+ def __init__(+ self,+ java: Path,+ javac: Path,+ jlink: Path,+ jmod: Path,+ jrt_fs_jar: Path,+ jar_builder: Path,+ ):+ self.java = java+ self.javac = javac+ self.jlink = jlink+ self.jmod = jmod+ self.jrt_fs_location = jrt_fs_jar+ self.jar_builder = jar_builder++ def jlink_version(self):+ return run_subprocess([self.jlink, "--version"]).decode("utf-8").strip()++ def compile_module_descriptor(+ self, module_info_java: Path, system_modules_jar: Path, out_dir: Path+ ):+ classpath_arg_value = str(system_modules_jar)++ run_subprocess(+ [+ self.javac,+ "--system=none",+ f"--patch-module=java.base={classpath_arg_value}",+ "-d",+ out_dir,+ module_info_java,+ ]+ )++ def create_jmod_from_modular_jar(+ self, jmod_file: Path, jlink_version: str, module_jar: Path+ ):+ run_subprocess(+ [+ self.jmod,+ "create",+ "--module-version",+ jlink_version,+ # Use LINUX-OTHER to be compatible with JDK 21+ b/294137077+ "--target-platform",+ "LINUX-OTHER",+ "--class-path",+ module_jar,+ jmod_file,+ ]+ )++ def link_jmods_into_jdk_image(+ self, jmod_dir: Path, module_name: str, out_dir: Path+ ):+ run_subprocess(+ [+ self.jlink,+ "--module-path",+ jmod_dir,+ "--add-modules",+ module_name,+ "--output",+ out_dir,+ "--disable-plugin",+ "system-modules",+ ]+ )+++def generate_module_descriptor(moduleName: str, jars: List[Path]) -> str:+ string_builder = ""+ string_builder += f"module {moduleName} {{\n"+ package_name_regex = r"(.*)/[^/]*.class"+ for jar in jars:+ with zipfile.ZipFile(jar) as jar_zip:+ entry_names = [entry.filename for entry in jar_zip.infolist()]+ package_names = set()+ for entry in entry_names:+ match = re.match(package_name_regex, entry)+ if match:+ package = match.group(1).replace("/", ".")+ package_names.add(package)+ for package in sorted(package_names):+ string_builder += f" exports {package};\n"+ string_builder += "}\n"+ return string_builder+++def create_jar(+ java: Path,+ jar_builder: Path,+ module_info_class: Path,+ in_jars: List[Path],+ output_jar: Path,+):+ # META: Our JarBuilder is similar to JarFlinger+ run_subprocess(+ [+ java,+ "-jar",+ jar_builder,+ "--class-files",+ f"{module_info_class.name}:{module_info_class}",+ # META: Our jar builder only supports one append-jar+ "--append-jar",+ in_jars[0],+ "--output",+ output_jar,+ ]+ )+++def copy_jrt_fs_jar(out_dir: Path, jdk_tools: JdkTools):+ source = jdk_tools.jrt_fs_location++ copied_libs_dir = out_dir / "lib"+ os.makedirs(copied_libs_dir, exist_ok=True)+ destination = copied_libs_dir / source.name++ # META: Skip manifest.mf filtering since it is not applicable to us+ shutil.copy(source, destination)+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--core-for-system-modules-jar", required=True)+ parser.add_argument("--java", required=True)+ parser.add_argument("--javac", required=True)+ parser.add_argument("--jlink", required=True)+ parser.add_argument("--jmod", required=True)+ parser.add_argument("--jrt-fs-jar", required=True)+ parser.add_argument("--jar-builder", required=True)+ parser.add_argument("--output", required=True)+ args = parser.parse_args()++ jdk_tools = JdkTools(+ args.java,+ Path(args.javac),+ Path(args.jlink),+ Path(args.jmod),+ Path(args.jrt_fs_jar),+ Path(args.jar_builder),+ )++ work_dir = tempfile.mkdtemp()+ JdkImageTransformDelegate(+ args.core_for_system_modules_jar,+ Path(work_dir),+ Path(args.output),+ jdk_tools,+ ).run()++ return 0+++if __name__ == "__main__":+ sys.exit(main())
@@ -0,0 +1,168 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import argparse+import json+import sys+import zipfile+from pathlib import Path+from typing import Dict, List, Set+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="Check whether the provided list of files contains any duplicate class names in them."+ )+ parser.add_argument(+ "--jar-to-owning-target-map-file",+ type=Path,+ help="A file that contains the mapping between jar paths and the owning target.",+ required=False,+ )+ parser.add_argument(+ "--validation-output",+ type=Path,+ required=True,+ )+ parser.add_argument(+ "--consolidated-files-list",+ type=Path,+ help="A file containing a list of consolidated JSON files (one path per line).",+ required=False,+ )+ parser.add_argument(+ "--mode",+ type=str,+ choices=["pre-dexed-libs", "non-pre-dexed-jars"],+ required=True,+ )+ args = parser.parse_args()++ if args.mode == "pre-dexed-libs":+ class_to_targets_map = get_class_to_target_mapping_from_consolidated_files(+ args.consolidated_files_list+ )+ elif args.mode == "non-pre-dexed-jars":+ class_to_targets_map = get_class_to_target_mapping_from_jars(+ args.jar_to_owning_target_map_file+ )+ else:+ raise ValueError(f"Unknown mode: {args.mode}")++ duplicate_classes = {+ class_name: target_name_list+ for class_name, target_name_list in class_to_targets_map.items()+ if len(target_name_list) > 1+ }++ print(build_validation_message(duplicate_classes), file=sys.stderr)+ if duplicate_classes:+ sys.exit(1)+ else:+ with open(args.validation_output, "w") as f:+ f.write("No duplicate class names found")+ sys.exit(0)+++def get_class_to_target_mapping_from_consolidated_files(+ consolidated_files_list: Path,+) -> Dict[str, List[str]]:+ """+ Reads consolidated JSON files and builds a mapping from class names to targets.++ Each consolidated file is a JSON object mapping target names to lists of class names.+ This is much faster than reading individual files because:+ 1. Fewer files to open (32 batches instead of 40K+ files)+ 2. Consolidated files are already in the optimal format++ Note: Batch-level duplicate detection is already done in consolidate_class_names.py,+ so duplicates within a single batch will fail fast at consolidation time.+ This function only needs to detect cross-batch duplicates.+ """+ # Read the list of consolidated files+ with open(consolidated_files_list) as f:+ consolidated_files = [line.strip() for line in f if line.strip()]++ class_to_target_mapping: Dict[str, List[str]] = {}++ # Read each consolidated file and merge the results+ for consolidated_file in consolidated_files:+ with open(consolidated_file) as f:+ target_to_classes: Dict[str, List[str]] = json.load(f)++ for target_name, class_names in target_to_classes.items():+ for class_name in class_names:+ if "$" not in class_name and "module-info" not in class_name:+ class_to_target_mapping.setdefault(class_name, []).append(+ target_name+ )++ return class_to_target_mapping+++def get_class_to_target_mapping_from_jars(+ jar_to_owning_target_map_file: Path,+) -> Dict[str, List[str]]:+ """+ Reads a JSON file that maps JAR file paths to their owning targets,+ extracts class names from each JAR file, and builds a mapping+ from class names to the targets that contain them.+ """+ with open(jar_to_owning_target_map_file) as f:+ target_to_jar_file_map = json.loads(f.read())++ class_to_target_mapping: Dict[str, List[str]] = {}+ for jar_path, target_name in target_to_jar_file_map.items():+ class_names = extract_class_names_from_jar(jar_path)+ for class_name in class_names:+ if "$" in class_name or "module-info" in class_name:+ continue+ class_to_target_mapping.setdefault(class_name, []).append(target_name)++ return class_to_target_mapping+++def extract_class_names_from_jar(jar_path: str) -> Set[str]:+ """+ Extracts class names from a JAR file.+ Returns a set of fully qualified class names.+ """+ class_names = set()+ with zipfile.ZipFile(jar_path, "r") as jar:+ for entry in jar.namelist():+ if entry.endswith(".class"):+ # Convert path/to/ClassName.class to path.to.ClassName+ class_name = entry.replace("/", ".").replace(".class", "")+ class_names.add(class_name)+ return class_names+++def build_validation_message(+ duplicate_classes: Dict[str, List[str]],+) -> str:+ if not duplicate_classes:+ return "No duplicate class names found"++ messages = []+ for class_name, targets in duplicate_classes.items():+ targets_str = ", ".join(sorted(targets))+ messages.append(+ f"* {class_name} exists in the following targets: {targets_str}\n",+ )+ return f"""+Duplicate class name(s) found:++This means multiple copies of the same class is being included in the final apk.+Check the class names and the target names listed below and make sure to only include one copy of each class.+Run `buck cquery allpaths(<apk_target>, <library_target>)` or `arc deppy explain-dep <apk_target> <library_target>` to find the dependency paths.+{"".join(messages)}+ """+++if __name__ == "__main__":+ main()
@@ -0,0 +1,264 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.+++import argparse+import json+import pathlib+import re++PREFIX_MARKER = "^"+SUFFIX_MARKER = "^"+REGEX_MARKER = "^-"+++class ClassNameFilter:+ def __init__(self, primary_dex_patterns):+ prefixes = []+ suffixes = []+ substrings = []+ exact_matches = []+ regular_expressions = []++ for pattern in primary_dex_patterns:+ if pattern.startswith(REGEX_MARKER):+ regular_expressions.append(pattern[2:])+ else:+ is_prefix = pattern[0] == PREFIX_MARKER+ is_suffix = pattern[-1] == SUFFIX_MARKER+ if is_prefix and is_suffix:+ exact_matches.append(pattern[1:-1])+ elif is_prefix:+ prefixes.append(pattern[1:])+ elif is_suffix:+ suffixes.append(pattern[:-1])+ else:+ substrings.append(pattern)++ self.prefixes = prefixes+ self.suffixes = suffixes+ self.substrings = substrings+ self.exact_matches = exact_matches+ self.regular_expressions = [+ re.compile(regular_expression) for regular_expression in regular_expressions+ ]++ def class_name_matches_filter(self, class_name):+ if class_name in self.exact_matches:+ return True++ for prefix in self.prefixes:+ if class_name.startswith(prefix):+ return True++ for suffix in self.suffixes:+ if class_name.endswith(suffix):+ return True++ for substring in self.substrings:+ if substring in class_name:+ return True++ for regular_expression in self.regular_expressions:+ if regular_expression.match(class_name):+ return True++ return False+++def _parse_args():+ parser = argparse.ArgumentParser(+ description="Tool to filter a dex for primary class names.",+ fromfile_prefix_chars="@",+ )++ parser.add_argument(+ "--primary-dex-patterns",+ type=pathlib.Path,+ required=True,+ help="a path to a list of primary dex patterns",+ )+ parser.add_argument(+ "--dex-target-identifiers",+ type=str,+ required=True,+ nargs="+",+ help="a list of dex target identifiers",+ )+ parser.add_argument(+ "--class-names",+ type=pathlib.Path,+ required=True,+ nargs="+",+ help="a path to a list of class names",+ )+ parser.add_argument(+ "--weight-estimates",+ type=pathlib.Path,+ required=True,+ nargs="+",+ help="a path to a weight estimate",+ )+ parser.add_argument(+ "--ref-counts",+ type=pathlib.Path,+ required=True,+ nargs="+",+ help="a path to a ref count file (format: '<method_count> <field_count> <type_count>')",+ )+ parser.add_argument(+ "--synthetic-contexts",+ type=pathlib.Path,+ nargs="+",+ default=[],+ help="a path to a synthetic-to-context file (one '<synthetic> <context>' pair per line)",+ )+ parser.add_argument(+ "--output",+ type=pathlib.Path,+ required=True,+ help="a path to an output. The output is a JSON mapping of dex target names to a map of primary dex classes, secondary dex classes, and weight estimate.",+ )++ return parser.parse_args()+++def _parse_ref_counts(ref_count_path):+ """Parse a ref count file containing '<method_count> <field_count> <type_count>'."""+ with open(ref_count_path) as ref_count_file:+ parts = ref_count_file.read().strip().split()+ if len(parts) != 3:+ raise ValueError(+ f"Expected 3 values (method field type) in ref count file "+ f"{ref_count_path}, got {len(parts)}: {parts!r}"+ )+ return parts[0], parts[1], parts[2]+++def _parse_synthetic_contexts(synthetic_contexts_path):+ """Parse '<synthetic> <context>' lines, as written by the pre-dex step, into a dict."""+ synthetic_to_context = {}+ with open(synthetic_contexts_path) as synthetic_contexts_file:+ for line in synthetic_contexts_file:+ line = line.strip()+ if not line:+ continue+ synthetic, _, context = line.partition(" ")+ if not context:+ raise ValueError(+ f"Malformed line in {synthetic_contexts_path}: {line!r}"+ )+ synthetic_to_context[synthetic] = context+ return synthetic_to_context+++def _resolve_synthesizing_context(java_class, synthetic_to_context):+ """Follow a synthetic back to the class it was synthesized from.++ D8 can synthesize from a synthetic, so the chain is walked to its end. The seen-set guards+ against a cycle in D8's output, which would otherwise hang the build.+ """+ seen = set()+ while java_class in synthetic_to_context and java_class not in seen:+ seen.add(java_class)+ java_class = synthetic_to_context[java_class]+ return java_class+++def _belongs_in_primary_dex(java_class, class_name_filter, synthetic_to_context):+ if class_name_filter.class_name_matches_filter(java_class):+ return True++ # A synthetic has to land in the same dex as the class it was synthesized from, which+ # references it directly. Splitting them puts the reference across a dex boundary that the+ # primary dex cannot resolve. primary_dex_patterns are written against real class names, so+ # match the context rather than the synthetic's mangled name.+ context = _resolve_synthesizing_context(java_class, synthetic_to_context)+ return context != java_class and class_name_filter.class_name_matches_filter(+ context+ )+++def main():+ args = _parse_args()++ primary_dex_patterns_path = args.primary_dex_patterns+ with open(primary_dex_patterns_path) as primary_dex_patterns_file:+ all_primary_dex_patterns = [line.rstrip() for line in primary_dex_patterns_file]++ class_name_filter = ClassNameFilter(all_primary_dex_patterns)++ dex_target_identifiers = args.dex_target_identifiers+ class_names_paths = args.class_names+ weight_estimate_paths = args.weight_estimates+ ref_count_paths = args.ref_counts+ synthetic_contexts_paths = args.synthetic_contexts+ output = args.output++ assert len(dex_target_identifiers) == len(class_names_paths), (+ "Must provide same number of class names files as dex target identifiers!"+ )++ assert len(dex_target_identifiers) == len(weight_estimate_paths), (+ "Must provide same number of weight estimate files as dex target identifiers!"+ )++ assert len(dex_target_identifiers) == len(ref_count_paths), (+ "Must provide same number of ref count files as dex target identifiers!"+ )++ assert not synthetic_contexts_paths or len(dex_target_identifiers) == len(+ synthetic_contexts_paths+ ), "Must provide same number of synthetic context files as dex target identifiers!"++ json_output = {}+ for i in range(len(dex_target_identifiers)):+ dex_target_name = dex_target_identifiers[i]+ weight_estimate_path = weight_estimate_paths[i]+ with open(weight_estimate_path) as weight_estimate_file:+ weight_estimate = weight_estimate_file.read().strip()++ method_ref_count, field_ref_count, type_ref_count = _parse_ref_counts(+ ref_count_paths[i]+ )++ class_names_path = class_names_paths[i]+ with open(class_names_path) as class_names_file:+ all_class_names = [line.rstrip() for line in class_names_file]++ synthetic_to_context = (+ _parse_synthetic_contexts(synthetic_contexts_paths[i])+ if synthetic_contexts_paths+ else {}+ )++ primary_dex_class_names = []+ secondary_dex_class_names = []+ for java_class in all_class_names:+ if _belongs_in_primary_dex(+ java_class, class_name_filter, synthetic_to_context+ ):+ primary_dex_class_names.append(java_class + ".class")+ else:+ secondary_dex_class_names.append(java_class + ".class")++ json_output[dex_target_name] = {+ "primary_dex_class_names": primary_dex_class_names,+ "secondary_dex_class_names": secondary_dex_class_names,+ "weight_estimate": weight_estimate,+ "method_ref_count": method_ref_count,+ "field_ref_count": field_ref_count,+ "type_ref_count": type_ref_count,+ }++ with open(output, "w") as output_file:+ json.dump(json_output, output_file, indent=4)+++if __name__ == "__main__":+ main()
@@ -0,0 +1,63 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import argparse+import pathlib+import shutil++import utils++ZIP_NOTHING_TO_DO_EXIT_CODE = 12+++def _parse_args():+ parser = argparse.ArgumentParser(+ description="Tool to remove extra resources from apk."+ )+ parser.add_argument(+ "--input-apk",+ type=pathlib.Path,+ required=True,+ help="a path to the original apk",+ )+ parser.add_argument(+ "--output-apk",+ type=pathlib.Path,+ required=True,+ help="a path to the output apk with removed resources",+ )+ parser.add_argument(+ "--extra-filtered-resources",+ type=str,+ action="append",+ required=True,+ help="list of patterns of files to filter out from the input apk",+ )+ return parser.parse_args()+++def main():+ args = _parse_args()+ shutil.copyfile(args.input_apk, args.output_apk)+ utils.execute_command(["chmod", "644", args.output_apk])++ # The normal resource filtering apparatus is super slow because it extracts the whole apk,+ # strips files out of it, then repackages it.+ #+ # This is a faster filtering step that just uses zip -d to remove entries from the archive.+ # It's also superbly dangerous.+ #+ # If zip -d returns that there was nothing to do, then we don't fail.+ utils.execute_command_ignore_exit_codes(+ ["zip", "-d", str(args.output_apk)] + args.extra_filtered_resources,+ [ZIP_NOTHING_TO_DO_EXIT_CODE],+ )+++if __name__ == "__main__":+ main()
@@ -0,0 +1,57 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.+++import argparse+import os+from pathlib import Path+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="Filter the ABIs in a prebuilt native library directory"+ )+ parser.add_argument(+ "library_dirs",+ type=Path,+ help="A file that lists directories containing ABI subdirectories",+ )+ parser.add_argument(+ "output_dir",+ type=Path,+ help="Symlinks to the filtered ABIs will be created here",+ )+ parser.add_argument(+ "--abis",+ required=True,+ nargs="+",+ help="The ABIs to filter",+ )+ args = parser.parse_args()++ args.output_dir.mkdir(parents=True)+ with open(args.library_dirs, "r") as f:+ for line in f:+ library_dir = Path(line.rstrip())+ for abi in args.abis:+ abi_path = library_dir / abi+ if abi_path.exists():+ abi_output_path = args.output_dir / abi+ abi_output_path.mkdir(exist_ok=True)+ for source_path in abi_path.iterdir():+ # This should be a directory, but files will be silently ignored by APK+ # packaging, so we don't need to error here. We use os.path.relpath because+ # pathlib.Path.relative_to only works if the paths have a common prefix.+ (abi_output_path / source_path.name).symlink_to(+ os.path.relpath(source_path, start=abi_output_path),+ target_is_directory=source_path.is_dir(),+ )+++if __name__ == "__main__":+ main()
@@ -0,0 +1,47 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//decls:toolchains_common.bzl", "toolchains_common")+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")++def _jdk_system_image_impl(ctx: AnalysisContext) -> list[Provider]:+ java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]++ output = ctx.actions.declare_output("image", has_content_based_path = False)+ cmd = cmd_args([+ ctx.attrs.create_jdk_system_image[RunInfo],+ "--core-for-system-modules-jar",+ ctx.attrs.core_for_system_modules_jar,+ "--java",+ java_toolchain.java[RunInfo],+ "--javac",+ java_toolchain.javac[RunInfo],+ "--jlink",+ java_toolchain.jlink[RunInfo],+ "--jmod",+ java_toolchain.jmod[RunInfo],+ "--jrt-fs-jar",+ java_toolchain.jrt_fs_jar,+ "--jar-builder",+ ctx.attrs.jar_builder,+ "--output",+ output.as_output(),+ ])+ ctx.actions.run(cmd, category = "create_jdk_system_image")++ return [DefaultInfo(default_output = output)]++jdk_system_image = rule(+ impl = _jdk_system_image_impl,+ attrs = {+ "core_for_system_modules_jar": attrs.source(),+ "create_jdk_system_image": attrs.exec_dep(default = "prelude//android/tools:create_jdk_system_image"),+ "jar_builder": attrs.source(default = "prelude//toolchains/android/src/com/facebook/buck/util/zip:jar_builder"),+ "_java_toolchain": toolchains_common.java_for_android(),+ },+)
@@ -0,0 +1,815 @@+#!/usr/bin/python3+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++"""+Applies the merge sequence to the linkable_graph and module graph to produce merged libraries.++The merge sequence is a list of "merge entries". Each entry is comprised of "merge specs", each of which have a name and+a list of roots. A merge entry may be a merge spec or a list of merge specs.++For example:++```+[+ ("libgroup1.so", [//group1:root1, //group1:root2]),+ ("libgroup2.so", [//group2:root]),+ (+ ("libgroup3lib1.so": [//group3:root1]),+ ("libgroup3lib2.so": [//group3:root2]),+ ),+ ...+]+```++We use this sequence to assign each target in the linkable graph to a "merge group". The list is processed in order and+each entry defines a new merge group. That group consists of all the roots in the entry and all of the transitive+dependencies of those roots, except for nodes that have already been assigned a merge group.++We then need to split that merge group into "split groups" for four reasons: avoiding unwanted dependencies between+libraries, defining valid libraries, avoiding adding implicit module dependencies to targets, and excluding targets that+shouldn't be merged. That imposes these constraints:+1. Libraries defined by specs in the same entry should not depend on one another, so any shared dependencies must be+ split into separate libraries.+2. Targets in a split group will all be in the same module. A library cannot span multiple modules.+3. For split groups in the root module, all targets will have the same set of transitive module dependencies (including+ through targets in other merge groups). A non-root module cannot be loaded without loading all of its module+ dependencies, but if a JNI entry-point target is in the root module and has module dependencies, those dependencies+ would have to be loaded explicitly in advance, or the library load for the target will fail. Making any such target+ depend on *more* modules in merged-library builds would therefore risk merged-build-only runtime crashes.+4. Some targets are excluded from merging (explicitly via a blocklist, or implicitly because they cannot be packaged as+ assets). Non-asset targets are rare, often cause issues when merged, and complicate split-group "layering" as+ described below, so it significantly simplifies merge sequence configuration and mechanics to exclude them.++Finally, we need to prevent dependency cycles between merged libraries. This only requires additional effort at the+split group level; there cannot be any cycles between merge groups because, by definition, any transitive dependency of+a target in a previous merge group is already in a previous merge group.++To ensure there are no cycles, we further split the split groups into "layers" by how many times their dependents in the+current merge group reenter the same split group. There cannot be a cycle between any pair of split group layers,+regardless of whether the layers are from the same split group. If dependency chains exist in both directions between+two split group layers:+- The layers must share the same transitive module dependencies.+- The layers must have different dependent reentry counts or be in different modules, or else they'd be the same layer.+- If the layers are in the same module, there are dependency chains in both directions between different layers of the+ same split group. But those layers have different dependent reentry counts into that split group, so this is+ impossible. The layers are in different modules.+- One layer must be in the root module, or else there would be a module dependency cycle. (As a special case, cycles+ between the root module and non-root modules are allowed.)+- Every target in the root-module layer in the dependency chain starting from the non-root module layer must be a+ non-asset target, or else the module would have included each such target, since they're transitive dependencies and+ no other non-root module includes them.+- But we do not merge non-asset targets. There is no cycle.++Further, the number of layers in a split group is the minimal number of libraries that can be merged from that split+group without causing a cycle. There exists a dependency chain between each pair of layers in a split group that exits+the split group at one layer and reenters it at the other, so any library merging two layers of the same split group+transitively depends on itself.++The split group layering determines the final library constituents.++We perform a bottom-up traversal to identify transitive module dependencies, then a top-down traversal to assign split+groups, compute dependent split-group reentry counts, and finalize split group layers. While we could avoid the second+traversal by instead layering based on *dependency* reentry count, using *dependent* reentry count produces better+target distribution between layers.+- Optimal target distribution would maximize the number of targets in the largest layer. For a fixed number of+ libraries, build size varies depending on how many symbols need to be exposed in order to facilitate linkage across+ libraries, and so reducing the number of satellite targets will in general improve build size.+- Split-group-reentrant dependency chains are rare, so targets without split-group-reentrant dependencies or dependents+ are common. Similarly, short split-group-reentrant dependency chains are more common than longer ones.+- So if we want to maximize the size of the largest layer, we want the targets without reentrant dependencies to merge+ with the targets at the heads of reentrant dependency chains, the most common targets in such chains.++Once we've done the split group layering, the split group and layer identify the "final library" for each target. The+one remaining thing to do is to produce a name for each final library. Ideally, each merge group will end up with a+single library and the naming is simple. If it ends up having multiple libraries, we give each a unique name by adding+suffixes.++We aim to minimize the suffixing of the largest, most central layers, so we apply the following rules:+1. Library names start with the names of the merge specs from the current entry whose roots include or depend on the+ library's targets. This is just the spec name if there is only one, or `lib_shared_` plus the underscore-separated+ list of spec names if there are multiple.+2. If a merge spec includes targets from multiple modules, each library in a non-root module will be suffixed with that+ module name.+3. We perform a topological traversal of the final library graph, maintaining counters of times we've encountered each+ (possibly module-suffixed) library name. Each final library after the first encountered for its library name will be+ further suffixed with that library name's counter value.+"""++from __future__ import annotations++import argparse+import json+import os+import pathlib+import re+import sys+import typing+from collections import defaultdict+from typing import Optional++Label = typing.NewType("Label", str)+++class LinkableGraphNode(typing.NamedTuple):+ """+ A node in the linkable graph input+ """++ raw_target: str+ soname: str+ deps: list[Label]+ can_be_asset: bool+ force_static: bool+ labels: list[str]++ @staticmethod+ def parse(json: dict[str, object]) -> LinkableGraphNode:+ deps = [Label(x) for x in json.pop("deps")] # pyre-ignore+ return LinkableGraphNode(deps=deps, **json) # pyre-ignore+++class MergemapInput(typing.NamedTuple):+ """+ Parsed form of the mergemap input file+ """++ merge_sequence: list[MergeSequenceGroupSpec]+ blocklist: list[re.Pattern[str]]+ nodes_by_platform: dict[str, dict[Label, LinkableGraphNode]]++ @staticmethod+ def parse(mergemap_input: dict[str, typing.Any]) -> MergemapInput:+ merge_sequence = [+ MergeSequenceGroupSpec(x)+ for x in mergemap_input["native_library_merge_sequence"]+ ]+ blocklist = [+ re.compile(x)+ for x in mergemap_input["native_library_merge_sequence_blocklist"]+ ]+ nodes_by_platform = {}+ for platform, linkable_graph_spec in mergemap_input[+ "linkable_graphs_by_platform"+ ].items():+ nodes = {}+ for target, node_data in linkable_graph_spec.items():+ target = Label(target)+ node_data = LinkableGraphNode.parse(node_data)+ nodes[target] = node_data+ nodes_by_platform[platform] = nodes++ return MergemapInput(+ merge_sequence=merge_sequence,+ blocklist=blocklist,+ nodes_by_platform=nodes_by_platform,+ )+++class ApkModuleGraph:+ """+ Parsed form of the optional apk module graph input+ """++ def __init__(self, target_to_module_mapping: Optional[dict[str, str]]) -> None:+ self.target_to_module_mapping = target_to_module_mapping++ def module_for_target(self, target: str) -> str:+ if self.target_to_module_mapping:+ module = self.target_to_module_mapping[target]+ return module+ else:+ return ROOT_MODULE+++class SplitGroupKey(typing.NamedTuple):+ """+ Identifies a single "split group"+ """++ # If excluded, this holds the targets label+ excluded: typing.Optional[Label]+ module: str+ current_merge_group: int+ # Holds the set of names of specs in the entry that depend on the targets.+ # This will contain only one string for most targets/entries.+ merge_subgroup: set[str]+ # For the root module, holds the structified set of transitively reachable modules+ transitive_module_key: typing.Optional[frozenset[str]]++ def get_base_name(self) -> str:+ if self.excluded:+ return self.excluded++ assert len(self.merge_subgroup) > 0++ dependent_spec_names = sorted(self.merge_subgroup)++ if len(dependent_spec_names) == 1:+ return dependent_spec_names[0]+ else:+ base_name = "lib_shared"+ for dependent_spec_name in dependent_spec_names:+ base_name += f"_{dependent_spec_name[3:-3]}"+ base_name += ".so"+ return base_name+++class NodeData(typing.NamedTuple):+ base_library_name: str+ could_be_root_for: list[str]+ module: str+ merge_group: int+ is_excluded: bool+ final_lib_key: FinalLibKey+ dependent_included_split_group_entry_counts: dict[int, int]++ def debug(self) -> object:+ return self._asdict()+++class FinalLibKey(typing.NamedTuple):+ split_group: int+ cycle_breaker: typing.Hashable+++class FinalLibData(typing.NamedTuple):+ module: str+ merge_group: int+ # this will be either the merge group spec name or come from the label for an excluded lib.+ base_library_name: str+ is_excluded: bool+ key: FinalLibKey+ deps: set[FinalLibKey]+ entry_point_targets: set[str]+++class FinalLibGraph:+ """The "final lib graph" is traversed to produce the final lib names"""++ graph: dict[FinalLibKey, FinalLibData]++ def __init__(self) -> None:+ self.graph = {}++ def _ensure_lib_data(self, node_data: NodeData) -> FinalLibData:+ lib_key = node_data.final_lib_key+ lib_data = self.graph.get(lib_key, None)+ if not lib_data:+ lib_data = self.graph.setdefault(+ lib_key,+ FinalLibData(+ module=node_data.module,+ merge_group=node_data.merge_group,+ base_library_name=node_data.base_library_name,+ is_excluded=node_data.is_excluded,+ key=lib_key,+ deps=set(),+ entry_point_targets=set(),+ ),+ )+ else:+ assert lib_data.module == node_data.module, (lib_data, node_data)+ assert lib_data.merge_group == node_data.merge_group, (lib_data, node_data)++ return lib_data++ def add_node(+ self,+ node_data: NodeData,+ deps: list[str],+ deps_data: list[NodeData],+ ) -> None:+ lib_data = self._ensure_lib_data(node_data)++ for dep, dep_data in zip(deps, deps_data):+ if dep_data.final_lib_key != node_data.final_lib_key:+ lib_data.deps.add(dep_data.final_lib_key)+ dep_lib_data = self._ensure_lib_data(dep_data)+ dep_lib_data.entry_point_targets.add(dep)++ def dump_lib_edges(self, names: dict[FinalLibKey, str]) -> dict[str, list[str]]:+ return {+ names[k]: [names[d] for d in node.deps] for k, node in self.graph.items()+ }++ def dump_entry_point_targets(+ self, names: dict[FinalLibKey, str]+ ) -> dict[str, list[str]]:+ return {+ names[k]: list(node.entry_point_targets) for k, node in self.graph.items()+ }++ def assign_names(+ self, merge_group_module_constituents: list[set[str]]+ ) -> dict[FinalLibKey, str]:+ final_lib_graph = {}+ for key, dep_data in self.graph.items():+ final_lib_graph[key] = list(dep_data.deps)++ # this topo_sort also verifies that we produced an acyclic final lib graph+ sorted_final_lib_keys = topo_sort(+ final_lib_graph, lambda x: self.graph[x].module if self.graph[x] else str(x)+ )++ name_counters = {}+ final_lib_names: dict[FinalLibKey, str] = {}+ for key in sorted_final_lib_keys:+ dep_data = self.graph[key]+ if dep_data.is_excluded:+ final_lib_names[key] = dep_data.base_library_name+ else:+ lib_name, ext = os.path.splitext(dep_data.base_library_name)+ if len(+ merge_group_module_constituents[dep_data.merge_group]+ ) > 1 and not is_root_module(dep_data.module):+ lib_name += "_" + dep_data.module++ count = name_counters.setdefault(lib_name, 0) + 1+ name_counters[lib_name] = count+ if count > 1:+ lib_name += "_{}".format(count - 1)+ final_lib_names[key] = lib_name + ext+ return final_lib_names+++# Older python has poor typing support, so we need to use coarser types there (but pyre wants the exact ones)+if sys.version_info >= (3, 9):+ MergeSubgroupMapping = typing.Callable[[Label], typing.Optional[set[str]]]+ MergeGroupSpecDef = typing.Tuple[str, list[str]]+else:+ MergeSubgroupMapping = typing.Callable+ MergeGroupSpecDef = typing.Tuple+++class MergeSequenceGroupSpec:+ # These lists run parallel to one another; the group_roots_patterns+ # entry for a given index contains all the root patterns for the+ # group_specs entry at the same index.+ group_specs: list[MergeGroupSpecDef]+ group_roots_patterns: list[list[re.Pattern[str]]]++ def __init__(+ self, group_specs: typing.Union[MergeGroupSpecDef, list[MergeGroupSpecDef]]+ ) -> None:+ self.group_specs = (+ [group_specs] if isinstance(group_specs[0], str) else group_specs+ )++ for group_spec in self.group_specs:+ library_name = group_spec[0]+ assert library_name.startswith("lib"), (+ f"native merge library name {library_name} does not begin with 'lib'"+ )+ assert library_name.endswith(".so"), (+ f"native merge library name {library_name} does not end with '.so'"+ )++ self.group_roots_patterns = [+ [re.compile(x) for x in spec[1]] for spec in self.group_specs+ ]++ def get_rooted_specs(self, raw_target: str) -> set[str]:+ result = set()+ for patterns, group_spec in zip(self.group_roots_patterns, self.group_specs):+ for p in patterns:+ if p.search(raw_target):+ result.add(group_spec[0])+ break++ return result++ def compute_merge_subgroup_mapping(+ self,+ group_roots: dict[Label, set[str]],+ post_ordered_targets: list[Label],+ graph_map: dict[Label, LinkableGraphNode],+ ) -> MergeSubgroupMapping:+ merge_specs_with_reachable_roots = defaultdict(set)++ for target, rooted_specs in group_roots.items():+ merge_specs_with_reachable_roots[target].update(rooted_specs)++ for target in post_ordered_targets[::-1]:+ node = graph_map.get(target)+ assert node is not None+ roots_to_add = merge_specs_with_reachable_roots[target]+ for child in node.deps:+ merge_specs_with_reachable_roots[child].update(roots_to_add)++ return lambda x: frozenset(merge_specs_with_reachable_roots[x])+++def get_native_linkables_by_merge_sequence( # noqa: C901+ graph_node_map: dict[Label, LinkableGraphNode],+ native_library_merge_sequence: list[MergeSequenceGroupSpec],+ native_library_merge_sequence_blocklist: list[typing.Pattern],+ apk_module_graph: ApkModuleGraph,+ native_library_merge_non_asset_libs: bool,+) -> typing.Tuple[dict[Label, NodeData], dict[FinalLibKey, str], FinalLibGraph]:+ final_lib_graph = FinalLibGraph()+ node_data: dict[Label, NodeData] = {}+ transitive_module_deps_map: dict[Label, frozenset[str]] = {}++ dependents_in_current_merge_group_map: dict[Label, list[Label]] = {}++ def check_is_excluded(target: Label) -> bool:+ node = graph_node_map[target]+ if not native_library_merge_non_asset_libs and not node.can_be_asset:+ return True++ raw_target = node.raw_target+ for x in native_library_merge_sequence_blocklist:+ if x.search(raw_target):+ return True++ # TODO(cjhopman): This logic does not explicitly exclude targets that are used_by_wrap_script. D38377593+ # enforces that such targets never can_be_asset and are therefore implicitly excluded, but D38845949 still+ # explicitly excludes them for Buck 1.+ return False++ def get_children_without_merge_group(label: Label) -> list[Label]:+ node = graph_node_map[label]+ group_deps = [child for child in node.deps if child not in node_data]++ # In addition to applying an ordering to targets, this traversal identifies within-merge-group dependents.+ for group_dep in group_deps:+ dependents_in_current_merge_group_map.setdefault(group_dep, []).append(+ label+ )++ return group_deps++ current_merge_group = 0++ split_groups: dict[SplitGroupKey, int] = {}++ merge_group_module_constituents: list[set[str]] = []++ for current_merge_group in range(len(native_library_merge_sequence)):+ dependents_in_current_merge_group_map = {}++ merge_group_module_constituents.append(set())+ group_specs: MergeSequenceGroupSpec = native_library_merge_sequence[+ current_merge_group+ ]+ group_roots = {}+ for label, node in graph_node_map.items():+ if label not in node_data:+ rooted_specs = group_specs.get_rooted_specs(node.raw_target)+ if rooted_specs:+ group_roots[label] = rooted_specs++ post_ordered_targets = post_order_traversal_by(+ group_roots.keys(), get_children_without_merge_group+ )++ merge_subgroup_mapping = group_specs.compute_merge_subgroup_mapping(+ group_roots, post_ordered_targets, graph_node_map+ )++ def get_split_group(+ label: Label,+ transitive_module_deps: frozenset[str],+ module: str,+ current_merge_group: int = current_merge_group,+ merge_subgroup_mapping: MergeSubgroupMapping = merge_subgroup_mapping,+ ) -> typing.Tuple[bool, int, str]:+ excluded = None+ if check_is_excluded(label):+ excluded = label++ merge_subgroup = merge_subgroup_mapping(label)++ if is_root_module(module):+ transitive_module_key = transitive_module_deps+ else:+ transitive_module_key = None++ split_group_key = SplitGroupKey(+ excluded=excluded,+ module=module,+ current_merge_group=current_merge_group,+ merge_subgroup=merge_subgroup,+ transitive_module_key=transitive_module_key,+ )+ return (+ excluded is not None,+ split_groups.setdefault(split_group_key, len(split_groups)),+ split_group_key.get_base_name(),+ )++ # Bottom-up traversal (compute transitive module dependencies)+ for target in post_ordered_targets:+ assert target not in node_data, "{}: {}".format(+ target, post_ordered_targets+ )++ node = graph_node_map[target]+ module = apk_module_graph.module_for_target(node.raw_target)++ merge_group_module_constituents[current_merge_group].add(module)++ transitive_module_deps = {module}+ for dep in node.deps:+ transitive_module_deps.update(transitive_module_deps_map[dep])+ transitive_module_deps_map[target] = frozenset(transitive_module_deps)++ # Top-down traversal (determine split groups, compute dependent split group reentry counts, finalize layers)+ for target in reversed(post_ordered_targets):+ assert target not in node_data, "{}: {}".format(+ target, post_ordered_targets+ )++ node = graph_node_map[target]+ module = apk_module_graph.module_for_target(node.raw_target)++ is_excluded, split_group, base_library_name = get_split_group(+ target, transitive_module_deps_map[target], module+ )++ dependent_included_split_group_entry_counts: dict[int, int] = {}++ for dependent_in_group in dependents_in_current_merge_group_map.get(+ target, []+ ):+ dependent_in_group_data = node_data[dependent_in_group]+ dependent_split_group = (+ dependent_in_group_data.final_lib_key.split_group+ )+ is_included_split_group_entry = (+ split_group != dependent_split_group+ and not dependent_in_group_data.is_excluded+ )++ # dependent_included_split_group_entry_counts do not count entry into a target's own split group layer,+ # so we have to ensure that its dependencies record an entry count of at least 1 for that split group.+ if (+ is_included_split_group_entry+ and dependent_split_group+ not in dependent_included_split_group_entry_counts+ ):+ dependent_included_split_group_entry_counts[+ dependent_split_group+ ] = 1++ for (+ group,+ entry_count,+ ) in dependent_in_group_data.dependent_included_split_group_entry_counts.items():+ if group == dependent_split_group and is_included_split_group_entry:+ entry_count += 1++ curr_entry_count = dependent_included_split_group_entry_counts.get(+ group, 0+ )+ if entry_count > curr_entry_count:+ dependent_included_split_group_entry_counts[group] = entry_count++ this_node_data = NodeData(+ base_library_name=base_library_name,+ could_be_root_for=list(group_roots.get(target, set())),+ module=module,+ merge_group=current_merge_group,+ final_lib_key=FinalLibKey(+ split_group=split_group,+ cycle_breaker=dependent_included_split_group_entry_counts.get(+ split_group, 0+ ),+ ),+ is_excluded=is_excluded,+ dependent_included_split_group_entry_counts=dependent_included_split_group_entry_counts,+ )+ node_data[target] = this_node_data++ for target in post_ordered_targets:+ node = graph_node_map[target]+ deps_data = [node_data[dep] for dep in node.deps]+ final_lib_graph.add_node(node_data[target], node.deps, deps_data)++ final_lib_names = final_lib_graph.assign_names(merge_group_module_constituents)+ return node_data, final_lib_names, final_lib_graph+++T = typing.TypeVar("T")+++def post_order_traversal_by(+ roots: list[T],+ get_nodes_to_traverse_func: typing.Callable[[T], list[T]],+ get_node_str: typing.Callable[[T], str] = None,+) -> list[T]:+ """+ Returns the post-order sorted list of the nodes in the traversal.++ This implementation simply performs a dfs. We maintain a work stack here.+ When visiting a node, we first add an item to the work stack to output that+ node, and then add items to visit all the children. While a work item for a+ child will not be added if it has already been visited, if there's an item in+ the stack for that child it will still be added. When popping the visit, if+ the node had been visited, it's ignored. This ensures that a node's children are+ all visited before we output that node.+ """+ ordered = []+ visited = {}+ OUTPUT = 1+ VISIT = 2+ current_parents = []+ work = [(VISIT, n) for n in roots]+ while work:+ kind, node = work.pop()+ if kind == VISIT:+ if node not in visited:+ visited[node] = True+ current_parents.append(node)++ work.append((OUTPUT, node))+ for dep in get_nodes_to_traverse_func(node):+ if dep in current_parents:+ current_parents_strs = []+ for k in current_parents:+ current_parents_strs.append(+ get_node_str(k) if get_node_str else str(k)+ )+ raise AssertionError(+ "detected cycle: {}".format(+ " -> ".join(+ current_parents_strs+ + [get_node_str(dep) if get_node_str else str(dep)]+ )+ )+ )++ if dep not in visited:+ work.append((VISIT, dep))+ else:+ ordered.append(node)+ current_parents.pop()+ return ordered+++ROOT_MODULE = "dex"+++def is_root_module(module: str) -> bool:+ return module == ROOT_MODULE+++def topo_sort(+ graph: dict[T, list[T]], get_node_str: typing.Callable[[T], str] = None+) -> list[T]:+ """+ Topo-sort the given graph.+ """+ in_degrees = {node: 0 for node in graph}+ for _node, deps in graph.items():+ assert len(deps) == len(set(deps))+ for dep in deps:+ in_degrees[dep] += 1++ roots = []++ for node, in_degree in in_degrees.items():+ if in_degree == 0:+ roots.append(node)++ postordered = post_order_traversal_by(roots, lambda x: graph[x], get_node_str)+ postordered.reverse()++ return postordered+++def read_apk_module_graph(path: Optional[str]) -> ApkModuleGraph:+ if not path:+ return ApkModuleGraph(None)++ target_to_module_mapping = {}+ # the format of this file is, the first line contains an integer, then follows that many lines describing dependencies+ # between modules. Each line is of the form: <module_name> <dep_name1> <dep_name2> ...+ # after that, all target->module mappings are listed, one on each line.+ # Each line has the form: <raw_target> <module_name>+ with open(path) as modules_in:+ lines = modules_in.read().splitlines()+ module_lines = int(lines[0])+ for line in lines[module_lines + 1 :]:+ target, module = line.split()+ target_to_module_mapping[target] = module+ return ApkModuleGraph(target_to_module_mapping)+++def read_mergemap_input(path: str) -> MergemapInput:+ with open(path) as mergemap_input:+ mergemap_input = json.load(mergemap_input)+ return MergemapInput.parse(mergemap_input)+++def main() -> int: # noqa: C901+ parser = argparse.ArgumentParser()+ parser.add_argument("--mergemap-input", required=True)+ parser.add_argument("--apk-module-graph")+ parser.add_argument("--output")+ parser.add_argument("--merge-non-asset-libs", action="store_true")+ args = parser.parse_args()++ apk_module_graph = read_apk_module_graph(args.apk_module_graph)++ final_result = {}+ debug_results = {}+ split_groups = {}+ mergemap_input = read_mergemap_input(args.mergemap_input)+ for platform, nodes in mergemap_input.nodes_by_platform.items():+ (+ node_data,+ final_lib_names,+ final_lib_graph,+ ) = get_native_linkables_by_merge_sequence(+ nodes,+ mergemap_input.merge_sequence,+ mergemap_input.blocklist,+ apk_module_graph,+ args.merge_non_asset_libs,+ )++ final_mapping = {}+ for target in nodes.keys():+ if target in node_data:+ node = node_data[target]+ if node.is_excluded:+ final_mapping[target] = None+ else:+ final_mapping[target] = final_lib_names[node.final_lib_key]+ split_groups[final_lib_names[node.final_lib_key]] = (+ node.base_library_name+ )+ else:+ final_mapping[target] = str(target)+ debug_results[platform] = (+ # Target name -> various information+ {k: v.debug() for k, v in node_data.items()},+ # Serialized FinalLibKey -> final library name+ {str(k): v for k, v in final_lib_names.items()},+ # Final library name -> final names of direct library dependencies+ final_lib_graph.dump_lib_edges(final_lib_names),+ # Final library name -> entry point targets+ final_lib_graph.dump_entry_point_targets(final_lib_names),+ )+ final_result[platform] = final_mapping++ if args.output:+ pathlib.Path(args.output).mkdir(parents=True, exist_ok=True)+ with open(os.path.join(args.output, "merge.map"), "w") as outfile:+ json.dump(final_result, outfile, indent=2, sort_keys=True)+ with open(os.path.join(args.output, "split_groups.map"), "w") as outfile:+ json.dump(split_groups, outfile, indent=2, sort_keys=True)++ # When writing an output dir we also produce some debugging information.+ for platform, result in final_result.items():++ def set_default(obj: object) -> object:+ if isinstance(obj, frozenset):+ return list(obj)+ raise TypeError++ with open(+ os.path.join(args.output, "{}.debug".format(platform)), "w"+ ) as outfile:+ json.dump(+ debug_results[platform], outfile, indent=2, default=set_default+ )++ # The "inverted" map just provides a much simpler human-readable form of the merge mapping of the form:+ # libfoo.so+ # target1+ # target2+ # libfoo2.so+ # ...+ inverted = defaultdict(set)+ for label, lib in result.items():+ if not lib:+ lib = label+ inverted[lib].add(label)+ with open(+ os.path.join(args.output, "{}.inverted".format(platform)),+ "w",+ ) as outfile:+ lines = []+ for lib in sorted(inverted.keys()):+ lines.append(lib + "\n")+ for label in sorted(inverted[lib]):+ lines.append(" " + str(label) + "\n")+ outfile.writelines(lines)+ else:+ json.dump(final_result, sys.stdout, indent=2)++ return 0+++if __name__ == "__main__":+ sys.exit(main())
@@ -0,0 +1,84 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.+++import argparse+import hashlib+import os+from pathlib import Path+from typing import NamedTuple+++class NativeLibrary(NamedTuple):+ full_path: Path+ relative_path: Path+ size: int+ sha256: str+++def _get_native_library(path: Path, relative_path: Path) -> NativeLibrary:+ if not (path.name == "wrap.sh" or path.suffix == ".so"):+ raise Exception("Unexpected path {} in native library directory!".format(path))++ with open(path, "rb") as f:+ file_size = os.path.getsize(path)+ sha256 = hashlib.sha256(f.read()).hexdigest()++ return NativeLibrary(path, relative_path, file_size, sha256)+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="Writes out metadata relating to native libraries"+ )+ parser.add_argument(+ "--native-library-dirs",+ type=Path,+ help="A file of directories containing native libraries",+ )+ parser.add_argument(+ "--metadata-output",+ type=Path,+ help="Metadata is written to this file",+ )+ args = parser.parse_args()++ native_libraries = []+ with open(args.native_library_dirs) as f:+ for line in f:+ native_library_dir = Path(line.strip())+ for full_path in native_library_dir.rglob("*"):+ if full_path.is_file():+ native_libraries.append(+ _get_native_library(+ full_path, full_path.relative_to(native_library_dir)+ )+ )++ # buck1 sorts native libraries in decreasing file size order, so we do the same.+ native_libraries.sort(+ key=lambda native_lib: (-native_lib.size, native_lib.relative_path)+ )++ with open(args.metadata_output, "w") as f:+ f.write(+ "\n".join(+ [+ "{} {} {}".format(+ str(native_lib.relative_path),+ str(native_lib.size),+ str(native_lib.sha256),+ )+ for native_lib in native_libraries+ ]+ )+ )+++if __name__ == "__main__":+ main()
@@ -0,0 +1,457 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++"""+Sorts pre-dexed libraries into primary/secondary dex groups for an Android APK.++This tool replaces the _sort_pre_dexed_files Starlark function that previously+ran inside the merge_pre_dexed_libs dynamic_output lambda, taking ~3-4 seconds+in the Starlark interpreter. By running as a compiled Python tool, this+completes in ~10-50ms.++It reads:+ - All filter_dex JSON outputs (one per batch)+ - The APK module graph file (for Voltron builds)+ - A lib metadata JSON mapping identifier -> owner target label++It outputs a dex_plan.json that the simplified lambda reads to declare+merge_dexes actions.+"""++from __future__ import annotations++import argparse+import json+import pathlib+from typing import Optional, TypedDict+++ROOT_MODULE: str = "dex"++# DEX 64K limit enforcement.+#+# Each DEX file is limited to 65536 method_ids, field_ids, and type_ids.+# Per-library ref counts from the DEX header are summed as a conservative+# upper bound — the actual merged DEX has fewer refs because shared+# dependencies are deduplicated.+#+# The merge step uses ["--no-desugar", "--no-optimize"], so D8 performs a+# pure mechanical merge with no synthetic generation. Merged refs are+# always <= sum of input refs, never more.+DEX_REF_LIMIT: int = 65536++# Type aliases for the data structures used throughout.+# A single entry in a dex group: {"id": <lib_id>, "class_names": [<class>, ...]}+DexEntry = dict[str, object]+# A group is a list of DexEntry dicts that will be merged into one .dex file.+DexGroup = list[DexEntry]+# Per-module sorting result before flattening.+ModuleSortResult = dict[str, list[DexGroup]]+++class FilterDexInfo(TypedDict):+ primary_dex_class_names: list[str]+ secondary_dex_class_names: list[str]+ weight_estimate: str+ method_ref_count: str+ field_ref_count: str+ type_ref_count: str+++# Filter dex data: identifier -> filter info+FilterDexData = dict[str, FilterDexInfo]+# Lib metadata: identifier -> owner target label+LibMetadata = dict[str, str]+# Target to module mapping+TargetToModule = dict[str, str]+# Module metadata: module_name -> {"canary_class_name": ..., "module_deps": [...]}+ModuleMetadata = dict[str, dict[str, object]]+# Flattened group for JSON output: {"lib_ids": [...], "class_names": [...]}+FlatGroup = dict[str, list[str]]+++def _parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description="Sort pre-dexed files into dex merge groups.",+ fromfile_prefix_chars="@",+ )+ parser.add_argument(+ "--filter-dex-outputs",+ type=pathlib.Path,+ nargs="+",+ required=True,+ help="Paths to filter_dex JSON output files",+ )+ parser.add_argument(+ "--lib-metadata",+ type=pathlib.Path,+ required=True,+ help="JSON file mapping identifier -> owner target label",+ )+ parser.add_argument(+ "--module-graph",+ type=pathlib.Path,+ default=None,+ help="APK module graph file (for Voltron builds)",+ )+ parser.add_argument(+ "--weight-limit",+ type=int,+ required=True,+ help="Secondary dex weight limit in bytes",+ )+ parser.add_argument(+ "--enable-bootstrap-dexes",+ action="store_true",+ default=False,+ help="Whether to enable bootstrap dexes",+ )+ parser.add_argument(+ "--output",+ type=pathlib.Path,+ required=True,+ help="Output dex plan JSON file",+ )+ return parser.parse_args()+++def _parse_module_graph(+ module_graph_path: Optional[pathlib.Path],+) -> tuple[TargetToModule, ModuleMetadata]:+ """Parse the APK module graph file, returning target-to-module mapping and module metadata."""+ if module_graph_path is None:+ return {}, {}++ with open(module_graph_path) as f:+ lines = f.read().split("\n")++ module_count = int(lines[0])+ module_infos = lines[1 : module_count + 1]+ target_to_module_lines = lines[module_count + 1 : -1]++ target_to_module: TargetToModule = {}+ module_metadata: ModuleMetadata = {}++ for line in module_infos:+ parts = line.split(" ")+ module_name = parts[0]+ canary_class_name = parts[1]+ module_deps = [dep for dep in parts[2:] if dep]+ module_metadata[module_name] = {+ "canary_class_name": canary_class_name,+ "module_deps": module_deps,+ }++ for line in target_to_module_lines:+ if not line:+ continue+ target, module = line.split(" ")+ target_to_module[target] = module++ return target_to_module, module_metadata+++def _assign_to_dex(+ dest: list[DexGroup],+ module: str,+ lib_id: str,+ weight_estimate: int,+ dex_class_names: list[str],+ current_size_map: dict[str, int],+ current_inputs_map: dict[str, DexGroup],+ dex_weight_limit: Optional[int],+ method_ref_count: int,+ field_ref_count: int,+ type_ref_count: int,+ current_method_refs_map: dict[str, int],+ current_field_refs_map: dict[str, int],+ current_type_refs_map: dict[str, int],+) -> None:+ """Assign a lib's classes to a dex group, starting a new group if limits exceeded."""+ if len(dex_class_names) == 0:+ return++ current_size = current_size_map.get(module, 0)+ current_method_refs = current_method_refs_map.get(module, 0)+ current_field_refs = current_field_refs_map.get(module, 0)+ current_type_refs = current_type_refs_map.get(module, 0)++ should_start_new_dex = False+ if dex_weight_limit is not None:+ if current_size + weight_estimate > dex_weight_limit:+ should_start_new_dex = True+ if current_method_refs + method_ref_count > DEX_REF_LIMIT:+ should_start_new_dex = True+ if current_field_refs + field_ref_count > DEX_REF_LIMIT:+ should_start_new_dex = True+ if current_type_refs + type_ref_count > DEX_REF_LIMIT:+ should_start_new_dex = True++ # Guard: only split when dex_weight_limit is not None.+ # For primary dex without bootstrap, dex_weight_limit is None.+ # Extra primary groups become bootstrap dexes in assets/+ # (dex_rules.bzl primary_dex_inputs[1:]), without bootstrap+ # classloader -> ClassNotFoundException, metadata numbering+ # wrong -> mismatched filenames.+ if should_start_new_dex:+ current_size = 0+ current_method_refs = 0+ current_field_refs = 0+ current_type_refs = 0+ current_inputs_map[module] = []++ current_inputs = current_inputs_map.setdefault(module, [])+ if len(current_inputs) == 0:+ dest.append(current_inputs)++ current_size_map[module] = current_size + weight_estimate+ current_method_refs_map[module] = current_method_refs + method_ref_count+ current_field_refs_map[module] = current_field_refs + field_ref_count+ current_type_refs_map[module] = current_type_refs + type_ref_count+ current_inputs.append({"id": lib_id, "class_names": dex_class_names})+++def _organize_lib(+ dest: list[DexGroup],+ module: str,+ lib_id: str,+ weight_estimate: int,+ dex_class_names: list[str],+ current_size_map: dict[str, int],+ current_inputs_map: dict[str, DexGroup],+ dex_weight_limit: Optional[int],+ method_ref_count: int,+ field_ref_count: int,+ type_ref_count: int,+ current_method_refs_map: dict[str, int],+ current_field_refs_map: dict[str, int],+ current_type_refs_map: dict[str, int],+) -> None:+ """Organize a lib into dex groups, chunking classes if weight or ref counts exceed limits."""+ if len(dex_class_names) == 0:+ return++ is_oversized = False+ if dex_weight_limit is not None:+ if weight_estimate > dex_weight_limit:+ is_oversized = True+ if method_ref_count > DEX_REF_LIMIT:+ is_oversized = True+ if field_ref_count > DEX_REF_LIMIT:+ is_oversized = True+ if type_ref_count > DEX_REF_LIMIT:+ is_oversized = True++ if is_oversized:+ num_classes = len(dex_class_names)+ chunks = max(+ weight_estimate / dex_weight_limit if dex_weight_limit else 1,+ method_ref_count / DEX_REF_LIMIT if method_ref_count > DEX_REF_LIMIT else 1,+ field_ref_count / DEX_REF_LIMIT if field_ref_count > DEX_REF_LIMIT else 1,+ type_ref_count / DEX_REF_LIMIT if type_ref_count > DEX_REF_LIMIT else 1,+ )+ chunk_size = max(1, int(num_classes // chunks))+ for start_index in range(0, num_classes, chunk_size):+ end_index = min(start_index + chunk_size, num_classes)+ chunked = dex_class_names[start_index:end_index]+ _assign_to_dex(+ dest,+ module,+ lib_id,+ weight_estimate,+ chunked,+ current_size_map,+ current_inputs_map,+ dex_weight_limit,+ method_ref_count,+ field_ref_count,+ type_ref_count,+ current_method_refs_map,+ current_field_refs_map,+ current_type_refs_map,+ )+ else:+ _assign_to_dex(+ dest,+ module,+ lib_id,+ weight_estimate,+ dex_class_names,+ current_size_map,+ current_inputs_map,+ dex_weight_limit,+ method_ref_count,+ field_ref_count,+ type_ref_count,+ current_method_refs_map,+ current_field_refs_map,+ current_type_refs_map,+ )+++def _sort_pre_dexed_files(+ filter_dex_data: FilterDexData,+ lib_metadata: LibMetadata,+ target_to_module: TargetToModule,+ weight_limit: int,+ enable_bootstrap_dexes: bool,+) -> dict[str, ModuleSortResult]:+ """+ Sort pre-dexed files into primary and secondary dex groups per module.++ This is a Python port of the _sort_pre_dexed_files Starlark function+ from dex_rules.bzl.+ """+ sorted_inputs: dict[str, ModuleSortResult] = {}++ current_primary_dex_size: dict[str, int] = {}+ current_primary_dex_inputs: dict[str, DexGroup] = {}+ current_secondary_dex_size: dict[str, int] = {}+ current_secondary_dex_inputs: dict[str, DexGroup] = {}++ current_primary_method_refs: dict[str, int] = {}+ current_primary_field_refs: dict[str, int] = {}+ current_primary_type_refs: dict[str, int] = {}+ current_secondary_method_refs: dict[str, int] = {}+ current_secondary_field_refs: dict[str, int] = {}+ current_secondary_type_refs: dict[str, int] = {}++ # Process libs in the same order as the original Starlark code, which iterates+ # pre_dexed_libs in order. lib_metadata preserves this order (written from+ # pre_dexed_libs iteration). We iterate lib_metadata keys and look up filter data.+ for identifier in lib_metadata:+ filter_info = filter_dex_data.get(identifier)+ if filter_info is None:+ continue+ owner_target = lib_metadata[identifier]++ module = target_to_module.get(owner_target, ROOT_MODULE)+ if module not in sorted_inputs:+ sorted_inputs[module] = {+ "primary_groups": [],+ "secondary_groups": [],+ }++ primary_dex_class_names: list[str] = filter_info["primary_dex_class_names"]+ secondary_dex_class_names: list[str] = filter_info["secondary_dex_class_names"]+ weight_estimate = int(filter_info["weight_estimate"])+ lib_method_refs = int(filter_info["method_ref_count"])+ lib_field_refs = int(filter_info["field_ref_count"])+ lib_type_refs = int(filter_info["type_ref_count"])++ module_inputs = sorted_inputs[module]++ if len(primary_dex_class_names) > 0 and module != ROOT_MODULE:+ # Non-root modules shouldn't have primary dex classes; move to secondary+ secondary_dex_class_names = (+ secondary_dex_class_names + primary_dex_class_names+ )+ primary_dex_class_names = []++ # Organize primary dex classes+ _organize_lib(+ module_inputs["primary_groups"],+ module,+ identifier,+ weight_estimate,+ primary_dex_class_names,+ current_primary_dex_size,+ current_primary_dex_inputs,+ weight_limit if enable_bootstrap_dexes else None,+ lib_method_refs,+ lib_field_refs,+ lib_type_refs,+ current_primary_method_refs,+ current_primary_field_refs,+ current_primary_type_refs,+ )++ # Organize secondary dex classes+ _organize_lib(+ module_inputs["secondary_groups"],+ module,+ identifier,+ weight_estimate,+ secondary_dex_class_names,+ current_secondary_dex_size,+ current_secondary_dex_inputs,+ weight_limit,+ lib_method_refs,+ lib_field_refs,+ lib_type_refs,+ current_secondary_method_refs,+ current_secondary_field_refs,+ current_secondary_type_refs,+ )++ return sorted_inputs+++def _flatten_groups(groups: list[DexGroup]) -> list[FlatGroup]:+ """Convert list of [{id, class_names}, ...] to {lib_ids: [...], class_names: [...]}."""+ result: list[FlatGroup] = []+ for group in groups:+ lib_ids: list[str] = [str(entry["id"]) for entry in group]+ class_names: list[str] = []+ for entry in group:+ # pyre-ignore[6]: entry["class_names"] is always list[str]+ class_names.extend(entry["class_names"])+ result.append({"lib_ids": lib_ids, "class_names": class_names})+ return result+++def main() -> None:+ args = _parse_args()++ # Read all filter_dex JSON outputs and merge them+ merged_filter_data: FilterDexData = {}+ for filter_output_path in args.filter_dex_outputs:+ with open(filter_output_path) as f:+ batch_data = json.load(f)+ merged_filter_data.update(batch_data)++ # Read lib metadata (identifier -> owner target label)+ with open(args.lib_metadata) as f:+ lib_metadata: LibMetadata = json.load(f)++ # Parse module graph+ target_to_module, module_metadata = _parse_module_graph(args.module_graph)++ # Sort pre-dexed files into groups+ sorted_inputs = _sort_pre_dexed_files(+ merged_filter_data,+ lib_metadata,+ target_to_module,+ args.weight_limit,+ args.enable_bootstrap_dexes,+ )++ # Flatten groups for JSON output+ modules_output = []+ for module, data in sorted_inputs.items():+ modules_output.append(+ {+ "module": module,+ "primary_groups": _flatten_groups(data["primary_groups"]),+ "secondary_groups": _flatten_groups(data["secondary_groups"]),+ }+ )++ plan = {+ "modules": modules_output,+ "module_metadata": module_metadata,+ }++ with open(args.output, "w") as f:+ json.dump(plan, f)+++if __name__ == "__main__":+ main()
@@ -0,0 +1,31 @@+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("android_devxx")++source_listing()++prelude = native++prelude.python_test(+ name = "test_sort_pre_dexed_files",+ srcs = ["test_sort_pre_dexed_files.py"],+ deps = [+ "prelude//android/tools:sort_pre_dexed_files_lib",+ ],+)++prelude.python_test(+ name = "test_filter_dex",+ srcs = ["test_filter_dex.py"],+ deps = [+ "prelude//android/tools:filter_dex_lib",+ ],+)++prelude.python_test(+ name = "test_combine_apk_with_relinked_libs",+ srcs = ["test_combine_apk_with_relinked_libs.py"],+ deps = [+ "prelude//android/tools:combine_apk_with_relinked_libs_lib",+ ],+)
@@ -0,0 +1,284 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""Tests for combine_apk_with_relinked_libs.py.++Covers the core replacement logic: flat ZIP .so replacement, nested ZIP/JAR+replacement, error on unreplaced libraries, and the empty-mapping passthrough.+"""++from __future__ import annotations++import io+import json+import os+import tempfile+import unittest+import zipfile++from android.tools.combine_apk_with_relinked_libs import (+ _build_relinked_lookup,+ _find_matching_key,+ _maybe_rebuild_inner_zip,+ main,+)+++def _make_so_bytes(tag: str) -> bytes:+ """Return distinguishable fake .so content."""+ return f"ELF-{tag}".encode()+++class BuildRelinkedLookupTest(unittest.TestCase):+ """Tests for _build_relinked_lookup."""++ def test_maps_existing_files(self) -> None:+ with tempfile.TemporaryDirectory() as d:+ abi_dir = os.path.join(d, "arm64-v8a")+ os.makedirs(abi_dir)+ so_path = os.path.join(abi_dir, "libfoo.so")+ with open(so_path, "wb") as f:+ f.write(b"data")++ result = _build_relinked_lookup(["arm64-v8a/libfoo.so"], d)+ self.assertEqual(result, {"arm64-v8a/libfoo.so": so_path})++ def test_raises_on_missing_files(self) -> None:+ with tempfile.TemporaryDirectory() as d:+ with self.assertRaises(RuntimeError):+ _build_relinked_lookup(["arm64-v8a/libmissing.so"], d)++ def test_empty_mapping(self) -> None:+ with tempfile.TemporaryDirectory() as d:+ result = _build_relinked_lookup([], d)+ self.assertEqual(result, {})+++class FindMatchingKeyTest(unittest.TestCase):+ """Tests for _find_matching_key."""++ def test_exact_match(self) -> None:+ lookup = {"arm64-v8a/libfoo.so": "/path"}+ self.assertEqual(+ _find_matching_key("arm64-v8a/libfoo.so", lookup), "arm64-v8a/libfoo.so"+ )++ def test_suffix_match(self) -> None:+ lookup = {"arm64-v8a/libfoo.so": "/path"}+ self.assertEqual(+ _find_matching_key("lib/arm64-v8a/libfoo.so", lookup),+ "arm64-v8a/libfoo.so",+ )++ def test_deep_suffix_match(self) -> None:+ lookup = {"arm64-v8a/libfoo.so": "/path"}+ self.assertEqual(+ _find_matching_key("assets/module/lib/arm64-v8a/libfoo.so", lookup),+ "arm64-v8a/libfoo.so",+ )++ def test_no_match(self) -> None:+ lookup = {"arm64-v8a/libfoo.so": "/path"}+ self.assertIsNone(_find_matching_key("arm64-v8a/libbar.so", lookup))++ def test_partial_name_no_false_match(self) -> None:+ lookup = {"arm64-v8a/libfoo.so": "/path"}+ # "xarm64-v8a/libfoo.so" should NOT match because "/" separator is required+ self.assertIsNone(_find_matching_key("xarm64-v8a/libfoo.so", lookup))+++class MaybeRebuildInnerZipTest(unittest.TestCase):+ """Tests for _maybe_rebuild_inner_zip."""++ def test_returns_none_when_no_match(self) -> None:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("lib/arm64-v8a/libbar.so", b"data")+ lookup = {"arm64-v8a/libfoo.so": "/path"}+ self.assertIsNone(_maybe_rebuild_inner_zip(buf.getvalue(), lookup))++ def test_returns_none_for_bad_zip(self) -> None:+ lookup = {"arm64-v8a/libfoo.so": "/path"}+ self.assertIsNone(_maybe_rebuild_inner_zip(b"not a zip", lookup))++ def test_replaces_matching_entry(self) -> None:+ original = _make_so_bytes("original")+ relinked = _make_so_bytes("relinked")++ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("lib/arm64-v8a/libfoo.so", original)+ zf.writestr("classes.dex", b"dex-data")++ with tempfile.TemporaryDirectory() as d:+ abi_dir = os.path.join(d, "arm64-v8a")+ os.makedirs(abi_dir)+ with open(os.path.join(abi_dir, "libfoo.so"), "wb") as f:+ f.write(relinked)++ lookup = {"arm64-v8a/libfoo.so": os.path.join(abi_dir, "libfoo.so")}+ result = _maybe_rebuild_inner_zip(buf.getvalue(), lookup)++ self.assertIsNotNone(result)+ result_bytes, replaced = result+ self.assertIn("arm64-v8a/libfoo.so", replaced)++ with zipfile.ZipFile(io.BytesIO(result_bytes), "r") as zout:+ self.assertEqual(zout.read("lib/arm64-v8a/libfoo.so"), relinked)+ self.assertEqual(zout.read("classes.dex"), b"dex-data")+++class MainIntegrationTest(unittest.TestCase):+ """Integration tests for the main() entry point."""++ def _run_combine(+ self,+ tmpdir: str,+ input_entries: dict[str, bytes],+ mapping: list[str],+ relinked_files: dict[str, bytes],+ ) -> str:+ """Build input APK, mapping JSON, relinked libs dir, run main(), return output path."""+ # Create input APK+ input_path = os.path.join(tmpdir, "input.apk")+ with zipfile.ZipFile(input_path, "w") as zf:+ for name, data in input_entries.items():+ zf.writestr(name, data)++ # Create relinked libs directory+ relinked_dir = os.path.join(tmpdir, "relinked_libs")+ for rel_path, data in relinked_files.items():+ full_path = os.path.join(relinked_dir, rel_path)+ os.makedirs(os.path.dirname(full_path), exist_ok=True)+ with open(full_path, "wb") as f:+ f.write(data)++ # Create mapping JSON+ mapping_path = os.path.join(tmpdir, "mapping.json")+ with open(mapping_path, "w") as f:+ json.dump(mapping, f)++ output_path = os.path.join(tmpdir, "output.apk")++ import sys++ old_argv = sys.argv+ sys.argv = [+ "combine_apk_with_relinked_libs.py",+ "--input",+ input_path,+ "--relinked-libs-dir",+ relinked_dir,+ "--mapping",+ mapping_path,+ "--output",+ output_path,+ ]+ try:+ main()+ finally:+ sys.argv = old_argv++ return output_path++ def test_flat_so_replacement(self) -> None:+ """Standard lib/<abi>/<soname> entries are replaced."""+ original = _make_so_bytes("original")+ relinked = _make_so_bytes("relinked")++ with tempfile.TemporaryDirectory() as tmpdir:+ output = self._run_combine(+ tmpdir,+ input_entries={+ "lib/arm64-v8a/libfoo.so": original,+ "classes.dex": b"dex-data",+ },+ mapping=["arm64-v8a/libfoo.so"],+ relinked_files={"arm64-v8a/libfoo.so": relinked},+ )++ with zipfile.ZipFile(output, "r") as zf:+ self.assertEqual(zf.read("lib/arm64-v8a/libfoo.so"), relinked)+ self.assertEqual(zf.read("classes.dex"), b"dex-data")++ def test_nested_jar_replacement(self) -> None:+ """Libraries inside nested JARs are replaced."""+ original = _make_so_bytes("original")+ relinked = _make_so_bytes("relinked")++ inner_jar = io.BytesIO()+ with zipfile.ZipFile(inner_jar, "w") as zf:+ zf.writestr("lib/arm64-v8a/libfoo.so", original)++ with tempfile.TemporaryDirectory() as tmpdir:+ output = self._run_combine(+ tmpdir,+ input_entries={+ "module.jar": inner_jar.getvalue(),+ "classes.dex": b"dex-data",+ },+ mapping=["arm64-v8a/libfoo.so"],+ relinked_files={"arm64-v8a/libfoo.so": relinked},+ )++ with zipfile.ZipFile(output, "r") as zf:+ inner_bytes = zf.read("module.jar")+ with zipfile.ZipFile(io.BytesIO(inner_bytes), "r") as inner:+ self.assertEqual(inner.read("lib/arm64-v8a/libfoo.so"), relinked)++ def test_empty_mapping_copies_input(self) -> None:+ """When the mapping is empty, the output should be a copy of the input."""+ with tempfile.TemporaryDirectory() as tmpdir:+ input_path = os.path.join(tmpdir, "input.apk")+ with zipfile.ZipFile(input_path, "w") as zf:+ zf.writestr("classes.dex", b"dex-data")++ mapping_path = os.path.join(tmpdir, "mapping.json")+ with open(mapping_path, "w") as f:+ json.dump([], f)++ # Create an empty relinked dir+ relinked_dir = os.path.join(tmpdir, "relinked_libs")+ os.makedirs(relinked_dir)++ output_path = os.path.join(tmpdir, "output.apk")++ import sys++ old_argv = sys.argv+ sys.argv = [+ "combine_apk_with_relinked_libs.py",+ "--input",+ input_path,+ "--relinked-libs-dir",+ relinked_dir,+ "--mapping",+ mapping_path,+ "--output",+ output_path,+ ]+ try:+ main()+ finally:+ sys.argv = old_argv++ with zipfile.ZipFile(output_path, "r") as zf:+ self.assertEqual(zf.read("classes.dex"), b"dex-data")++ def test_unreplaced_library_raises(self) -> None:+ """If a mapped library is not found in the input APK, a RuntimeError is raised."""+ with tempfile.TemporaryDirectory() as tmpdir:+ with self.assertRaises(RuntimeError):+ self._run_combine(+ tmpdir,+ input_entries={+ "classes.dex": b"dex-data",+ },+ mapping=["arm64-v8a/libfoo.so"],+ relinked_files={"arm64-v8a/libfoo.so": b"relinked"},+ )
@@ -0,0 +1,114 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""Tests for filter_dex.py.++Covers primary-dex membership for the synthetic classes D8 creates. The synthetic names used+here deliberately do not resemble D8's actual mangling -- membership must come from the+synthetic-to-context map D8 reports, never from the shape of the name.+"""++from __future__ import annotations++import os+import tempfile+import unittest++from android.tools.filter_dex import (+ _belongs_in_primary_dex,+ _parse_synthetic_contexts,+ _resolve_synthesizing_context,+ ClassNameFilter,+)+++class ParseSyntheticContextsTest(unittest.TestCase):+ def _parse(self, contents: str) -> dict[str, str]:+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "synthetic_contexts.txt")+ with open(path, "w") as f:+ f.write(contents)+ return _parse_synthetic_contexts(path)++ def test_parses_pairs(self) -> None:+ self.assertEqual(+ self._parse("a/zzz0 a/Foo\nb/zzz1 b/Bar\n"),+ {"a/zzz0": "a/Foo", "b/zzz1": "b/Bar"},+ )++ def test_empty_file_yields_empty_map(self) -> None:+ self.assertEqual(self._parse(""), {})++ def test_blank_lines_are_skipped(self) -> None:+ self.assertEqual(self._parse("\na/zzz0 a/Foo\n\n"), {"a/zzz0": "a/Foo"})++ def test_line_without_context_is_rejected(self) -> None:+ with self.assertRaises(ValueError):+ self._parse("a/zzz0\n")+++class ResolveSynthesizingContextTest(unittest.TestCase):+ def test_non_synthetic_resolves_to_itself(self) -> None:+ self.assertEqual(_resolve_synthesizing_context("a/Foo", {}), "a/Foo")++ def test_single_hop(self) -> None:+ self.assertEqual(+ _resolve_synthesizing_context("a/zzz0", {"a/zzz0": "a/Foo"}), "a/Foo"+ )++ def test_chained_synthetics_resolve_to_the_root_context(self) -> None:+ # D8 can synthesize from a synthetic, so the chain has to be walked to its end.+ chain = {"a/zzz1": "a/zzz0", "a/zzz0": "a/Foo"}+ self.assertEqual(_resolve_synthesizing_context("a/zzz1", chain), "a/Foo")++ def test_cycle_terminates(self) -> None:+ cycle = {"a/zzz0": "a/zzz1", "a/zzz1": "a/zzz0"}+ self.assertIn(_resolve_synthesizing_context("a/zzz0", cycle), cycle)+++class BelongsInPrimaryDexTest(unittest.TestCase):+ def _belongs(self, java_class, patterns, synthetic_to_context=None) -> bool:+ return _belongs_in_primary_dex(+ java_class, ClassNameFilter(patterns), synthetic_to_context or {}+ )++ def test_class_matching_a_prefix_pattern(self) -> None:+ self.assertTrue(self._belongs("a/Foo", ["^a/"]))++ def test_class_matching_a_suffix_pattern(self) -> None:+ self.assertTrue(self._belongs("a/Foo", ["Foo^"]))++ def test_class_matching_a_substring_pattern(self) -> None:+ self.assertTrue(self._belongs("a/Foo", ["/Fo"]))++ def test_class_matching_a_regex_pattern(self) -> None:+ self.assertTrue(self._belongs("a/Foo", ["^-a/F.*"]))++ def test_unmatched_class_stays_out(self) -> None:+ self.assertFalse(self._belongs("b/Bar", ["^a/"]))++ def test_synthetic_follows_its_context_into_the_primary_dex(self) -> None:+ self.assertTrue(self._belongs("b/zzz0", ["^a/"], {"b/zzz0": "a/Foo"}))++ def test_synthetic_of_a_secondary_class_stays_out(self) -> None:+ self.assertFalse(self._belongs("b/zzz0", ["^a/"], {"b/zzz0": "b/Bar"}))++ def test_chained_synthetic_follows_its_root_context(self) -> None:+ chain = {"b/zzz1": "b/zzz0", "b/zzz0": "a/Foo"}+ self.assertTrue(self._belongs("b/zzz1", ["^a/"], chain))++ def test_pattern_naming_a_synthetic_directly_still_matches(self) -> None:+ # Some primary_dex_patterns name a D8 synthetic outright. Those must keep working even+ # though the synthetic's context is not itself in the primary dex.+ self.assertTrue(+ self._belongs(+ "androidx/Foo$ExternalSyntheticLambda0",+ ["^androidx/Foo$ExternalSyntheticLambda0^"],+ {"androidx/Foo$ExternalSyntheticLambda0": "androidx/Foo"},+ )+ )
@@ -0,0 +1,725 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Tests for sort_pre_dexed_files.py — the Python tool that replaces the+_sort_pre_dexed_files Starlark function in dex_rules.bzl.++The tool reads filter_dex JSON outputs and a lib metadata JSON, then sorts+pre-dexed libraries into primary/secondary dex groups per module, producing+a dex_plan.json consumed by the merge_pre_dexed_libs dynamic lambda.++Test structure:+ - SortPreDexedFilesTest: unit tests for the core sorting logic+ - ParseModuleGraphTest: unit tests for module graph file parsing+ - EndToEndToolTest: integration tests running the tool as a subprocess+"""++import json+import os+import subprocess+import tempfile+import unittest++from android.tools.sort_pre_dexed_files import (+ _flatten_groups,+ _parse_module_graph,+ _sort_pre_dexed_files,+)++# Path to the tool script, relative to the link-tree layout+_TOOL_MODULE_PATH = os.path.join(+ os.path.dirname(__file__), "..", "sort_pre_dexed_files.py"+)++_DEFAULT_WEIGHT_LIMIT = 12 * 1024 * 1024 # 12 MiB, matches Buck default++_DEFAULT_REF_COUNTS = {+ "method_ref_count": "0",+ "field_ref_count": "0",+ "type_ref_count": "0",+}+++def _add_default_ref_counts(filter_data):+ """Add default zero ref counts to any filter_data entries missing them."""+ for info in filter_data.values():+ for key, default_val in _DEFAULT_REF_COUNTS.items():+ if key not in info:+ info[key] = default_val+ return filter_data+++def _sort(filter_data, lib_metadata, target_to_module=None, **kwargs):+ """Convenience wrapper with defaults for _sort_pre_dexed_files."""+ _add_default_ref_counts(filter_data)+ return _sort_pre_dexed_files(+ filter_data,+ lib_metadata,+ target_to_module or {},+ weight_limit=kwargs.get("weight_limit", _DEFAULT_WEIGHT_LIMIT),+ enable_bootstrap_dexes=kwargs.get("enable_bootstrap_dexes", False),+ )+++class SortPreDexedFilesTest(unittest.TestCase):+ """Unit tests for _sort_pre_dexed_files — the core sorting logic.++ The function takes:+ - filter_data: merged filter_dex JSON (identifier -> class names + weight)+ - lib_metadata: identifier -> owner target label (controls iteration order)+ - target_to_module: target -> module name (from module graph)+ - weight_limit: max bytes per dex group before spilling+ - enable_bootstrap_dexes: whether to apply weight limit to primary dex too++ It returns: module -> {primary_groups: [...], secondary_groups: [...]}+ where each group is a list of {id, class_names} entries.+ """++ # --- Basic grouping ---++ def test_single_lib_primary_and_secondary(self):+ """A single lib with both primary and secondary classes produces one+ group in each category under the root module ("dex")."""+ filter_data = {+ "lib1": {+ "primary_dex_class_names": ["com.example.Main"],+ "secondary_dex_class_names": ["com.example.Helper"],+ "weight_estimate": "1000",+ },+ }+ result = _sort(filter_data, {"lib1": "//apps:lib1"})++ self.assertIn("dex", result)+ self.assertEqual(len(result["dex"]["primary_groups"]), 1)+ self.assertEqual(len(result["dex"]["secondary_groups"]), 1)+ self.assertEqual(+ result["dex"]["primary_groups"][0][0]["class_names"], ["com.example.Main"]+ )+ self.assertEqual(+ result["dex"]["secondary_groups"][0][0]["class_names"],+ ["com.example.Helper"],+ )++ def test_multiple_libs_grouped_under_weight_limit(self):+ """Multiple small libs whose combined weight is under the limit should+ land in the same secondary dex group."""+ filter_data = {+ "lib1": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": ["com.A"],+ "weight_estimate": "100",+ },+ "lib2": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": ["com.B"],+ "weight_estimate": "100",+ },+ }+ result = _sort(filter_data, {"lib1": "//apps:lib1", "lib2": "//apps:lib2"})++ self.assertEqual(len(result["dex"]["secondary_groups"]), 1)+ self.assertEqual(len(result["dex"]["secondary_groups"][0]), 2)++ def test_empty_class_names_produce_no_groups(self):+ """Libs with empty primary and secondary class names should not create+ any dex groups — they are effectively no-ops."""+ filter_data = {+ "lib1": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": [],+ "weight_estimate": "0",+ },+ }+ result = _sort(filter_data, {"lib1": "//apps:lib1"})++ self.assertEqual(len(result.get("dex", {}).get("primary_groups", [])), 0)+ self.assertEqual(len(result.get("dex", {}).get("secondary_groups", [])), 0)++ # --- Weight-based splitting ---++ def test_weight_limit_splits_secondary_groups(self):+ """When cumulative weight of libs exceeds the limit, subsequent libs+ should spill into a new secondary dex group."""+ filter_data = {+ "lib1": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": ["com.A"],+ "weight_estimate": "600",+ },+ "lib2": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": ["com.B"],+ "weight_estimate": "600",+ },+ }+ result = _sort(+ filter_data,+ {"lib1": "//apps:lib1", "lib2": "//apps:lib2"},+ weight_limit=1000,+ )++ # lib1 (600) + lib2 (600) = 1200 > 1000 limit+ self.assertEqual(len(result["dex"]["secondary_groups"]), 2)++ def test_bootstrap_dexes_applies_weight_limit_to_primary(self):+ """With enable_bootstrap_dexes=True, the weight limit also applies to+ primary dex groups, splitting them when exceeded."""+ filter_data = {+ "lib1": {+ "primary_dex_class_names": ["com.A"],+ "secondary_dex_class_names": [],+ "weight_estimate": "600",+ },+ "lib2": {+ "primary_dex_class_names": ["com.B"],+ "secondary_dex_class_names": [],+ "weight_estimate": "600",+ },+ }+ result = _sort(+ filter_data,+ {"lib1": "//apps:lib1", "lib2": "//apps:lib2"},+ weight_limit=1000,+ enable_bootstrap_dexes=True,+ )++ # 600 + 600 = 1200 > 1000 -> splits into 2 primary groups+ self.assertEqual(len(result["dex"]["primary_groups"]), 2)++ def test_large_lib_classes_chunked_across_groups(self):+ """A single lib whose weight exceeds the limit should have its classes+ chunked across multiple groups. All classes must be preserved."""+ classes = ["com.Class{}".format(i) for i in range(10)]+ filter_data = {+ "lib1": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": classes,+ "weight_estimate": "2500",+ },+ }+ result = _sort(filter_data, {"lib1": "//apps:lib1"}, weight_limit=1000)++ # 2500 > 1000 -> classes chunked across multiple groups+ self.assertGreater(len(result["dex"]["secondary_groups"]), 1)+ all_classes = []+ for group in result["dex"]["secondary_groups"]:+ for entry in group:+ all_classes.extend(entry["class_names"])+ self.assertCountEqual(all_classes, classes)++ # --- Module assignment ---++ def test_non_root_module_primary_classes_moved_to_secondary(self):+ """Primary dex classes assigned to a non-root module are relocated to+ that module's secondary dex. Only the root module ("dex") may have+ primary dex classes."""+ filter_data = {+ "lib1": {+ "primary_dex_class_names": ["com.feature.Primary"],+ "secondary_dex_class_names": ["com.feature.Secondary"],+ "weight_estimate": "1000",+ },+ }+ result = _sort(+ filter_data,+ {"lib1": "//apps:lib1"},+ target_to_module={"//apps:lib1": "feature_module"},+ )++ self.assertIn("feature_module", result)+ self.assertEqual(len(result["feature_module"]["primary_groups"]), 0)+ all_secondary_classes = []+ for group in result["feature_module"]["secondary_groups"]:+ for entry in group:+ all_secondary_classes.extend(entry["class_names"])+ self.assertIn("com.feature.Primary", all_secondary_classes)+ self.assertIn("com.feature.Secondary", all_secondary_classes)++ def test_multiple_modules_separated(self):+ """Libs assigned to different modules via the target-to-module mapping+ should be placed in separate module entries."""+ filter_data = {+ "lib1": {+ "primary_dex_class_names": ["com.main.Main"],+ "secondary_dex_class_names": [],+ "weight_estimate": "1000",+ },+ "lib2": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": ["com.feature.Impl"],+ "weight_estimate": "1000",+ },+ }+ result = _sort(+ filter_data,+ {"lib1": "//apps:lib1", "lib2": "//apps:lib2"},+ target_to_module={"//apps:lib1": "dex", "//apps:lib2": "feature1"},+ )++ self.assertIn("dex", result)+ self.assertIn("feature1", result)+ self.assertEqual(len(result["dex"]["primary_groups"]), 1)+ self.assertEqual(len(result["feature1"]["secondary_groups"]), 1)++ def test_unmapped_target_defaults_to_root_module(self):+ """Libs whose owner target is not in the target-to-module mapping+ should default to the root module ("dex")."""+ filter_data = {+ "lib1": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": ["com.Unknown"],+ "weight_estimate": "100",+ },+ }+ # target_to_module has an entry for a different target, not lib1's owner+ result = _sort(+ filter_data,+ {"lib1": "//apps:lib1"},+ target_to_module={"//other:target": "feature1"},+ )++ self.assertIn("dex", result)+ self.assertNotIn("feature1", result)+ self.assertEqual(len(result["dex"]["secondary_groups"]), 1)++ # --- Ref-count-based splitting ---++ def test_ref_count_splits_secondary_groups(self):+ """When cumulative method ref count exceeds DEX_REF_LIMIT (65536),+ subsequent libs should spill into a new secondary dex group, even+ if weight is well under the weight limit."""+ filter_data = {+ "lib1": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": ["com.A"],+ "weight_estimate": "100",+ "method_ref_count": "40000",+ "field_ref_count": "0",+ "type_ref_count": "0",+ },+ "lib2": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": ["com.B"],+ "weight_estimate": "100",+ "method_ref_count": "40000",+ "field_ref_count": "0",+ "type_ref_count": "0",+ },+ }+ result = _sort(+ filter_data,+ {"lib1": "//apps:lib1", "lib2": "//apps:lib2"},+ weight_limit=_DEFAULT_WEIGHT_LIMIT,+ )++ # 40000 + 40000 = 80000 > 65536 -> splits into 2 secondary groups+ self.assertEqual(len(result["dex"]["secondary_groups"]), 2)++ def test_high_ref_counts_do_not_split_primary_without_bootstrap(self):+ """Without enable_bootstrap_dexes, primary dex groups must NOT be+ split even when ref counts exceed the limit. Splitting primary+ without the bootstrap classloader causes ClassNotFoundException."""+ filter_data = {+ "lib1": {+ "primary_dex_class_names": ["com.A"],+ "secondary_dex_class_names": [],+ "weight_estimate": "100",+ "method_ref_count": "40000",+ "field_ref_count": "0",+ "type_ref_count": "0",+ },+ "lib2": {+ "primary_dex_class_names": ["com.B"],+ "secondary_dex_class_names": [],+ "weight_estimate": "100",+ "method_ref_count": "40000",+ "field_ref_count": "0",+ "type_ref_count": "0",+ },+ }+ result = _sort(+ filter_data,+ {"lib1": "//apps:lib1", "lib2": "//apps:lib2"},+ weight_limit=_DEFAULT_WEIGHT_LIMIT,+ enable_bootstrap_dexes=False,+ )++ # Without bootstrap, primary must stay in a single group+ self.assertEqual(len(result["dex"]["primary_groups"]), 1)++ def test_large_lib_chunked_by_ref_count(self):+ """A single lib whose method ref count exceeds DEX_REF_LIMIT should+ have its classes chunked across multiple groups, similar to+ weight-based chunking."""+ classes = ["com.Class{}".format(i) for i in range(10)]+ filter_data = {+ "lib1": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": classes,+ "weight_estimate": "100",+ "method_ref_count": "200000",+ "field_ref_count": "0",+ "type_ref_count": "0",+ },+ }+ result = _sort(+ filter_data, {"lib1": "//apps:lib1"}, weight_limit=_DEFAULT_WEIGHT_LIMIT+ )++ # 200000 > 65536 -> classes chunked across multiple groups+ self.assertGreater(len(result["dex"]["secondary_groups"]), 1)+ all_classes = []+ for group in result["dex"]["secondary_groups"]:+ for entry in group:+ all_classes.extend(entry["class_names"])+ self.assertCountEqual(all_classes, classes)++ # --- Ordering and skipping ---++ def test_iteration_order_follows_lib_metadata_keys(self):+ """Libs should be processed in lib_metadata key insertion order, not+ filter_data order. This is critical for deterministic dex assignment."""+ filter_data = {+ "lib_b": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": ["com.B"],+ "weight_estimate": "600",+ },+ "lib_a": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": ["com.A"],+ "weight_estimate": "600",+ },+ }+ # lib_a first in metadata -> processed first -> gets first group+ lib_metadata = {"lib_a": "//apps:lib_a", "lib_b": "//apps:lib_b"}+ result = _sort(filter_data, lib_metadata, weight_limit=1000)++ self.assertEqual(len(result["dex"]["secondary_groups"]), 2)+ self.assertEqual(+ result["dex"]["secondary_groups"][0][0]["class_names"], ["com.A"]+ )+ self.assertEqual(+ result["dex"]["secondary_groups"][1][0]["class_names"], ["com.B"]+ )++ def test_lib_in_metadata_but_not_filter_data_skipped(self):+ """Libs present in lib_metadata but absent from filter_data (e.g.,+ libs with no dex output) should be silently skipped."""+ filter_data = {+ "lib1": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": ["com.A"],+ "weight_estimate": "100",+ },+ }+ # lib2 in metadata but not in filter_data+ result = _sort(filter_data, {"lib1": "//apps:lib1", "lib2": "//apps:lib2"})++ self.assertEqual(len(result["dex"]["secondary_groups"]), 1)+ self.assertEqual(result["dex"]["secondary_groups"][0][0]["id"], "lib1")+++class FlattenGroupsTest(unittest.TestCase):+ """Unit tests for _flatten_groups — converts the internal per-entry+ representation [{id, class_names}, ...] into the plan JSON format+ {lib_ids: [...], class_names: [...]} per group."""++ def test_single_group_single_entry(self):+ groups = [[{"id": "lib1", "class_names": ["com.A", "com.B"]}]]+ result = _flatten_groups(groups)+ self.assertEqual(len(result), 1)+ self.assertEqual(result[0]["lib_ids"], ["lib1"])+ self.assertEqual(result[0]["class_names"], ["com.A", "com.B"])++ def test_single_group_multiple_entries(self):+ """Multiple entries in one group should have their lib_ids and+ class_names concatenated in order."""+ groups = [+ [+ {"id": "lib1", "class_names": ["com.A"]},+ {"id": "lib2", "class_names": ["com.B", "com.C"]},+ ]+ ]+ result = _flatten_groups(groups)+ self.assertEqual(result[0]["lib_ids"], ["lib1", "lib2"])+ self.assertEqual(result[0]["class_names"], ["com.A", "com.B", "com.C"])++ def test_multiple_groups(self):+ groups = [+ [{"id": "lib1", "class_names": ["com.A"]}],+ [{"id": "lib2", "class_names": ["com.B"]}],+ ]+ result = _flatten_groups(groups)+ self.assertEqual(len(result), 2)+ self.assertEqual(result[0]["lib_ids"], ["lib1"])+ self.assertEqual(result[1]["lib_ids"], ["lib2"])++ def test_empty_groups(self):+ self.assertEqual(_flatten_groups([]), [])+++class ParseModuleGraphTest(unittest.TestCase):+ """Unit tests for _parse_module_graph.++ The module graph file format is:+ Line 0: <module_count>+ Lines 1..module_count: <module_name> <canary_class> <dep1> <dep2> ...+ Remaining lines: <target> <module>+ Last line: empty (trailing newline)+ """++ def _write_module_graph(self, content):+ """Write content to a temp file and return its path."""+ f = tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False)+ f.write(content)+ f.close()+ self.addCleanup(os.unlink, f.name)+ return f.name++ def test_none_returns_empty_dicts(self):+ target_to_module, module_metadata = _parse_module_graph(None)+ self.assertEqual(target_to_module, {})+ self.assertEqual(module_metadata, {})++ def test_simple_graph(self):+ """Parse a graph with 2 modules and 2 target mappings."""+ path = self._write_module_graph(+ "2\n"+ "dex com/facebook/CanaryClass dex\n"+ "feature1 com/facebook/feature1/Canary dex\n"+ "//apps:lib1 dex\n"+ "//apps:lib2 feature1\n"+ )+ target_to_module, module_metadata = _parse_module_graph(path)++ self.assertEqual(+ target_to_module,+ {+ "//apps:lib1": "dex",+ "//apps:lib2": "feature1",+ },+ )+ self.assertEqual(+ module_metadata["dex"]["canary_class_name"], "com/facebook/CanaryClass"+ )+ self.assertEqual(module_metadata["dex"]["module_deps"], ["dex"])+ self.assertEqual(module_metadata["feature1"]["module_deps"], ["dex"])++ def test_modules_only_no_target_mappings(self):+ """A module graph with modules defined but no target-to-module mappings+ should produce empty target_to_module but populated module_metadata."""+ path = self._write_module_graph("1\ndex com/CanaryClass dex\n")+ target_to_module, module_metadata = _parse_module_graph(path)++ self.assertEqual(target_to_module, {})+ self.assertIn("dex", module_metadata)++ def test_trailing_newline_does_not_drop_last_mapping(self):+ """The file format ends with a trailing newline. The [:-1] slice in+ _parse_module_graph strips this empty last line. Verify the last+ real target mapping is preserved."""+ path = self._write_module_graph(+ "1\ndex com/CanaryClass dex\n//apps:last_target dex\n"+ )+ target_to_module, _ = _parse_module_graph(path)++ self.assertIn("//apps:last_target", target_to_module)+ self.assertEqual(target_to_module["//apps:last_target"], "dex")+++class EndToEndToolTest(unittest.TestCase):+ """Integration tests running sort_pre_dexed_files.py as a subprocess.++ These verify the full pipeline: arg parsing, file I/O, sorting, and JSON+ output. They complement the unit tests which test internal functions directly.+ """++ def _run_tool(+ self,+ tmpdir,+ filter_data_files,+ lib_metadata,+ weight_limit=_DEFAULT_WEIGHT_LIMIT,+ module_graph=None,+ enable_bootstrap_dexes=False,+ ):+ """Write inputs, run the tool, return parsed plan JSON."""+ # Write filter_dex outputs+ filter_paths = []+ for i, data in enumerate(filter_data_files):+ _add_default_ref_counts(data)+ path = os.path.join(tmpdir, "filter_output_{}.json".format(i))+ with open(path, "w") as f:+ json.dump(data, f)+ filter_paths.append(path)++ # Write lib metadata+ metadata_path = os.path.join(tmpdir, "lib_metadata.json")+ with open(metadata_path, "w") as f:+ json.dump(lib_metadata, f)++ # Build command+ output_path = os.path.join(tmpdir, "plan.json")+ cmd = [+ "python3",+ _TOOL_MODULE_PATH,+ "--filter-dex-outputs",+ *filter_paths,+ "--lib-metadata",+ metadata_path,+ "--weight-limit",+ str(weight_limit),+ "--output",+ output_path,+ ]+ if module_graph:+ graph_path = os.path.join(tmpdir, "module_graph.txt")+ with open(graph_path, "w") as f:+ f.write(module_graph)+ cmd.extend(["--module-graph", graph_path])+ if enable_bootstrap_dexes:+ cmd.append("--enable-bootstrap-dexes")++ result = subprocess.run(cmd, capture_output=True, text=True)+ self.assertEqual(result.returncode, 0, "Tool failed: {}".format(result.stderr))++ with open(output_path) as f:+ return json.load(f)++ def test_basic_plan_output(self):+ """Two libs with primary and secondary classes produce a valid plan+ with correct lib_ids and class_names."""+ with tempfile.TemporaryDirectory() as tmpdir:+ plan = self._run_tool(+ tmpdir,+ filter_data_files=[+ {+ "lib1": {+ "primary_dex_class_names": ["com.Main"],+ "secondary_dex_class_names": ["com.Helper"],+ "weight_estimate": "1000",+ },+ "lib2": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": ["com.Utils"],+ "weight_estimate": "2000",+ },+ }+ ],+ lib_metadata={"lib1": "//apps:lib1", "lib2": "//apps:lib2"},+ )++ self.assertEqual(len(plan["modules"]), 1)+ module = plan["modules"][0]+ self.assertEqual(module["module"], "dex")+ self.assertEqual(module["primary_groups"][0]["lib_ids"], ["lib1"])+ self.assertEqual(module["primary_groups"][0]["class_names"], ["com.Main"])+ self.assertEqual(len(module["secondary_groups"]), 1)+ self.assertIn("lib1", module["secondary_groups"][0]["lib_ids"])+ self.assertIn("lib2", module["secondary_groups"][0]["lib_ids"])++ def test_with_module_graph(self):+ """Libs are correctly assigned to different modules when a module+ graph file is provided."""+ with tempfile.TemporaryDirectory() as tmpdir:+ plan = self._run_tool(+ tmpdir,+ filter_data_files=[+ {+ "lib1": {+ "primary_dex_class_names": ["com.Main"],+ "secondary_dex_class_names": [],+ "weight_estimate": "1000",+ },+ "lib2": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": ["com.Feature"],+ "weight_estimate": "1000",+ },+ }+ ],+ lib_metadata={"lib1": "//apps:lib1", "lib2": "//apps:lib2"},+ module_graph=(+ "2\n"+ "dex com/CanaryClass dex\n"+ "feature1 com/feature1/Canary dex\n"+ "//apps:lib1 dex\n"+ "//apps:lib2 feature1\n"+ ),+ )++ modules_by_name = {m["module"]: m for m in plan["modules"]}+ self.assertIn("dex", modules_by_name)+ self.assertIn("feature1", modules_by_name)+ self.assertEqual(+ modules_by_name["dex"]["primary_groups"][0]["lib_ids"], ["lib1"]+ )+ self.assertEqual(+ modules_by_name["feature1"]["secondary_groups"][0]["lib_ids"], ["lib2"]+ )+ self.assertIn("feature1", plan["module_metadata"])++ def test_multiple_filter_dex_batches(self):+ """The tool should merge multiple --filter-dex-outputs files. Each+ file represents a batch of libs processed by filter_dex in parallel."""+ with tempfile.TemporaryDirectory() as tmpdir:+ batch1 = {+ "lib1": {+ "primary_dex_class_names": ["com.A"],+ "secondary_dex_class_names": [],+ "weight_estimate": "100",+ },+ }+ batch2 = {+ "lib2": {+ "primary_dex_class_names": [],+ "secondary_dex_class_names": ["com.B"],+ "weight_estimate": "100",+ },+ }+ plan = self._run_tool(+ tmpdir,+ filter_data_files=[batch1, batch2],+ lib_metadata={"lib1": "//apps:lib1", "lib2": "//apps:lib2"},+ )++ module = plan["modules"][0]+ # lib1 in primary, lib2 in secondary — both batches merged+ self.assertEqual(module["primary_groups"][0]["lib_ids"], ["lib1"])+ self.assertEqual(module["secondary_groups"][0]["lib_ids"], ["lib2"])++ def test_bootstrap_dexes_cli_flag(self):+ """The --enable-bootstrap-dexes flag should apply weight limit to+ primary dex groups, splitting them when exceeded."""+ with tempfile.TemporaryDirectory() as tmpdir:+ plan = self._run_tool(+ tmpdir,+ filter_data_files=[+ {+ "lib1": {+ "primary_dex_class_names": ["com.A"],+ "secondary_dex_class_names": [],+ "weight_estimate": "600",+ },+ "lib2": {+ "primary_dex_class_names": ["com.B"],+ "secondary_dex_class_names": [],+ "weight_estimate": "600",+ },+ }+ ],+ lib_metadata={"lib1": "//apps:lib1", "lib2": "//apps:lib2"},+ weight_limit=1000,+ enable_bootstrap_dexes=True,+ )++ module = plan["modules"][0]+ # 600 + 600 > 1000 -> 2 primary groups+ self.assertEqual(len(module["primary_groups"]), 2)
@@ -0,0 +1,195 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.+++import argparse+import pathlib+import platform+import shutil+import zipfile+from tempfile import TemporaryDirectory++import utils+++CLASSES_JAR_FILE_NAME = "classes.jar"+ANNOTATIONS_ZIP_FILE_NAME = "annotations.zip"+LIBS_DIR_NAME = "libs"+++def _parse_args():+ parser = argparse.ArgumentParser(+ description="Tool to unpack an aar for android_prebuilt_aar."+ )++ parser.add_argument(+ "--aar", type=pathlib.Path, required=True, help="a path to the aar to unpack"+ )+ parser.add_argument(+ "--manifest-path",+ type=pathlib.Path,+ required=True,+ help="a path to the manifest that is unpacked",+ )+ parser.add_argument(+ "--all-classes-jar-path",+ type=pathlib.Path,+ required=True,+ help="a path to the single output jar containing all the Java classes that this aar contains",+ )+ parser.add_argument(+ "--r-dot-txt-path",+ type=pathlib.Path,+ required=True,+ help="a path to the R.txt that is unpacked",+ )+ parser.add_argument(+ "--res-path",+ type=pathlib.Path,+ required=True,+ help="a path to the resources that are unpacked",+ )+ parser.add_argument(+ "--assets-path",+ type=pathlib.Path,+ required=True,+ help="a path to the assets that are unpacked",+ )+ parser.add_argument(+ "--jni-path",+ type=pathlib.Path,+ required=True,+ help="a path to the native lib directory that is unpacked",+ )+ parser.add_argument(+ "--annotation-jars-dir",+ type=pathlib.Path,+ required=True,+ help="a path to a directory where the external annotations.zip may be copied if present",+ )+ parser.add_argument(+ "--proguard-config-path",+ type=pathlib.Path,+ required=True,+ help="a path to the proguard config that is unpacked",+ )+ parser.add_argument(+ "--lint-jar-path",+ type=pathlib.Path,+ required=True,+ help="a path to the lint jar file that is unpacked",+ )+ parser.add_argument(+ "--jar-builder-tool",+ type=str,+ required=True,+ help="tool for building jars",+ )++ return parser.parse_args()+++def main():+ args = _parse_args()++ aar_path = args.aar+ manifest_path = args.manifest_path+ all_classes_path = args.all_classes_jar_path+ res_path = args.res_path+ assets_path = args.assets_path+ jni_path = args.jni_path+ r_dot_txt_path = args.r_dot_txt_path+ annotation_jars_dir = args.annotation_jars_dir+ proguard_config_path = args.proguard_config_path+ lint_jar_path = args.lint_jar_path+ jar_builder_tool = args.jar_builder_tool++ with TemporaryDirectory() as temp_dir:+ unpack_dir = pathlib.Path(temp_dir)+ with zipfile.ZipFile(aar_path, "r") as aar_zip:+ aar_zip.extractall(unpack_dir)++ if platform.system() != "Windows":+ # If the zip file was built on e.g. Windows, then it might not have+ # correct permissions (which means we can't read any of the files), so+ # make sure we actually read everything here.+ utils.execute_command(["chmod", "-R", "+rX", unpack_dir])++ unpacked_manifest = unpack_dir / "AndroidManifest.xml"+ assert unpacked_manifest.exists()+ shutil.copyfile(unpacked_manifest, manifest_path)++ unpacked_res = unpack_dir / "res"+ if unpacked_res.exists():+ shutil.copytree(unpacked_res, res_path)+ else:+ res_path.mkdir()++ unpacked_assets = unpack_dir / "assets"+ if unpacked_assets.exists():+ shutil.copytree(unpacked_assets, assets_path)+ else:+ assets_path.mkdir()++ unpacked_jni = unpack_dir / "jni"+ if unpacked_jni.exists():+ shutil.copytree(unpacked_jni, jni_path)+ else:+ jni_path.mkdir()++ unpacked_r_dot_txt = unpack_dir / "R.txt"+ if unpacked_r_dot_txt.exists():+ shutil.copyfile(unpacked_r_dot_txt, r_dot_txt_path)+ else:+ r_dot_txt_path.touch()++ annotation_jars_dir.mkdir()+ annotations_zip_path = unpack_dir / ANNOTATIONS_ZIP_FILE_NAME+ if annotations_zip_path.exists():+ shutil.copy(annotations_zip_path, annotation_jars_dir)++ unpacked_proguard_config = unpack_dir / "proguard.txt"+ if unpacked_proguard_config.exists():+ shutil.copyfile(unpacked_proguard_config, proguard_config_path)+ else:+ proguard_config_path.touch()++ unpacked_lint_jar = unpack_dir / "lint.jar"+ if unpacked_lint_jar.exists():+ shutil.copyfile(unpacked_lint_jar, lint_jar_path)+ else:+ lint_jar_path.touch()++ # Java .class files can exist at `classes.jar` or any jar file in /libs,+ # so combine them into a single `.jar` file.+ all_jars = []+ classes_jar = unpack_dir / CLASSES_JAR_FILE_NAME+ if classes_jar.exists():+ all_jars.append(classes_jar)++ libs_dir = unpack_dir / LIBS_DIR_NAME+ if libs_dir.exists():+ libs = [lib for lib in libs_dir.iterdir() if lib.suffix == ".jar"]+ all_jars += libs++ jars_list = unpack_dir / "jars_list.txt"+ with open(jars_list, "w") as f:+ f.write("\n".join([str(jar) for jar in all_jars]))++ combine_all_jars_cmd = utils.shlex_split(jar_builder_tool) + [+ "--entries-to-jar",+ jars_list,+ "--output",+ all_classes_path,+ ]++ utils.execute_command(combine_all_jars_cmd)+++if __name__ == "__main__":+ main()
@@ -0,0 +1,29 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//user:rule_spec.bzl", "RuleRegistrationSpec")++def _impl(ctx: AnalysisContext) -> list[Provider]:+ return [+ DefaultInfo(),+ LocalResourceInfo(+ setup = cmd_args([ctx.attrs.broker[RunInfo]] + ctx.attrs.args),+ resource_env_vars = {+ "ANDROID_SERIAL": "serial_number",+ },+ ),+ ]++registration_spec = RuleRegistrationSpec(+ name = "android_emulators",+ impl = _impl,+ attrs = {+ "args": attrs.list(attrs.arg(), default = []),+ "broker": attrs.exec_dep(providers = [RunInfo]),+ },+)
@@ -0,0 +1,149 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//linking:link_info.bzl",+ "ExtraLinkerOutputs",+)++def merge_extra_linker_args(arg_dicts: list[dict[str, typing.Any]]) -> dict[str, typing.Any]:+ """Merge multiple extra linker output factory dicts.++ This function combines multiple extra linker output configurations into a single+ configuration. It handles both the outputs factory (which produces artifacts and+ providers) and the flags factory (which produces linker flags).++ Args:+ arg_dicts: A list of dicts, each potentially containing:+ - "extra_linker_outputs_factory": A function (ctx) -> ExtraLinkerOutputs+ - "extra_linker_outputs_flags_factory": A function (ctx, outputs) -> list++ Returns:+ A merged dict with combined factory functions, or an empty dict if no+ non-empty dicts were provided.+ """+ non_empty = [d for d in arg_dicts if d]+ if len(non_empty) == 0:+ return {}+ if len(non_empty) == 1:+ return non_empty[0]++ def combined_outputs_factory(ctx: AnalysisContext) -> ExtraLinkerOutputs:+ artifacts = {}+ providers = {}+ for arg_dict in non_empty:+ if "extra_linker_outputs_factory" in arg_dict:+ result = arg_dict["extra_linker_outputs_factory"](ctx)+ artifacts |= result.artifacts+ providers |= result.providers+ return ExtraLinkerOutputs(artifacts = artifacts, providers = providers)++ def combined_flags_factory(ctx: AnalysisContext, outputs: dict[str, Artifact]) -> list:+ flags = []+ for arg_dict in non_empty:+ if "extra_linker_outputs_flags_factory" in arg_dict:+ flags += arg_dict["extra_linker_outputs_flags_factory"](ctx, outputs)+ return flags++ return {+ "extra_linker_outputs_factory": combined_outputs_factory,+ "extra_linker_outputs_flags_factory": combined_flags_factory,+ }++def package_validators_decorator(ctx: AnalysisContext, build_func, extension: str):+ package_validators = ctx.attrs.package_validators+ if not package_validators:+ return build_func++ def wrapped_build_func(**build_kwargs):+ final_filename = build_kwargs["output_filename"]+ build_kwargs["output_filename"] = final_filename + "_pre_validation"+ output = build_func(**build_kwargs)++ validation_outputs = _get_package_validation_outputs(+ actions = ctx.actions,+ package_validators = package_validators,+ package_output = output,+ )+ final_output = ctx.actions.declare_output(+ final_filename + extension,+ has_content_based_path = False,+ )+ ctx.actions.run(+ cmd_args(+ [+ "cp",+ output,+ final_output.as_output(),+ ],+ hidden = validation_outputs,+ ),+ category = "package_validators",+ identifier = "symlink_original_output",+ )++ return final_output++ return wrapped_build_func++def _get_package_validation_outputs(actions: AnalysisActions, package_validators: list, package_output: Artifact) -> list[Artifact]:+ if not package_validators:+ return []++ outputs = []+ for idx, validator in enumerate(package_validators):+ validator, validator_args = validator++ output = actions.declare_output(validator.label.name + "_package_validator_{}".format(idx), has_content_based_path = False)+ outputs.append(output)++ actions.run(+ cmd_args([+ validator[RunInfo],+ "--package",+ package_output,+ "--output-path",+ output.as_output(),+ validator_args,+ ]),+ category = "package_validator",+ identifier = str(idx),+ )++ return outputs++# A wrapper around AnalysisContext that makes it easier to define subtargets without needing to pass information+# for them all the way back to the outermost analysis impl.+EnhancementContext = record(+ ctx = AnalysisContext,+ actions = AnalysisActions,+ attrs = typing.Any,+ label = Label,+ # methods+ debug_output = typing.Callable,+ get_sub_targets = typing.Callable,+)++def create_enhancement_context(ctx: AnalysisContext) -> EnhancementContext:+ extra_sub_targets = {}++ def debug_output(name: str, output: Artifact, other_outputs = [], sub_targets: dict[str, typing.Any] = {}):+ """Adds a subtarget to expose debugging outputs."""+ extra_sub_targets[name] = [DefaultInfo(default_outputs = [output], other_outputs = other_outputs, sub_targets = sub_targets)]++ def get_sub_targets():+ return extra_sub_targets++ return EnhancementContext(+ ctx = ctx,+ actions = ctx.actions,+ attrs = ctx.attrs,+ label = ctx.label,+ debug_output = debug_output,+ get_sub_targets = get_sub_targets,+ )
@@ -0,0 +1,343 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//android:android_providers.bzl", "AndroidPackageableInfo", "merge_android_packageable_info")+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")+load("@prelude//java:java_providers.bzl", "get_all_java_packaging_deps")+load(+ "@prelude//linking:shared_libraries.bzl",+ "SharedLibrary", # @unused Used as type+ "SharedLibraryInfo",+ "merge_shared_libraries",+ "traverse_shared_library_info",+)+load("@prelude//utils:argfile.bzl", "argfile")+load("@prelude//utils:expect.bzl", "expect")+load("@prelude//utils:utils.bzl", "flatten")++# "Voltron" gives us the ability to split our Android APKs into different "modules". These+# modules can then be downloaded on demand rather than shipped with the "main" APK.+#+# The module corresponding to the "main" APK is called the "root" module.+#+# Voltron support comes in two main parts:+# (1) Constructing the Voltron module graph (assigning targets to each module). This is done+# by constructing a "target graph" and then delegating to buck1 to produce the module graph.+# (2) Using the Voltron module graph while building our APK.+#+# For (1), in order to calculate which targets belong to each module, we reconstruct a "target+# graph" from "deps" information that is propagated up through AndroidPackageableInfo.+# In buck1 we use the underlying "TargetGraph" object that is based on the raw target+# definitions. This results in some slightly different behavior for `provided_deps` - in+# buck2, we (correctly) ignore `provided_deps`, since they do not influence the packaging of+# the APK, whereas in `buck1`, we treat `provided_deps` the same as `deps`.+# In practice, this rarely affects the module assignments, but can mean that `buck2` will+# put a target inside a module whereas `buck1` will put it into the main APK (since `buck1`+# can find a path from an "always in main APK seed" to the target via some `provided_dep`,+# whereas `buck2` does not).+#+# For (2), we package up secondary DEX files and native libs into `assets/module_name` (see+# dex_rules.bzl and android_binary_native_rules.bzl for more information on how we do that).+# It is worth noting that we still put all of the non-root modules into the final APK. If+# the module should be downloaded on demand, then it is removed from the final APK in a+# subsequent post-processing step.+#+# There is also an `android_app_modularity` rule that just prints out details of the Voltron+# module graph and is used for any subsequent verification.+def android_app_modularity_impl(ctx: AnalysisContext) -> list[Provider]:+ if ctx.attrs._build_only_native_code:+ return [+ # Add an unused default output in case this target is used as an attr.source() anywhere.+ DefaultInfo(default_output = ctx.actions.write("{}/unused.txt".format(ctx.label.name), [], has_content_based_path = False)),+ ]++ all_deps = ctx.attrs.deps + flatten(ctx.attrs.application_module_configs.values())+ android_packageable_info = merge_android_packageable_info(ctx.label, ctx.actions, all_deps)++ shared_library_info = merge_shared_libraries(+ ctx.actions,+ deps = filter(None, [x.get(SharedLibraryInfo) for x in all_deps]),+ )+ traversed_shared_library_info = traverse_shared_library_info(shared_library_info, transformation_provider = None)++ cmd, output = _get_base_cmd_and_output(+ ctx.actions,+ ctx.label,+ [android_packageable_info],+ traversed_shared_library_info,+ ctx.attrs._android_toolchain[AndroidToolchainInfo],+ ctx.attrs.application_module_configs,+ ctx.attrs.application_module_dependencies,+ ctx.attrs.application_module_blocklist,+ )++ if ctx.attrs.should_include_classes:+ no_dx_target_labels = [no_dx_target.label.raw_target() for no_dx_target in ctx.attrs.no_dx]+ java_packaging_deps = [+ packaging_dep+ for packaging_dep in get_all_java_packaging_deps(ctx, all_deps)+ if packaging_dep.dex and packaging_dep.dex.dex.owner.raw_target() not in no_dx_target_labels+ ]+ targets_to_jars_args = [cmd_args([str(packaging_dep.label.raw_target()), packaging_dep.jar], delimiter = " ") for packaging_dep in java_packaging_deps]+ targets_to_jars = argfile(actions = ctx.actions, name = "targets_to_jars.txt", args = targets_to_jars_args)+ cmd.add([+ "--targets-to-jars",+ targets_to_jars,+ ])++ if ctx.attrs.should_include_libraries:+ targets_to_so_names_args = [+ cmd_args([str(shared_lib.label.raw_target()), shared_lib.soname.ensure_str()], delimiter = " ") for shared_lib in traversed_shared_library_info+ ]+ targets_to_so_names = argfile(actions = ctx.actions, name = "targets_to_so_names.txt", args = targets_to_so_names_args)+ cmd.add([+ "--targets-to-so-names",+ targets_to_so_names,+ ])++ traversed_prebuilt_native_library_dirs = (+ android_packageable_info.prebuilt_native_library_dirs.traverse() if android_packageable_info.prebuilt_native_library_dirs else []+ )+ targets_to_non_assets_prebuilt_native_library_dirs_args = [+ cmd_args(prebuilt_native_library_dir.raw_target, prebuilt_native_library_dir.dir, delimiter = " ")+ for prebuilt_native_library_dir in traversed_prebuilt_native_library_dirs+ if not prebuilt_native_library_dir.is_asset and not prebuilt_native_library_dir.for_primary_apk+ ]+ targets_to_non_assets_prebuilt_native_library_dirs = argfile(+ actions = ctx.actions,+ name = "targets_to_non_assets_prebuilt_native_library_dirs.txt",+ args = targets_to_non_assets_prebuilt_native_library_dirs_args,+ )+ cmd.add([+ "--targets-to-non-asset-prebuilt-native-library-dirs",+ targets_to_non_assets_prebuilt_native_library_dirs,+ ])++ ctx.actions.run(cmd, category = "apk_module_graph")++ return [DefaultInfo(default_output = output)]++def get_target_to_module_mapping(ctx: AnalysisContext, deps_by_platform: dict[str, list[Dependency]]) -> Artifact | None:+ if not ctx.attrs.application_module_configs:+ return None++ android_packageable_infos = []+ shared_libraries = []+ for deps in deps_by_platform.values() + [flatten(ctx.attrs.application_module_configs.values())]:+ android_packageable_infos.append(merge_android_packageable_info(ctx.label, ctx.actions, deps))+ shared_library_info = merge_shared_libraries(+ ctx.actions,+ deps = filter(None, [x.get(SharedLibraryInfo) for x in deps]),+ )+ shared_libraries.extend(traverse_shared_library_info(shared_library_info, transformation_provider = None))++ cmd, output = _get_base_cmd_and_output(+ ctx.actions,+ ctx.label,+ android_packageable_infos,+ shared_libraries,+ ctx.attrs._android_toolchain[AndroidToolchainInfo],+ ctx.attrs.application_module_configs,+ ctx.attrs.application_module_dependencies,+ ctx.attrs.application_module_blocklist,+ )++ cmd.add("--output-module-info-and-target-to-module-only")++ ctx.actions.run(cmd, category = "apk_module_graph")++ return output++def _get_base_cmd_and_output(+ actions: AnalysisActions,+ label: Label,+ android_packageable_infos: list[AndroidPackageableInfo],+ shared_libraries: list[SharedLibrary],+ android_toolchain: AndroidToolchainInfo,+ application_module_configs: dict[str, list[Dependency]],+ application_module_dependencies: [dict[str, list[str]], None],+ application_module_blocklist: [list[Dependency], None],+) -> (cmd_args, Artifact):+ deps_map = {}+ primary_apk_deps = set()+ for android_packageable_info in android_packageable_infos:+ if android_packageable_info.deps:+ for deps_info in android_packageable_info.deps.traverse():+ deps = deps_map.setdefault(deps_info.name, [])+ deps_map[deps_info.name] = dedupe(deps + deps_info.deps)+ if deps_info.for_primary_apk:+ primary_apk_deps.add(deps_info.name)++ target_graph_file = actions.write_json("target_graph.json", deps_map, has_content_based_path = False)+ application_module_configs_map = {+ module_name: [seed.get(AndroidPackageableInfo).target_label for seed in seeds if seed.get(AndroidPackageableInfo)]+ for module_name, seeds in application_module_configs.items()+ }+ application_module_configs_file = actions.write_json("application_module_configs.json", application_module_configs_map, has_content_based_path = False)+ application_module_dependencies_file = actions.write_json(+ "application_module_dependencies.json", application_module_dependencies or {}, has_content_based_path = False+ )+ output = actions.declare_output("apk_module_metadata.txt", has_content_based_path = False)++ cmd = cmd_args([+ android_toolchain.apk_module_graph[RunInfo],+ "--root-target",+ str(label.raw_target()),+ "--target-graph",+ target_graph_file,+ "--seed-config-map",+ application_module_configs_file,+ "--app-module-dependencies-map",+ application_module_dependencies_file,+ "--output",+ output.as_output(),+ ])++ # Anything that is used by a wrap script needs to go into the primary APK, as do all+ # of their deps.+ used_by_wrap_script_libs = [str(shared_lib.label.raw_target()) for shared_lib in shared_libraries if shared_lib.for_primary_apk]+ prebuilt_native_library_dirs = flatten([+ list(android_packageable_info.prebuilt_native_library_dirs.traverse()) if android_packageable_info.prebuilt_native_library_dirs else []+ for android_packageable_info in android_packageable_infos+ ])+ prebuilt_native_library_targets_for_primary_apk = dedupe(+ [str(native_lib_dir.raw_target) for native_lib_dir in prebuilt_native_library_dirs if native_lib_dir.for_primary_apk]+ )+ if application_module_blocklist or used_by_wrap_script_libs or prebuilt_native_library_targets_for_primary_apk or len(primary_apk_deps) > 0:+ all_blocklisted_deps = used_by_wrap_script_libs + prebuilt_native_library_targets_for_primary_apk + list(primary_apk_deps)+ if application_module_blocklist:+ all_blocklisted_deps.extend([str(blocklisted_dep.label.raw_target()) for blocklisted_dep in application_module_blocklist])++ application_module_blocklist_file = actions.write(+ "application_module_blocklist.txt",+ all_blocklisted_deps,+ has_content_based_path = False,+ )+ cmd.add([+ "--always-in-main-apk-seeds",+ application_module_blocklist_file,+ ])++ return cmd, output++ROOT_MODULE = "dex"++def is_root_module(module: str) -> bool:+ return module == ROOT_MODULE++def all_targets_in_root_module(_module: str) -> str:+ return ROOT_MODULE++APKModuleGraphInfo = record(+ module_list = list[str],+ target_to_module_mapping_function = typing.Callable,+ module_to_canary_class_name_function = typing.Callable,+ module_to_module_deps_function = typing.Callable,+ transitive_module_deps_function = typing.Callable,+ calculated_deps_function = typing.Callable,+ get_deps_debug_data = typing.Callable,+)++def get_root_module_only_apk_module_graph_info() -> APKModuleGraphInfo:+ def root_module_canary_class_name(module: str):+ expect(is_root_module(module))+ return "secondary"++ def root_module_deps(module: str):+ expect(is_root_module(module))+ return []++ return APKModuleGraphInfo(+ module_list = [ROOT_MODULE],+ target_to_module_mapping_function = all_targets_in_root_module,+ module_to_canary_class_name_function = root_module_canary_class_name,+ module_to_module_deps_function = root_module_deps,+ transitive_module_deps_function = root_module_deps,+ calculated_deps_function = root_module_deps,+ get_deps_debug_data = root_module_deps,+ )++def get_apk_module_graph_info(ctx: AnalysisContext, apk_module_graph_file: Artifact, artifacts) -> APKModuleGraphInfo:+ apk_module_graph_lines = artifacts[apk_module_graph_file].read_string().split("\n")+ module_count = int(apk_module_graph_lines[0])+ module_infos = apk_module_graph_lines[1 : module_count + 1]+ target_to_module_lines = apk_module_graph_lines[module_count + 1 : -1]+ expect(apk_module_graph_lines[-1] == "", "Expect last line to be an empty string!")++ module_to_canary_class_name_map = {}+ module_to_module_deps_map = {}+ transitive_module_deps_map = {}+ calculated_deps_map = {}+ shared_module_rdeps = {}+ for line in module_infos:+ line_data = line.split(" ")+ module_name = line_data[0]+ canary_class_name = line_data[1]+ module_deps = [module_dep for module_dep in line_data[2:] if module_dep]+ module_to_canary_class_name_map[module_name] = canary_class_name+ module_to_module_deps_map[module_name] = module_deps+ shared_modules = [module_dep for module_dep in module_deps if module_dep.startswith("s_")]+ for shared_module in shared_modules:+ rdeps = shared_module_rdeps.get(shared_module, set())+ rdeps.add(module_name)+ shared_module_rdeps[shared_module] = rdeps++ target_to_module_mapping = {str(ctx.label.raw_target()): ROOT_MODULE}+ for line in target_to_module_lines:+ target, module = line.split(" ")+ target_to_module_mapping[target] = module++ for module, deps in module_to_module_deps_map.items():+ visited_modules = set()+ queue = [d for d in deps]+ for _ in range(1, 1000): # represents a while loop since while loops dont exist in starlark+ if len(queue) == 0:+ transitive_module_deps_map[module] = visited_modules+ continue+ node = queue.pop()+ visited_modules.add(node)+ for d in module_to_module_deps_map[node]:+ if d not in visited_modules:+ queue.append(d)+ for shared_module, rdeps in shared_module_rdeps.items():+ rdeps_list = list(rdeps)+ head = rdeps_list[0]+ intersection = transitive_module_deps_map[head]+ for rdep in rdeps_list[1:]:+ intersection = intersection & transitive_module_deps_map[rdep]+ calculated_deps_map[shared_module] = intersection | rdeps++ def target_to_module_mapping_function(raw_target: str) -> str:+ mapped_module = target_to_module_mapping.get(raw_target)+ expect(mapped_module != None, "No module found for target {}!".format(raw_target))+ return mapped_module++ def module_to_canary_class_name_function(voltron_module: str) -> str:+ return module_to_canary_class_name_map.get(voltron_module)++ def module_to_module_deps_function(voltron_module: str) -> list:+ return module_to_module_deps_map.get(voltron_module)++ def transitive_module_deps_function(voltron_module: str) -> set[str]:+ return transitive_module_deps_map.get(voltron_module)++ def calculated_deps_function(voltron_module: str) -> set[str]:+ return calculated_deps_map.get(voltron_module) if voltron_module in calculated_deps_map else set()++ def get_deps_debug_data() -> str:+ return "tdeps - {} \n calculated deps - {}".format(transitive_module_deps_map, calculated_deps_map)++ return APKModuleGraphInfo(+ module_list = module_to_canary_class_name_map.keys(),+ target_to_module_mapping_function = target_to_module_mapping_function,+ module_to_canary_class_name_function = module_to_canary_class_name_function,+ module_to_module_deps_function = module_to_module_deps_function,+ transitive_module_deps_function = transitive_module_deps_function,+ calculated_deps_function = calculated_deps_function,+ get_deps_debug_data = get_deps_debug_data,+ )
@@ -0,0 +1,17 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++AospJarInfo = provider(+ fields = {+ # Optional ART profile source (a text HSPL class/method listing) for this jar.+ # When the jar is placed on an APEX systemserverclasspath, the APEX rule compiles+ # this against the jar with profman to produce a profile-guided .prof for+ # dexpreopt/odrefresh. None if the jar has no profile.+ "profile": provider_field(typing.Any, default = None),+ },+)
@@ -0,0 +1,16 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++def apple_app_intents_impl(_ctx: AnalysisContext) -> list[Provider]:+ """+ Implementation for apple_appintents rule.+ This is a bare-bones implementation that will be expanded as needed.+ """++ # TODO: Add actual implementation logic+ return []
@@ -0,0 +1,153 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")+load(+ "@prelude//ide_integrations/xcode:data.bzl",+ "XCODE_DATA_SUB_TARGET",+ "XcodeDataInfoKeys",+ "generate_xcode_data",+)+load("@prelude//utils:utils.bzl", "flatten")+load(+ ":apple_asset_catalog_compilation_options.bzl", "AppleAssetCatalogsCompilationOptions", "get_apple_asset_catalogs_compilation_options"+) # @unused Used as a type+load(":apple_asset_catalog_types.bzl", "AppleAssetCatalogResult", "AppleAssetCatalogSpec", "StringWithSourceTarget")+load(":apple_bundle_utility.bzl", "get_bundle_min_target_version", "get_bundle_resource_processing_options")+load(":apple_sdk.bzl", "get_apple_sdk_name")+load(":apple_sdk_metadata.bzl", "get_apple_sdk_metadata_for_sdk_name")+load(":resource_groups.bzl", "create_resource_graph")++def apple_asset_catalog_impl(ctx: AnalysisContext) -> list[Provider]:+ spec = AppleAssetCatalogSpec(+ app_icon = StringWithSourceTarget(source = ctx.label, value = ctx.attrs.app_icon) if ctx.attrs.app_icon != None else None,+ dirs = ctx.attrs.dirs,+ launch_image = StringWithSourceTarget(source = ctx.label, value = ctx.attrs.launch_image) if ctx.attrs.launch_image != None else None,+ )+ graph = create_resource_graph(+ ctx = ctx,+ labels = ctx.attrs.labels,+ deps = [],+ exported_deps = [],+ asset_catalog_spec = spec,+ )++ xcode_data_default_info, xcode_data_info = generate_xcode_data(ctx, "apple_asset_catalog", None, _xcode_populate_attributes)++ return [+ DefaultInfo(+ sub_targets = {+ XCODE_DATA_SUB_TARGET: xcode_data_default_info,+ },+ ),+ graph,+ xcode_data_info,+ ]++def compile_apple_asset_catalog(ctx: AnalysisContext, specs: list[AppleAssetCatalogSpec]) -> [AppleAssetCatalogResult, None]:+ single_spec = _merge_asset_catalog_specs(ctx, specs)+ if len(single_spec.dirs) == 0:+ return None+ plist = ctx.actions.declare_output("AssetCatalog.plist", has_content_based_path = False)+ catalog = ctx.actions.declare_output("AssetCatalogCompiled", dir = True, has_content_based_path = False)+ processing_options = get_bundle_resource_processing_options(ctx)+ compilation_options = get_apple_asset_catalogs_compilation_options(ctx)+ command = _get_actool_command(ctx, single_spec, catalog.as_output(), plist.as_output(), compilation_options)+ ctx.actions.run(+ command,+ prefer_local = processing_options.prefer_local,+ prefer_remote = processing_options.prefer_remote,+ allow_cache_upload = processing_options.allow_cache_upload,+ category = "apple_asset_catalog",+ )+ return AppleAssetCatalogResult(compiled_catalog = catalog, catalog_plist = plist)++def _merge_asset_catalog_specs(ctx: AnalysisContext, xs: list[AppleAssetCatalogSpec]) -> AppleAssetCatalogSpec:+ app_icon = _get_at_most_one_attribute(ctx, xs, "app_icon")+ launch_image = _get_at_most_one_attribute(ctx, xs, "launch_image")+ dirs = dedupe(flatten([x.dirs for x in xs]))+ return AppleAssetCatalogSpec(app_icon = app_icon, dirs = dirs, launch_image = launch_image)++def _get_at_most_one_attribute(ctx: AnalysisContext, xs: list[typing.Any], attr_name: str) -> [StringWithSourceTarget, None]:+ all_values = dedupe(filter(None, [getattr(x, attr_name) for x in xs]))+ if len(all_values) > 1:+ fail(+ "At most one asset catalog in the dependencies of `{}` can have an `{}` attribute. At least 2 catalogs are providing it: `{}` and `{}`.".format(+ _get_target(ctx), attr_name, all_values[0].source, all_values[1].source+ )+ )+ elif len(all_values) == 1:+ return all_values[0]+ else:+ return None++def _get_target(ctx: AnalysisContext) -> str:+ return ctx.label.package + ":" + ctx.label.name++def _get_actool_command(+ ctx: AnalysisContext,+ info: AppleAssetCatalogSpec,+ catalog_output: OutputArtifact,+ plist_output: OutputArtifact,+ compilation_options: AppleAssetCatalogsCompilationOptions,+) -> cmd_args:+ external_name = get_apple_sdk_name(ctx)+ sdk_metadata = get_apple_sdk_metadata_for_sdk_name(external_name)+ target_device = sdk_metadata.target_device_flags++ actool_platform = sdk_metadata.actool_platform_override+ if not actool_platform:+ actool_platform = external_name++ actool = ctx.attrs._apple_toolchain[AppleToolchainInfo].actool+ actool_command = cmd_args(+ [+ actool,+ "--platform",+ actool_platform,+ "--minimum-deployment-target",+ get_bundle_min_target_version(ctx, ctx.attrs.binary),+ "--compile",+ '"$TMPDIR"',+ "--output-partial-info-plist",+ plist_output,+ ]+ + target_device+ + (["--app-icon", info.app_icon.value] if info.app_icon else [])+ + (["--launch-image", info.launch_image.value] if info.launch_image else [])+ + (["--notices"] if compilation_options.enable_notices else [])+ + (["--warnings"] if compilation_options.enable_warnings else [])+ + (["--errors"] if compilation_options.enable_errors else [])+ + (["--compress-pngs"] if compilation_options.compress_pngs else [])+ + ["--optimization", compilation_options.optimization]+ + ["--output-format", compilation_options.output_format]+ + compilation_options.extra_flags+ + info.dirs+ )++ # `actool` expects the output directory to be present.+ # Use the wrapper script to create the directory first and then actually call `actool`.+ wrapper_script, _ = ctx.actions.write(+ "actool_wrapper.sh",+ [+ cmd_args("set -euo pipefail"),+ cmd_args('ACTOOL_INPUT_ROOT="$PWD"'),+ cmd_args('export TMPDIR="$(mktemp -d)"'),+ cmd_args('cd "$TMPDIR"'),+ cmd_args(actool_command, absolute_prefix = "$ACTOOL_INPUT_ROOT/", delimiter = " "),+ cmd_args(catalog_output, format = 'mkdir -p {} && cp -r "$TMPDIR"/ {}', absolute_prefix = "$ACTOOL_INPUT_ROOT/"),+ ],+ allow_args = True,+ has_content_based_path = False,+ )+ command = cmd_args(["/bin/sh", wrapper_script], hidden = [actool_command, catalog_output])+ return command++def _xcode_populate_attributes(ctx) -> dict[str, typing.Any]:+ data = {XcodeDataInfoKeys.EXTRA_XCODE_FILES: ctx.attrs.dirs}+ return data
@@ -0,0 +1,30 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++AppleAssetCatalogsCompilationOptions = record(+ enable_notices = field(bool),+ enable_warnings = field(bool),+ enable_errors = field(bool),+ compress_pngs = field(bool),+ optimization = field(str),+ output_format = field(str),+ extra_flags = field(list[str]),+)++def get_apple_asset_catalogs_compilation_options(ctx: AnalysisContext) -> AppleAssetCatalogsCompilationOptions:+ options = ctx.attrs.asset_catalogs_compilation_options++ return AppleAssetCatalogsCompilationOptions(+ enable_notices = options.get("notices", True),+ enable_warnings = options.get("warnings", True),+ enable_errors = options.get("errors", True),+ compress_pngs = options.get("compress_pngs", True),+ optimization = options.get("optimization", "space"),+ output_format = options.get("output_format", "human-readable-text"),+ extra_flags = options.get("extra_flags", []),+ )
@@ -0,0 +1,31 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++StringWithSourceTarget = record(+ # Target providing the string value+ source = field(Label),+ value = field(str),+)++AppleAssetCatalogSpec = record(+ # At most one per given `apple_bundle` (including all transitive catalog dependencies),+ # optional reference in a form of a name (extension omitted) of an .appiconset which+ # contains an image set representing an application icon.+ # This set should be contained in one of catalogs referenced by `dirs` attribute.+ app_icon = field([StringWithSourceTarget, None]),+ dirs = field(list[Artifact]),+ # Same as `app_icon` but with an application launch image semantics.+ launch_image = field([StringWithSourceTarget, None]),+)++AppleAssetCatalogResult = record(+ # Directory which contains compiled assets ready to be copied into application bundle+ compiled_catalog = field(Artifact),+ # .plist file to be merged into main application Info.plist file, containing information about compiled assets+ catalog_plist = field(Artifact),+)
@@ -0,0 +1,423 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")+load("@prelude//apple:apple_stripping.bzl", "apple_strip_args")+load("@prelude//apple:apple_utility.bzl", "get_module_name")+load(+ "@prelude//apple:modularization_dependency_graph.bzl",+ "create_modularization_dep_graph_subtargets_and_provider",+)+load("@prelude//apple:xcassets_asset_symbols.bzl", "meta_xcassets_asset_symbol_usage_providers_and_subtargets")+# @oss-disable[end= ]: load(+ # @oss-disable[end= ]: "@prelude//apple/meta_only:linker_outputs.bzl",+ # @oss-disable[end= ]: "extra_distributed_thin_lto_opt_outputs_merger",+ # @oss-disable[end= ]: "get_extra_linker_output_flags",+ # @oss-disable[end= ]: "get_extra_linker_outputs",+# @oss-disable[end= ]: )+load(+ "@prelude//apple/swift:swift_compilation.bzl",+ "compile_swift",+ "get_swift_anonymous_targets",+ "get_swift_debug_infos",+ "get_swift_dependency_info",+ "get_swiftmodule_linkable",+)+load("@prelude//apple/swift:swift_helpers.bzl", "uses_explicit_modules")+load(+ "@prelude//apple/swift:swift_incremental_support.bzl",+ "get_uses_content_based_paths",+)+load("@prelude//apple/swift:swift_types.bzl", "SWIFT_EXTENSION")+load(+ "@prelude//cxx:argsfiles.bzl",+ "CompileArgsfiles",+)+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")+load("@prelude//cxx:cxx_executable.bzl", "cxx_executable")+load("@prelude//cxx:cxx_library_utility.bzl", "cxx_attr_deps", "cxx_attr_exported_deps", "cxx_attr_link_style")+load(+ "@prelude//cxx:cxx_sources.bzl",+ "CxxSrcWithFlags", # @unused Used as a type+ "get_srcs_with_flags",+)+load(+ "@prelude//cxx:cxx_transitive_diagnostics.bzl",+ "cxx_transitive_diagnostics_combine",+)+load(+ "@prelude//cxx:cxx_types.bzl",+ "CxxRuleAdditionalParams",+ "CxxRuleConstructorParams",+ "CxxRuleSubTargetParams",+ "xcode_data_enabled",+)+load("@prelude//cxx:cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload")+load(+ "@prelude//cxx:headers.bzl",+ "HeaderMode",+ "cxx_attr_headers",+ "cxx_attr_headers_list",+ "cxx_get_regular_cxx_headers_layout",+ "prepare_headers",+)+load("@prelude//cxx:index_store.bzl", "create_index_store_subtargets_and_provider")+load(+ "@prelude//cxx:link_groups.bzl",+ "get_link_group_info",+)+load("@prelude//cxx:link_types.bzl", "ExtraLinkerOutputCategory")+load(+ "@prelude//linking:link_info.bzl",+ "CxxSanitizerRuntimeInfo",+ "ExtraLinkerOutputs",+ "LinkCommandDebugOutputInfo",+ "UnstrippedLinkOutputInfo",+ "to_link_strategy",+)+load(+ "@prelude//linking:linkable_graph.bzl",+ "LinkableGraph",+)+load("@prelude//target_stats:target_stats.bzl", "CycleMode", "target_stats_providers_and_subtargets")+load("@prelude//target_stats:target_stats_config.bzl", "TARGET_STATS_ENABLED")+load("@prelude//utils:arglike.bzl", "ArgLike")+load("@prelude//utils:utils.bzl", "filter_and_map_idx", "map_val")+load(":apple_bundle_types.bzl", "AppleBundleLinkerMapInfo", "AppleMinDeploymentVersionInfo")+load(":apple_bundle_utility.bzl", "get_bundle_infos_from_graph", "merge_bundle_linker_maps_info")+load(":apple_code_signing_types.bzl", "AppleEntitlementsInfo")+load(":apple_dsym.bzl", "DSYM_SUBTARGET", "get_apple_dsym")+load(":apple_entitlements.bzl", "entitlements_link_flags")+load(":apple_error_handler.bzl", "apple_build_error_handler", "cxx_error_deserializer", "cxx_error_handler")+load(":apple_frameworks.bzl", "get_framework_search_path_flags")+load(":apple_rpaths.bzl", "get_rpath_flags_for_apple_binary")+load(":apple_target_sdk_version.bzl", "get_min_deployment_version_for_node")+load(":apple_utility.bzl", "get_apple_cxx_headers_layout", "get_apple_stripped_attr_value_with_default_fallback", "target_stats_header_name")+load(":debug.bzl", "AppleDebuggableInfo")+load(":resource_groups.bzl", "create_resource_graph")+load(":xcode.bzl", "apple_populate_xcode_attributes")++def apple_binary_impl(ctx: AnalysisContext) -> [list[Provider], Promise]:+ def get_apple_binary_providers(deps_providers) -> list[Provider]:+ # FIXME: Ideally we'd like to remove the support of "bridging header",+ # cause it affects build time and in general considered a bad practise.+ # But we need it for now to achieve compatibility with BUCK1.+ objc_bridging_header_flags = _get_bridging_header_flags(ctx)++ cxx_srcs, swift_srcs = _filter_swift_srcs(ctx)+ contains_swift_sources = len(swift_srcs) > 0++ module_name = get_module_name(ctx)++ framework_search_path_flags = get_framework_search_path_flags(ctx)+ swift_compile_result = compile_swift(+ ctx,+ swift_srcs,+ False, # parse_as_library+ deps_providers,+ module_name,+ [],+ None,+ framework_search_path_flags,+ objc_bridging_header_flags,+ )+ swift_compile = swift_compile_result.swift_compilation+ swift_object_files = swift_compile.object_files if swift_compile else []+ swift_preprocessor = [swift_compile.pre] if swift_compile else []+ extra_link_flags = get_rpath_flags_for_apple_binary(ctx) + entitlements_link_flags(ctx)++ # Extensions have custom entry points and API restrictions+ extension_compiler_flags = []+ if ctx.attrs.application_extension:+ extra_link_flags += [+ "-fapplication-extension",+ "-e",+ "_NSExtensionMain",+ ]+ extension_compiler_flags = ["-fapplication-extension"]++ swift_dependency_info = swift_compile.dependency_info if swift_compile else get_swift_dependency_info(ctx, None, deps_providers, False)+ swift_debug_info = get_swift_debug_infos(+ ctx,+ swift_dependency_info,+ swift_compile,+ )++ link_strategy = to_link_strategy(cxx_attr_link_style(ctx))+ link_group_info = get_link_group_info(+ ctx,+ filter_and_map_idx(LinkableGraph, cxx_attr_deps(ctx)),+ link_strategy,+ )+ binary_subtargets = {+ "swift-compilation-database": [+ DefaultInfo(+ default_output = swift_compile.compilation_database.db if swift_compile else None,+ other_outputs = [swift_compile.compilation_database.other_outputs] if swift_compile else [],+ ),+ ],+ }++ validation_deps_outputs = get_validation_deps_outputs(ctx)+ stripped = get_apple_stripped_attr_value_with_default_fallback(ctx)+ constructor_params = CxxRuleConstructorParams(+ rule_type = "apple_binary",+ generate_sub_targets = CxxRuleSubTargetParams(xcode_data = xcode_data_enabled()),+ headers_layout = get_apple_cxx_headers_layout(ctx),+ extra_link_flags = extra_link_flags,+ extra_hidden = validation_deps_outputs,+ srcs = cxx_srcs,+ additional = CxxRuleAdditionalParams(+ srcs = swift_srcs,+ argsfiles = swift_compile.argsfiles if swift_compile else CompileArgsfiles(),+ # We need to add any swift modules that we include in the link, as+ # these will end up as `N_AST` entries that `dsymutil` will need to+ # follow.+ static_external_debug_info = swift_debug_info.static,+ shared_external_debug_info = swift_debug_info.shared,+ subtargets = binary_subtargets,+ ),+ extra_link_input = swift_object_files,+ extra_link_input_has_external_debug_info = True,+ extra_preprocessors = swift_preprocessor,+ strip_executable = stripped,+ strip_args_factory = apple_strip_args,+ cxx_populate_xcode_attributes_func = lambda local_ctx, **kwargs: apple_populate_xcode_attributes(+ local_ctx, contains_swift_sources = contains_swift_sources, **kwargs+ ),+ link_group_info = link_group_info,+ prefer_stripped_objects = ctx.attrs.prefer_stripped_objects,+ # Some apple rules rely on `static` libs *not* following dependents.+ link_groups_force_static_follows_dependents = False,+ swiftmodule_linkable = get_swiftmodule_linkable(swift_compile),+ compiler_flags = ctx.attrs.compiler_flags + extension_compiler_flags,+ lang_compiler_flags = ctx.attrs.lang_compiler_flags,+ preprocessor_flags = ctx.attrs.preprocessor_flags,+ lang_preprocessor_flags = ctx.attrs.lang_preprocessor_flags,+ error_handler = cxx_error_handler if cxx_error_deserializer(ctx) else apple_build_error_handler,+ index_stores = [swift_compile.index_store] if swift_compile else None,+ executable_name = ctx.attrs.executable_name,+ extra_linker_outputs_factory = _get_extra_linker_outputs,+ extra_linker_outputs_flags_factory = _get_extra_linker_outputs_flags,+ extra_distributed_thin_lto_opt_outputs_merger = _extra_distributed_thin_lto_opt_outputs_merger,+ allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs, get_cxx_toolchain_info(ctx).cxx_compiler_info.allow_cache_upload),+ precompiled_header = ctx.attrs.precompiled_header,+ prefix_header = ctx.attrs.prefix_header,+ use_content_based_paths = get_uses_content_based_paths(ctx),+ )+ cxx_output = cxx_executable(ctx, constructor_params)++ if stripped:+ unstripped_binary = cxx_output.unstripped_binary+ else:+ unstripped_binary = cxx_output.binary+ cxx_output.sub_targets["unstripped"] = [DefaultInfo(default_output = unstripped_binary)]++ dsym_artifact = get_apple_dsym(+ ctx = ctx,+ executable = unstripped_binary,+ debug_info = cxx_output.external_debug_info_artifacts,+ action_identifier = unstripped_binary.short_path,+ )+ cxx_output.sub_targets[DSYM_SUBTARGET] = [DefaultInfo(default_output = dsym_artifact)]++ min_version = get_min_deployment_version_for_node(ctx)+ min_version_providers = [AppleMinDeploymentVersionInfo(version = min_version)]++ non_exported_deps = cxx_attr_deps(ctx)+ exported_deps = cxx_attr_exported_deps(ctx)+ resource_graph = create_resource_graph(+ ctx = ctx,+ labels = ctx.attrs.labels,+ deps = non_exported_deps,+ exported_deps = exported_deps,+ )+ bundle_infos = get_bundle_infos_from_graph(resource_graph)+ if cxx_output.linker_map_data:+ bundle_infos.append(AppleBundleLinkerMapInfo(linker_maps = [cxx_output.linker_map_data.map]))++ link_command_providers = []+ if cxx_output.link_command_debug_output:+ link_command_providers.append(LinkCommandDebugOutputInfo(debug_outputs = [cxx_output.link_command_debug_output]))++ sanitizer_runtime_providers = []+ if cxx_output.sanitizer_runtime_files:+ sanitizer_runtime_providers.append(CxxSanitizerRuntimeInfo(runtime_files = cxx_output.sanitizer_runtime_files))++ index_stores = []+ swift_index_stores = []++ if swift_compile:+ swift_index_stores.append(swift_compile.index_store)+ index_stores.append(swift_compile.index_store)++ index_stores.extend(cxx_output.index_stores)++ all_deps = non_exported_deps + exported_deps++ meta_xcassets_usage_providers, meta_xcassets_usage_subtargets = meta_xcassets_asset_symbol_usage_providers_and_subtargets(ctx, cxx_srcs, swift_srcs)+ cxx_output.sub_targets.update(meta_xcassets_usage_subtargets)++ index_store_subtargets, index_store_info = create_index_store_subtargets_and_provider(ctx, index_stores, swift_index_stores, all_deps)+ cxx_output.sub_targets.update(index_store_subtargets)++ # Modularization dependency graphs. Unlike apple_library (which routes+ # through cxx_library), binaries go through cxx_executable, which does+ # not create this provider -- so build it here. Without it the tset is+ # severed at the binary and apple_bundle collects nothing from the+ # libraries beneath it.+ mod_dep_graph_subtargets, mod_dep_graph_info = create_modularization_dep_graph_subtargets_and_provider(+ ctx,+ swift_compile.modularization_dependency_graph if swift_compile else None,+ all_deps,+ )+ cxx_output.sub_targets.update(mod_dep_graph_subtargets)++ target_stats_providers = []+ if TARGET_STATS_ENABLED:+ target_stats_tools = get_cxx_toolchain_info(ctx).target_stats_tools+ if target_stats_tools != None:+ # Headers as well as srcs: file_cycles derives its ObjC import+ # edges from the header entries, so without them a binary can+ # never report a cycle.+ target_stats_srcs = {src.file.short_path: src.file for src in cxx_srcs + swift_srcs}+ target_stats_srcs.update({+ target_stats_header_name(header): header.artifact+ for header in cxx_attr_headers_list(ctx, ctx.attrs.headers, get_apple_cxx_headers_layout(ctx))+ })+ target_stats_providers, target_stats_subtargets = target_stats_providers_and_subtargets(+ ctx,+ tools = target_stats_tools,+ srcs = target_stats_srcs,+ deps = all_deps,+ cycle_mode = CycleMode("file"),+ module_name = module_name,+ swift_dot = swift_compile.modularization_dependency_graph if swift_compile else None,+ )+ cxx_output.sub_targets.update(target_stats_subtargets)++ validation_providers = [ValidationInfo(validations = cxx_output.validation_specs)] if cxx_output.validation_specs else []++ all_diagnostics = []+ if swift_compile:+ all_diagnostics.append(swift_compile.typecheck_file)+ if cxx_output.diagnostics:+ all_diagnostics.append(cxx_output.diagnostics)++ diagnostics_providers = [+ cxx_transitive_diagnostics_combine(+ ctx = ctx,+ diagnostics = all_diagnostics,+ # TODO: We might be able to use all_deps, but, this changes the iteration order of deps.+ deps = exported_deps + non_exported_deps,+ ),+ ]++ providers = (+ filter(+ None,+ [+ DefaultInfo(default_output = cxx_output.binary, sub_targets = cxx_output.sub_targets),+ RunInfo(args = cmd_args(cxx_output.binary, hidden = cxx_output.runtime_files)),+ AppleEntitlementsInfo(entitlements_file = ctx.attrs.entitlements_file),+ AppleDebuggableInfo(dsyms = [dsym_artifact], binaries = [unstripped_binary], debug_info_tset = cxx_output.external_debug_info),+ cxx_output.xcode_data,+ cxx_output.compilation_db,+ merge_bundle_linker_maps_info(bundle_infos),+ UnstrippedLinkOutputInfo(artifact = unstripped_binary),+ index_store_info,+ mod_dep_graph_info,+ swift_dependency_info,+ ],+ )+ + [resource_graph]+ + min_version_providers+ + link_command_providers+ + sanitizer_runtime_providers+ + validation_providers+ + diagnostics_providers+ + target_stats_providers+ + meta_xcassets_usage_providers+ )++ if cxx_output.xplugins_debug_artifacts_info:+ providers.append(cxx_output.xplugins_debug_artifacts_info)++ return providers++ if uses_explicit_modules(ctx):+ return get_swift_anonymous_targets(ctx, get_apple_binary_providers)+ else:+ return get_apple_binary_providers([])++def _get_extra_linker_outputs(+ ctx: AnalysisContext, extra_linker_output_category: ExtraLinkerOutputCategory = ExtraLinkerOutputCategory("produced-during-local-link")+) -> ExtraLinkerOutputs:+ _ = ctx # buildifier: disable=unused-variable+ # @oss-disable[end= ]: return get_extra_linker_outputs(ctx, extra_linker_output_category)+ return ExtraLinkerOutputs() # @oss-enable++def _get_extra_linker_outputs_flags(+ ctx: AnalysisContext,+ outputs: dict[str, Artifact],+ extra_linker_output_category: ExtraLinkerOutputCategory = ExtraLinkerOutputCategory("produced-during-local-link"),+) -> list[ArgLike]:+ _ = ctx # buildifier: disable=unused-variable+ # @oss-disable[end= ]: return get_extra_linker_output_flags(ctx, outputs, extra_linker_output_category)+ return [] # @oss-enable++def _extra_distributed_thin_lto_opt_outputs_merger(ctx: AnalysisContext, outputs_to_bind: dict[str, Artifact], outputs_to_merge: list[dict[str, Artifact]]):+ # @oss-disable[end= ]: return extra_distributed_thin_lto_opt_outputs_merger(ctx, outputs_to_bind, outputs_to_merge)+ return # @oss-enable++def _filter_swift_srcs(ctx: AnalysisContext) -> (list[CxxSrcWithFlags], list[CxxSrcWithFlags]):+ cxx_srcs = []+ swift_srcs = []+ for s in get_srcs_with_flags(ctx):+ if s.file.extension == SWIFT_EXTENSION:+ swift_srcs.append(s)+ else:+ cxx_srcs.append(s)+ return cxx_srcs, swift_srcs++def _get_bridging_header_flags(ctx: AnalysisContext) -> list[ArgLike]:+ if ctx.attrs.bridging_header:+ objc_bridging_header_flags = [+ # Disable bridging header -> PCH compilation to mitigate an issue in Xcode 13 beta.+ "-disable-bridging-pch",+ "-import-objc-header",+ cmd_args(ctx.attrs.bridging_header),+ ]++ headers_layout = cxx_get_regular_cxx_headers_layout(ctx)+ headers = cxx_attr_headers(ctx, headers_layout)+ header_map = {paths.join(h.namespace, h.name): h.artifact for h in headers}++ # We need to expose private headers to swift-compile action, in case something is imported to bridging header.+ cxx_toolchain_info = get_cxx_toolchain_info(ctx)+ header_mode = map_val(HeaderMode, getattr(ctx.attrs, "header_mode", None))+ allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs)+ uses_content_based_paths = get_uses_content_based_paths(ctx)+ header_root = prepare_headers(+ ctx.actions,+ cxx_toolchain_info,+ header_map,+ "apple-binary-private-headers",+ header_mode = header_mode,+ allow_cache_upload = allow_cache_upload,+ uses_content_based_paths = uses_content_based_paths,+ )+ if header_root != None:+ private_headers_args = [cmd_args("-I"), header_root.include_path]+ else:+ private_headers_args = []++ return objc_bridging_header_flags + private_headers_args+ else:+ return []
@@ -0,0 +1,717 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactTSet", # @unused Used as a type+ "make_artifact_tset",+ "project_artifacts",+)+load("@prelude//:paths.bzl", "paths")+load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")+load("@prelude//apple:apple_test_frameworks_utility.bzl", "get_test_frameworks_bundle_parts")+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo", "AppleToolsInfo")+load("@prelude//apple:debug.bzl", "AppleSelectiveDebuggableMetadata")+load(+ "@prelude//apple:modularization_dependency_graph.bzl",+ "ModularizationDependencyGraphInfo", # @unused Used as a type+ "create_modularization_dep_graph_subtargets_and_provider",+)+# @oss-disable[end= ]: load("@prelude//apple/meta_only:linker_outputs.bzl", "subtargets_for_apple_bundle_extra_outputs")+load("@prelude//apple/user:apple_selected_debug_path_file.bzl", "SELECTED_DEBUG_PATH_FILE_NAME")+load("@prelude//apple/user:apple_selective_debugging.bzl", "AppleSelectiveDebuggingInfo")+load("@prelude//apple/validation:required_reasons.bzl", "get_required_reasons_validator_output")+load("@prelude//apple/validation:swiftmodule_change_analysis.bzl", "get_swiftmodule_change_analysis_output")+load(+ "@prelude//cxx:cxx_transitive_diagnostics.bzl",+ "cxx_transitive_diagnostics_combine",+)+load(+ "@prelude//cxx:index_store.bzl",+ "IndexStoreInfo", # @unused Used as a type+ "create_index_store_subtargets_and_provider",+)+load(+ "@prelude//ide_integrations/xcode:data.bzl",+ "XCODE_DATA_SUB_TARGET",+ "XcodeDataInfoKeys",+ "generate_xcode_data",+)+load(+ "@prelude//linking:execution_preference.bzl",+ "LinkExecutionPreference",+ "LinkExecutionPreferenceInfo",+)+load(+ "@prelude//linking:link_info.bzl",+ "LinkCommandDebugOutputInfo", # @unused Used as a type+ "UnstrippedLinkOutputInfo",+ "make_link_command_debug_output_json_info",+)+load("@prelude//target_stats:target_stats.bzl", "target_stats_aggregate_providers_and_subtargets")+load("@prelude//utils:arglike.bzl", "ArgLike")+load("@prelude//utils:lazy.bzl", "lazy")+load(+ "@prelude//utils:utils.bzl",+ "flatten",+)+load(+ "@prelude//xplugins:debug_artifacts.bzl",+ "xplugins_get_debug_artifacts_info",+ "xplugins_get_debug_artifacts_subtargets",+ "xplugins_get_function_mapping_manifest_info",+)+load(":apple_bundle_destination.bzl", "AppleBundleDestination")+load(+ ":apple_bundle_part.bzl",+ "AppleBundleCodesignManifestTreePart",+ "AppleBundlePart",+ "AppleBundleSigningContextTreePart",+ "SwiftStdlibArguments",+ "assemble_bundle",+ "bundle_output",+ "get_apple_bundle_part_relative_destination_path",+ "get_bundle_dir_name",+)+load(":apple_bundle_resources.bzl", "get_apple_bundle_resource_part_list")+load(+ ":apple_bundle_types.bzl",+ "AppleBinaryExtraOutputsInfo",+ "AppleBundleBinaryOutput",+ "AppleBundleExtraOutputsInfo",+ "AppleBundleInfo",+ "AppleBundleLinkerMapInfo",+ "AppleBundleResourceInfo",+ "AppleBundleType",+ "AppleBundleTypeDefault",+ "AppleInfoPlistInfo",+)+load(":apple_bundle_utility.bzl", "get_bundle_min_target_version", "get_default_binary_dep", "get_flattened_binary_deps", "get_product_name")+load(":apple_code_signing_types.bzl", "CodeSignConfiguration", "get_code_signing_configuration_attr_value")+load(+ ":apple_dsym.bzl",+ "DSYM_INFO_SUBTARGET",+ "DSYM_SUBTARGET",+ "EXTENDED_DSYM_INFO_SUBTARGET",+ "get_apple_dsym",+ "get_apple_dsym_ext",+ "get_apple_dsym_info_json",+ "get_deps_debuggable_infos",+)+load(":apple_sdk.bzl", "get_apple_sdk_name")+load(+ ":apple_sdk_metadata.bzl",+ "MacOSXCatalystSdkMetadata",+ "MacOSXSdkMetadata",+)+load(":apple_universal_binaries.bzl", "create_universal_binary")+load(+ ":debug.bzl",+ "AggregatedAppleDebugInfo",+ "AppleDebuggableInfo",+ "get_aggregated_debug_info",+)+load(":xcode.bzl", "apple_xcode_data_add_xctoolchain")++_INSTALL_DATA_FILE_NAME = "install_apple_data.json"++_PLIST = "plist"++_XCTOOLCHAIN_SUB_TARGET = "xctoolchain"++AppleBundleDebuggableInfo = record(+ binary_info = field(AppleDebuggableInfo),+ # Debugable info of all bundle deps+ dep_infos = field(list[AppleDebuggableInfo]),+ # Concat of `binary_info` and `dep_infos`+ all_infos = field(list[AppleDebuggableInfo]),+)++AppleBundlePartListConstructorParams = record(+ # The binaries/executables, required to create a bundle+ binaries = field(list[AppleBundlePart]),+)++AppleBundlePartListOutput = record(+ # The parts to be copied into an Apple bundle, *including* binaries+ parts = field(list[AppleBundlePart]),+ # Part that holds the info.plist+ info_plist_part = field(AppleBundlePart),+ # Codesign manifest parts for inner bundles+ codesign_manifest_parts = field(list[AppleBundleCodesignManifestTreePart]),+ # Signing context parts for inner bundles+ signing_context_parts = field(list[AppleBundleSigningContextTreePart]),+)++_AppleBundleBinaryParts = record(+ all_parts = field(list[AppleBundlePart]),+ primary_part = field(AppleBundlePart),+ sub_targets = field(dict[str, list[DefaultInfo]]),+)++def _get_binary(ctx: AnalysisContext) -> AppleBundleBinaryOutput:+ binary_deps = get_flattened_binary_deps(ctx.attrs.binary)+ if len(binary_deps) > 1:+ if ctx.attrs.selective_debugging != None:+ fail("Selective debugging is not supported for universal binaries.")+ return create_universal_binary(+ ctx = ctx,+ binary_deps = ctx.attrs.binary,+ binary_name = "{}-UniversalBinary".format(get_product_name(ctx)),+ dsym_bundle_name = _get_bundle_dsym_name(ctx),+ split_arch_dsym = ctx.attrs.split_arch_dsym,+ )+ else:+ binary_dep = binary_deps[0]+ if len(binary_dep[DefaultInfo].default_outputs) != 1:+ fail("Expected single output artifact. Make sure the implementation of rule from `binary` attribute is correct.")++ return _maybe_scrub_binary(ctx, binary_dep)++def _get_bundle_dsym_name(ctx: AnalysisContext) -> str:+ return paths.replace_extension(get_bundle_dir_name(ctx), ".dSYM")++def _scrub_binary(+ ctx,+ binary: Artifact,+ binary_execution_preference_info: None | LinkExecutionPreferenceInfo,+ focused_targets_labels: list[Label] = [],+ identifier: None | str = None,+) -> Artifact:+ # If fast adhoc code signing is enabled, we need to resign the binary as it won't be signed later.+ code_signing_configuration = get_code_signing_configuration_attr_value(ctx)+ if code_signing_configuration == CodeSignConfiguration("fast-adhoc"):+ apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]+ adhoc_codesign_tool = apple_tools.adhoc_codesign_tool+ else:+ adhoc_codesign_tool = None++ selective_debugging_info = ctx.attrs.selective_debugging[AppleSelectiveDebuggingInfo]+ preference = binary_execution_preference_info.preference if binary_execution_preference_info else LinkExecutionPreference("any")+ return selective_debugging_info.scrub_binary(ctx, binary, preference, adhoc_codesign_tool, focused_targets_labels, identifier = identifier)++def _maybe_scrub_binary(ctx, binary_dep: Dependency) -> AppleBundleBinaryOutput:+ binary = binary_dep[DefaultInfo].default_outputs[0]+ unstripped_binary = binary_dep.get(UnstrippedLinkOutputInfo).artifact if binary_dep.get(UnstrippedLinkOutputInfo) != None else None+ debuggable_info = binary_dep.get(AppleDebuggableInfo)+ if ctx.attrs.selective_debugging == None:+ return AppleBundleBinaryOutput(binary = binary, unstripped_binary = unstripped_binary, debuggable_info = debuggable_info)++ if debuggable_info:+ if debuggable_info.selective_metadata:+ fail("Binary cannot contain selective metadata, as it only gets scrubbed when embedded in a bundle")++ # If we have debuggable info for this binary, create the scrubed dsym for the binary and filter debug info.+ debug_info_tset = debuggable_info.debug_info_tset++ # The traversal is intentionally designed to be topological, allowing us to skip+ # portions of the debug info that are not transitive in relation to the focused targets.+ all_debug_info = debug_info_tset._tset.traverse(ordering = "topological")+ selective_debugging_info = ctx.attrs.selective_debugging[AppleSelectiveDebuggingInfo]+ filtered_debug_info = selective_debugging_info.filter(ctx, all_debug_info)++ filtered_external_debug_info = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ infos = filtered_debug_info.infos,+ )++ # For debug symbols we take the unstripped unscrubbed binary+ debug_binaries = [unstripped_binary] if unstripped_binary else [binary]+ binary = _scrub_binary(ctx, binary, binary_dep.get(LinkExecutionPreferenceInfo), filtered_debug_info.swift_modules_labels)+ dsym_artifact = _get_scrubbed_binary_dsym(ctx, binary, debug_info_tset)++ filtered_map = {}+ for selected_target_info in filtered_debug_info.selected_target_infos:+ filtered_map.setdefault(selected_target_info.label, []).extend(selected_target_info.artifacts)++ debuggable_info = AppleDebuggableInfo(+ dsyms = [dsym_artifact],+ binaries = debug_binaries,+ debug_info_tset = filtered_external_debug_info,+ filtered_map = filtered_map,+ selective_metadata = [+ AppleSelectiveDebuggableMetadata(+ dsym = dsym_artifact,+ metadata = filtered_debug_info.metadata,+ ),+ ],+ )+ return AppleBundleBinaryOutput(binary = binary, unstripped_binary = unstripped_binary, debuggable_info = debuggable_info)+ else:+ binary = _scrub_binary(ctx, binary, binary_dep.get(LinkExecutionPreferenceInfo))+ return AppleBundleBinaryOutput(binary = binary, unstripped_binary = unstripped_binary)++def _get_scrubbed_binary_dsym(ctx, binary: Artifact, debug_info_tset: ArtifactTSet) -> Artifact:+ debug_info = project_artifacts(+ actions = ctx.actions,+ tsets = debug_info_tset,+ )+ dsym_artifact = get_apple_dsym(+ ctx = ctx,+ executable = binary,+ debug_info = debug_info,+ action_identifier = binary.short_path,+ )+ return dsym_artifact++def _get_binary_bundle_parts(+ ctx: AnalysisContext, binary_output: AppleBundleBinaryOutput, aggregated_debug_info: AggregatedAppleDebugInfo+) -> _AppleBundleBinaryParts:+ """Returns a tuple of all binary bundle parts and the primary bundle binary."""+ result = []++ primary_binary_part = AppleBundlePart(source = binary_output.binary, destination = AppleBundleDestination("executables"), new_name = get_product_name(ctx))+ result.append(primary_binary_part)++ selected_debug_target_part = _get_selected_debug_targets_part(ctx, aggregated_debug_info)+ if selected_debug_target_part:+ result.append(selected_debug_target_part)++ sub_targets = {+ "selected-debug-paths": [DefaultInfo(default_output = selected_debug_target_part.source if selected_debug_target_part else None)],+ }++ return _AppleBundleBinaryParts(+ all_parts = result,+ primary_part = primary_binary_part,+ sub_targets = sub_targets,+ )++def _get_dsym_input_binary_arg(ctx: AnalysisContext, binary_output: AppleBundleBinaryOutput, primary_binary_path_arg: cmd_args) -> cmd_args:+ # We've already scrubbed the default binary, we only want to scrub the unstripped one if present.+ unstripped_binary = binary_output.unstripped_binary+ if unstripped_binary:+ if ctx.attrs.selective_debugging != None:+ unstripped_binary = _scrub_binary(+ ctx, unstripped_binary, get_default_binary_dep(ctx.attrs.binary).get(LinkExecutionPreferenceInfo), identifier = "unstripped"+ )+ renamed_unstripped_binary = ctx.actions.copy_file(get_product_name(ctx), unstripped_binary, has_content_based_path = False)+ return cmd_args(renamed_unstripped_binary)+ else:+ return primary_binary_path_arg++def _apple_bundle_run_validity_checks(ctx: AnalysisContext):+ if ctx.attrs.extension == None:+ fail("`extension` attribute is required")++def _get_deps_selective_metadata(deps_debuggable_infos: list[AppleDebuggableInfo]) -> list[AppleSelectiveDebuggableMetadata]:+ all_metadatas = []+ for debuggable_info in deps_debuggable_infos:+ all_metadatas.extend(debuggable_info.selective_metadata)+ return all_metadatas++def _get_bundle_binary_dsym_artifacts(ctx: AnalysisContext, binary_output: AppleBundleBinaryOutput, executable_arg: ArgLike) -> list[Artifact]:+ if not ctx.attrs.split_arch_dsym:+ # Calling `dsymutil` on the correctly named binary in the _final bundle_ to yield dsym files+ # with naming convention compatible with Meta infra.+ binary_debuggable_info = binary_output.debuggable_info+ bundle_binary_dsym_artifact = get_apple_dsym_ext(+ ctx = ctx,+ executable = executable_arg,+ debug_info = project_artifacts(+ actions = ctx.actions,+ tsets = binary_debuggable_info.debug_info_tset if binary_debuggable_info else [],+ ),+ action_identifier = get_bundle_dir_name(ctx),+ output_path = _get_bundle_dsym_name(ctx),+ )+ return [bundle_binary_dsym_artifact]+ else:+ return binary_output.debuggable_info.dsyms++def _get_all_agg_debug_info(+ ctx: AnalysisContext, binary_output: AppleBundleBinaryOutput, deps_debuggable_infos: list[AppleDebuggableInfo]+) -> AggregatedAppleDebugInfo:+ all_debug_infos = deps_debuggable_infos + ([binary_output.debuggable_info] if binary_output.debuggable_info else [])+ return get_aggregated_debug_info(ctx, all_debug_infos)++def _maybe_scrub_selected_debug_paths_file(ctx: AnalysisContext, package_names: list[str]) -> Artifact:+ if not ctx.attrs.selective_debugging:+ return ctx.actions.write(SELECTED_DEBUG_PATH_FILE_NAME, sorted(set(package_names)), has_content_based_path = False)++ selective_debugging_info = ctx.attrs.selective_debugging[AppleSelectiveDebuggingInfo]+ return selective_debugging_info.scrub_selected_debug_paths_file(ctx, package_names, SELECTED_DEBUG_PATH_FILE_NAME)++def _get_selected_debug_targets_part(ctx: AnalysisContext, agg_debug_info: AggregatedAppleDebugInfo) -> [AppleBundlePart, None]:+ # Only app bundles need this. This file is searched by FBReport via+ # METAGetFocusedDebugPaths() which uses NSBundle URLForResource:+ if ctx.attrs.extension == "app" and agg_debug_info.debug_info.filtered_map:+ package_names = [label.package for label in agg_debug_info.debug_info.filtered_map.keys()]+ output = _maybe_scrub_selected_debug_paths_file(ctx, package_names)+ return AppleBundlePart(source = output, destination = AppleBundleDestination("resources"), new_name = SELECTED_DEBUG_PATH_FILE_NAME)+ else:+ return None++def get_apple_bundle_part_list(ctx: AnalysisContext, params: AppleBundlePartListConstructorParams) -> AppleBundlePartListOutput:+ resource_part_list = None+ if hasattr(ctx.attrs, "_resource_bundle") and ctx.attrs._resource_bundle != None:+ resource_info = ctx.attrs._resource_bundle[AppleBundleResourceInfo]+ if resource_info != None:+ resource_part_list = resource_info.resource_output++ if resource_part_list == None:+ resource_part_list = get_apple_bundle_resource_part_list(ctx)++ test_frameworks_parts = []+ if getattr(ctx.attrs, "embed_xctest_frameworks", False):+ if getattr(ctx.attrs, "extension", "") == "app":+ # XCTest frameworks should only be enabled for the top-level app,+ # not for any other bundles in the dep graph+ test_frameworks_parts = get_test_frameworks_bundle_parts(+ ctx,+ # It's not possible to pass information down the graph whether+ # the `apple_test()` rdep needs Swift support, so just assume+ # it does, in the future, Obj-C only test targets would be rare.+ swift_support_needed = True,+ )++ return AppleBundlePartListOutput(+ parts = resource_part_list.resource_parts + params.binaries + test_frameworks_parts,+ info_plist_part = resource_part_list.info_plist_part,+ codesign_manifest_parts = resource_part_list.codesign_manifest_parts,+ signing_context_parts = resource_part_list.signing_context_parts,+ )++def _infer_apple_bundle_type(ctx: AnalysisContext) -> AppleBundleType:+ if ctx.attrs.bundle_type != None:+ return AppleBundleType(ctx.attrs.bundle_type)++ return AppleBundleTypeDefault++def apple_bundle_impl(ctx: AnalysisContext) -> list[Provider]:+ _apple_bundle_run_validity_checks(ctx)++ binary_outputs = _get_binary(ctx)++ deps_debuggable_infos = get_deps_debuggable_infos(ctx)+ aggregated_debug_info = _get_all_agg_debug_info(ctx, binary_outputs, deps_debuggable_infos)++ binary_parts = _get_binary_bundle_parts(ctx, binary_outputs, aggregated_debug_info)+ apple_bundle_part_list_output = get_apple_bundle_part_list(ctx, AppleBundlePartListConstructorParams(binaries = binary_parts.all_parts))++ bundle = bundle_output(ctx)++ primary_binary_rel_path = get_apple_bundle_part_relative_destination_path(ctx, binary_parts.primary_part)++ validation_deps_outputs = get_validation_deps_outputs(ctx)++ incremental_bundling_override = None+ sdk_name = get_apple_sdk_name(ctx)+ if sdk_name == MacOSXSdkMetadata.name or sdk_name == MacOSXCatalystSdkMetadata.name:+ incremental_bundling_override = False++ bundle_result = assemble_bundle(+ ctx,+ bundle,+ apple_bundle_part_list_output.parts,+ apple_bundle_part_list_output.codesign_manifest_parts,+ apple_bundle_part_list_output.signing_context_parts,+ apple_bundle_part_list_output.info_plist_part,+ SwiftStdlibArguments(primary_binary_rel_path = primary_binary_rel_path),+ validation_deps_outputs,+ incremental_bundling_override = incremental_bundling_override,+ )+ sub_targets = bundle_result.sub_targets+ sub_targets.update(aggregated_debug_info.sub_targets)+ sub_targets.update(binary_parts.sub_targets)++ primary_binary_path = cmd_args([bundle, primary_binary_rel_path], delimiter = "/")+ primary_binary_path_arg = cmd_args(primary_binary_path, hidden = bundle)++ deps_with_binary = ctx.attrs.deps + get_flattened_binary_deps(ctx.attrs.binary)++ linker_maps_directory, linker_map_info = _linker_maps_data(ctx.actions, deps_with_binary)+ sub_targets["linker-maps"] = [DefaultInfo(default_output = linker_maps_directory)]++ xplugins_debug_info = xplugins_get_debug_artifacts_info(ctx, deps_with_binary)+ app_binary = get_default_binary_dep(ctx.attrs.binary) if ctx.attrs.extension == "app" and xplugins_debug_info else None+ xplugins_function_mapping_manifest_info = xplugins_get_function_mapping_manifest_info(+ ctx.actions,+ app_binary.label if app_binary else None,+ xplugins_debug_info,+ )+ sub_targets["xplugins"] = xplugins_get_debug_artifacts_subtargets(xplugins_function_mapping_manifest_info)++ link_cmd_debug_file, link_cmd_debug_info = _link_command_debug_data(ctx.actions, deps_with_binary)+ sub_targets["linker.command"] = [DefaultInfo(default_outputs = filter(None, [link_cmd_debug_file]))]++ # dsyms+ dsym_input_binary_arg = _get_dsym_input_binary_arg(ctx, binary_outputs, primary_binary_path_arg)+ binary_dsym_artifacts = _get_bundle_binary_dsym_artifacts(ctx, binary_outputs, dsym_input_binary_arg)+ # The same dSYM can reach a bundle through multiple dependency paths.+ dep_dsym_artifacts = set()+ for info in deps_debuggable_infos:+ dep_dsym_artifacts.update(info.dsyms)+ dep_dsym_artifacts = list(dep_dsym_artifacts)++ dsym_artifacts = binary_dsym_artifacts + dep_dsym_artifacts+ if dsym_artifacts:+ sub_targets[DSYM_SUBTARGET] = [DefaultInfo(default_outputs = dsym_artifacts)]++ dsym_json_info = get_apple_dsym_info_json(binary_dsym_artifacts, dep_dsym_artifacts)+ dsym_info = ctx.actions.write_json("dsym-info.json", dsym_json_info.json_object, pretty = True, has_content_based_path = False)+ sub_targets[DSYM_INFO_SUBTARGET] = [+ DefaultInfo(default_output = dsym_info, other_outputs = dsym_json_info.outputs),+ ]++ deps_selective_metadata = _get_deps_selective_metadata(deps_debuggable_infos)+ binary_selective_metadata = []+ if binary_outputs.debuggable_info and binary_outputs.debuggable_info.selective_metadata:+ if len(binary_outputs.debuggable_info.selective_metadata) > 1:+ fail("Binary cannot have multiple selective metadata")++ # `AppleSelectiveDebuggableMetadata` for the binary is computed here because+ # the dSYMs for the bundle get regenerated (via call to `_get_bundle_binary_dsym_artifacts()`).+ # To ensure we have the correct dSYM path, metadata needs to be created here, as otherwise+ # the map will contain the value of the dSYM for the standalone binary, not for the binary+ # as part of the bundle.+ binary_selective_metadata = [+ AppleSelectiveDebuggableMetadata(dsym = binary_dsym, metadata = binary_outputs.debuggable_info.selective_metadata[0].metadata)+ for binary_dsym in binary_dsym_artifacts+ ]+ all_selective_metadata = binary_selective_metadata + deps_selective_metadata++ extended_dsym_json_info = get_apple_dsym_info_json(binary_dsym_artifacts, dep_dsym_artifacts, all_selective_metadata)+ extended_dsym_info = ctx.actions.write_json("extended-dsym-info.json", extended_dsym_json_info.json_object, pretty = True, has_content_based_path = False)+ sub_targets[EXTENDED_DSYM_INFO_SUBTARGET] = [+ DefaultInfo(default_output = extended_dsym_info, other_outputs = extended_dsym_json_info.outputs),+ ]++ binary_name = get_product_name(ctx)++ # Debug binaries used for symbolication without dSYMs.+ # Create a symlink such that the basename of the exposed debug artifact+ # matches the name the binary has within the bundle (`binary_name`) instead+ # of the basename of the linker output. That's needed since GSYM upload+ # has to know the filename under which the binary ends up in the bundle.+ unstripped_binary_artifact = binary_outputs.unstripped_binary if binary_outputs.unstripped_binary else binary_outputs.binary+ renamed_unstripped_binary = ctx.actions.symlink_file(+ ctx.actions.declare_output("__unstripped_binaries__", binary_name),+ unstripped_binary_artifact,+ )+ binary_debug_artifacts = [renamed_unstripped_binary] + flatten([info.binaries for info in deps_debuggable_infos])++ sub_targets[_PLIST] = [DefaultInfo(default_output = apple_bundle_part_list_output.info_plist_part.source)]+ info_plist_info = AppleInfoPlistInfo(info_plist = apple_bundle_part_list_output.info_plist_part.source)++ sub_targets[_XCTOOLCHAIN_SUB_TARGET] = ctx.attrs._apple_xctoolchain.providers++ # Define the xcode data sub target+ plist_bundle_relative_path = get_apple_bundle_part_relative_destination_path(ctx, apple_bundle_part_list_output.info_plist_part)+ xcode_data_default_info, xcode_data_info = generate_xcode_data(+ ctx,+ "apple_bundle",+ bundle,+ _xcode_populate_attributes,+ processed_info_plist = apple_bundle_part_list_output.info_plist_part.source,+ info_plist_relative_path = plist_bundle_relative_path,+ )+ sub_targets[XCODE_DATA_SUB_TARGET] = xcode_data_default_info++ install_data = generate_install_data(ctx, plist_bundle_relative_path)++ # Collect extra bundle outputs+ extra_output_provider = _extra_output_provider(ctx)+ # @oss-disable[end= ]: extra_output_subtargets = subtargets_for_apple_bundle_extra_outputs(ctx, extra_output_provider)+ # @oss-disable[end= ]: sub_targets.update(extra_output_subtargets)++ # index store+ index_store_subtargets, index_store_info = _index_store_data(ctx, deps_with_binary)+ sub_targets.update(index_store_subtargets)++ # modularization dependency graphs+ mod_dep_graph_subtargets, mod_dep_graph_info = _modularization_dep_graph_data(ctx, deps_with_binary)+ sub_targets.update(mod_dep_graph_subtargets)++ target_stats_providers, target_stats_subtargets = target_stats_aggregate_providers_and_subtargets(ctx, deps = deps_with_binary)+ sub_targets.update(target_stats_subtargets)++ bundle_and_dsym_info_json = {+ "bundle": bundle,+ "dsym": dsym_json_info.json_object,+ }+ bundle_and_dsym_info = ctx.actions.write_json("bundle-and-dsym-info.json", bundle_and_dsym_info_json, has_content_based_path = False)+ sub_targets["bundle-and-dsym-info"] = [+ DefaultInfo(+ default_output = bundle_and_dsym_info,+ other_outputs = [bundle] + dsym_json_info.outputs,+ ),+ ]++ required_reasons_validator_output = get_required_reasons_validator_output(+ ctx,+ aggregated_debug_info.debug_info.debug_info_tset,+ )+ if required_reasons_validator_output != None:+ sub_targets["required-reasons-validation"] = [+ DefaultInfo(default_output = required_reasons_validator_output),+ ]+ validation_providers = [+ ValidationInfo(+ validations = [+ ValidationSpec(+ name = "required_reasons_usage",+ validation_result = required_reasons_validator_output,+ ),+ ],+ ),+ ]+ else:+ validation_providers = []++ diagnostics_info = cxx_transitive_diagnostics_combine(+ ctx = ctx,+ diagnostics = [],+ deps = deps_with_binary,+ )+ transitive_diagnostic_artifacts = project_artifacts(+ actions = ctx.actions,+ tsets = diagnostics_info.transitive_diagnostics,+ )+ sub_targets["check"] = [DefaultInfo(default_output = None, other_outputs = transitive_diagnostic_artifacts)]++ sub_targets["swiftmodule-change-analysis"] = [DefaultInfo(default_output = get_swiftmodule_change_analysis_output(ctx, deps_with_binary))]++ providers = (+ [+ DefaultInfo(default_output = bundle, sub_targets = sub_targets),+ AppleBundleInfo(+ bundle = bundle,+ bundle_type = _infer_apple_bundle_type(ctx),+ binary_name = binary_name,+ contains_watchapp = lazy.is_any(lambda part: part.destination == AppleBundleDestination("watchapp"), apple_bundle_part_list_output.parts),+ skip_copying_swift_stdlib = ctx.attrs.skip_copying_swift_stdlib,+ codesign_manifest_tree = bundle_result.codesign_manifest_tree,+ signing_context_tree = bundle_result.signing_context_tree,+ signing_info = bundle_result.signing_info,+ ),+ AppleDebuggableInfo(+ dsyms = dsym_artifacts,+ binaries = binary_debug_artifacts,+ debug_info_tset = aggregated_debug_info.debug_info.debug_info_tset,+ filtered_map = aggregated_debug_info.debug_info.filtered_map,+ selective_metadata = all_selective_metadata,+ ),+ InstallInfo(+ installer = ctx.attrs._apple_toolchain[AppleToolchainInfo].installer,+ files = {+ "app_bundle": bundle,+ "options": install_data,+ },+ ),+ RunInfo(args = primary_binary_path_arg),+ linker_map_info,+ xcode_data_info,+ extra_output_provider,+ link_cmd_debug_info,+ index_store_info,+ mod_dep_graph_info,+ info_plist_info,+ ]+ + target_stats_providers+ + bundle_result.providers+ + validation_providers+ )+ if xplugins_debug_info:+ providers.append(xplugins_debug_info)+ providers.append(xplugins_function_mapping_manifest_info)++ return providers++def _xcode_populate_attributes(ctx, processed_info_plist: Artifact, info_plist_relative_path: str) -> dict[str, typing.Any]:+ data = {+ XcodeDataInfoKeys.BUNDLE_TYPE: _infer_apple_bundle_type(ctx),+ XcodeDataInfoKeys.DEPLOYMENT_VERSION: get_bundle_min_target_version(ctx, get_default_binary_dep(ctx.attrs.binary)),+ XcodeDataInfoKeys.INFO_PLIST: ctx.attrs.info_plist,+ XcodeDataInfoKeys.PROCESSED_INFO_PLIST: processed_info_plist,+ XcodeDataInfoKeys.INFO_PLIST_RELATIVE_PATH: info_plist_relative_path,+ XcodeDataInfoKeys.PRODUCT_NAME: get_product_name(ctx),+ XcodeDataInfoKeys.SDK: get_apple_sdk_name(ctx),+ XcodeDataInfoKeys.APP_EXTENSION_DEPENDENCIES: _app_extension_deps(ctx),+ }++ apple_xcode_data_add_xctoolchain(ctx, data)+ return data++def _linker_maps_data(actions: AnalysisActions, deps_with_binary: list[Dependency]) -> (Artifact, AppleBundleLinkerMapInfo):+ deps_linker_map_infos = filter(+ None,+ [dep.get(AppleBundleLinkerMapInfo) for dep in deps_with_binary],+ )+ deps_linker_maps = flatten([info.linker_maps for info in deps_linker_map_infos])+ all_maps = {map.basename: map for map in deps_linker_maps}+ directory = actions.copied_dir(+ "LinkMap",+ all_maps,+ has_content_based_path = False,+ )+ provider = AppleBundleLinkerMapInfo(linker_maps = all_maps.values())+ return (directory, provider)++def _link_command_debug_data(actions: AnalysisActions, deps_with_binary: list[Dependency]) -> (Artifact, LinkCommandDebugOutputInfo):+ debug_output_infos = filter(+ None,+ [dep.get(LinkCommandDebugOutputInfo) for dep in deps_with_binary],+ )+ all_debug_infos = flatten([debug_info.debug_outputs for debug_info in debug_output_infos])+ link_cmd_debug_output_file = make_link_command_debug_output_json_info(actions, all_debug_infos)+ return link_cmd_debug_output_file, LinkCommandDebugOutputInfo(debug_outputs = all_debug_infos)++def _index_store_data(ctx: AnalysisContext, deps_with_binary: list[Dependency]) -> (dict[str, list[Provider]], IndexStoreInfo):+ index_store_subtargets, index_store_info = create_index_store_subtargets_and_provider(ctx, [], [], deps_with_binary)+ return index_store_subtargets, index_store_info++def _modularization_dep_graph_data(ctx: AnalysisContext, deps_with_binary: list[Dependency]) -> (dict[str, list[Provider]], ModularizationDependencyGraphInfo):+ subtargets, info = create_modularization_dep_graph_subtargets_and_provider(ctx, None, deps_with_binary)+ return subtargets, info++def _extra_output_provider(ctx: AnalysisContext) -> AppleBundleExtraOutputsInfo:+ # Collect the sub_targets for this bundle's binary that are extra_linker_outputs.+ extra_outputs = []+ for binary_dep in get_flattened_binary_deps(ctx.attrs.binary):+ linker_outputs = ctx.attrs._apple_toolchain[AppleToolchainInfo].extra_linker_outputs+ binary_outputs = {k: v[DefaultInfo].default_outputs for k, v in binary_dep[DefaultInfo].sub_targets.items() if k in linker_outputs}+ extra_outputs.append(+ AppleBinaryExtraOutputsInfo(+ name = get_product_name(ctx),+ default_output = binary_dep[DefaultInfo].default_outputs[0],+ extra_outputs = binary_outputs,+ )+ )++ # Collect the transitive extra bundle outputs from the deps.+ for dep in ctx.attrs.deps:+ if AppleBundleExtraOutputsInfo in dep:+ extra_outputs.extend(dep[AppleBundleExtraOutputsInfo].extra_outputs)++ return AppleBundleExtraOutputsInfo(extra_outputs = extra_outputs)++def _app_extension_deps(ctx: AnalysisContext) -> list[str]:+ app_extension_deps = []+ for dep in ctx.attrs.deps:+ apple_bundle_info = dep.get(AppleBundleInfo)+ if apple_bundle_info and paths.split_extension(apple_bundle_info.bundle.short_path)[1] == ".appex":+ app_extension_deps.append(str(dep.label.raw_target()))+ return app_extension_deps++def generate_install_data(ctx: AnalysisContext, plist_path: str, populate_rule_specific_attributes_func: [typing.Callable, None] = None, **kwargs) -> Artifact:+ data = {+ "fullyQualifiedName": ctx.label,+ "info_plist": plist_path,+ "platform_name": get_apple_sdk_name(ctx),+ ## TODO(T110665037): read from .buckconfig+ # We require the user to have run `xcode-select` and `/var/db/xcode_select_link` to symlink+ # to the selected Xcode. e.g: `/Applications/Xcode_14.2.app/Contents/Developer`+ "xcode_developer_path": "/var/db/xcode_select_link",+ }++ if populate_rule_specific_attributes_func:+ data.update(populate_rule_specific_attributes_func(ctx, **kwargs))++ return ctx.actions.write_json(_INSTALL_DATA_FILE_NAME, data, has_content_based_path = False)
@@ -0,0 +1,56 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//utils:buckconfig.bzl", "read_bool")+load(":apple_code_signing_types.bzl", "CodeSignConfiguration")++def _read_bool(config: str, default: [None, bool] = None) -> [None, bool]:+ return read_bool("apple", config, default = default, required = False, root_cell = True)++def _get_code_signing_configuration() -> str:+ is_dry_run = _read_bool("dry_run_code_signing", False)++ # This is a kill switch for the feature, it can also be disabled by setting+ # `apple.fast_adhoc_signing_enabled=false` in a global buckconfig file.+ is_fast_adhoc_signing_enabled = _read_bool("fast_adhoc_signing_enabled", True)++ is_codesign_execution_bypass_enabled = _read_bool("codesign_execution_bypass", False)+ if is_dry_run and is_codesign_execution_bypass_enabled:+ fail("Dry run and execution bypass are mutually exclusive, pick one")++ if is_dry_run:+ return CodeSignConfiguration("dry-run").value+ elif is_codesign_execution_bypass_enabled:+ # Fast adhoc only makes sense if we're executing codesign commands,+ # hence execution bypass takes precedence+ return CodeSignConfiguration("execution-bypass").value+ elif is_fast_adhoc_signing_enabled:+ return CodeSignConfiguration("fast-adhoc").value+ else:+ return CodeSignConfiguration("none").value++def apple_bundle_config() -> dict[str, typing.Any]:+ return {+ "_bundling_cache_buster": read_root_config("apple", "bundling_cache_buster", None),+ "_bundling_log_file_enabled": _read_bool("bundling_log_file_enabled", True),+ "_bundling_log_file_level": read_root_config("apple", "bundling_log_file_level", None),+ "_code_signing_configuration": _get_code_signing_configuration(),+ "_codesign_command_override": read_root_config("apple", "codesign_command_override", None),+ "_codesign_identities_command_override": read_root_config("apple", "codesign_identities_command_override", None),+ "_codesign_type": read_root_config("apple", "codesign_type_override", None),+ "_compile_resources_locally_override": _read_bool("compile_resources_locally_override"),+ "_embed_provisioning_profile_when_adhoc_code_signing": _read_bool("embed_provisioning_profile_when_adhoc_code_signing"),+ "_fast_adhoc_signing_probe_enabled": _read_bool("fast_adhoc_signing_probe_enabled", False),+ "_fast_provisioning_profile_parsing_enabled": _read_bool("fast_provisioning_profile_parsing_enabled", False),+ "_incremental_bundling_enabled": _read_bool("incremental_bundling_enabled", True),+ "_info_plist_identify_build_system_default": _read_bool("info_plist_identify_build_system", True),+ "_no_check_certificates": _read_bool("no_check_certificates", False),+ "_profile_bundling_enabled": _read_bool("profile_bundling_enabled", False),+ "_skip_adhoc_resigning_scrubbed_frameworks_override": _read_bool("skip_adhoc_resigning_scrubbed_frameworks_override"),+ "_use_entitlements_when_adhoc_code_signing": _read_bool("use_entitlements_when_adhoc_code_signing"),+ }
@@ -0,0 +1,159 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load(":apple_bundle_utility.bzl", "get_apple_versioned_macos_bundle_value_primitive")++# Abstraction of a place in a resulting bundle where file or directory will be copied. Actual value+# of path relative to bundle root depends on a platform. This class is an implementation detail and+# is not exposed to user unlike `AppleResourceDestination`.+# v1 code is `com/facebook/buck/apple/AppleBundleDestination.java`+AppleBundleDestination = enum(+ "resources",+ "frameworks",+ "executables",+ "plugins",+ "xpcservices",+ "metadata",+ "watchapp",+ "headers",+ "modules",+ "quicklook",+ "bundleroot",+ "loginitems",+ "launchagents",+ "appclips",+ "extensionkit_extensions",+)++AppleBundleDestinationPaths = record(+ resources = field(str, ""),+ frameworks = field(str, ""),+ executables = field(str, ""),+ plugins = field(str, ""),+ xpcservices = field(str, ""),+ metadata = field(str, ""),+ watchapp = field(str, ""),+ headers = field(str, ""),+ modules = field(str, ""),+ quicklook = field(str, ""),+ bundleroot = field(str, ""),+ loginitems = field(str, ""),+ launchagents = field(str, ""),+ appclips = field(str, ""),+ extensionkit_extensions = field(str, ""),+)++_IOSBundleDestinationPaths = AppleBundleDestinationPaths(+ frameworks = "Frameworks",+ plugins = "PlugIns",+ xpcservices = "XPCServices",+ watchapp = "Watch",+ quicklook = "Library/QuickLook",+ appclips = "AppClips",+ extensionkit_extensions = "Extensions",+)++_IOSFrameworkBundleDestinationPaths = AppleBundleDestinationPaths(+ frameworks = "Frameworks",+ xpcservices = "XPCServices",+ headers = "Headers",+ modules = "Modules",+)++macOS_content_path = "Contents"+_MacOSBundleDestinationPaths = AppleBundleDestinationPaths(+ resources = paths.join(macOS_content_path, "Resources"),+ frameworks = paths.join(macOS_content_path, "Frameworks"),+ executables = paths.join(macOS_content_path, "MacOS"),+ plugins = paths.join(macOS_content_path, "PlugIns"),+ xpcservices = paths.join(macOS_content_path, "XPCServices"),+ metadata = macOS_content_path,+ watchapp = macOS_content_path,+ headers = macOS_content_path,+ modules = macOS_content_path,+ quicklook = paths.join(macOS_content_path, "Library/QuickLook"),+ bundleroot = macOS_content_path,+ loginitems = paths.join(macOS_content_path, "Library/LoginItems"),+ launchagents = paths.join(macOS_content_path, "Library/LaunchAgents"),+)++_MacOSFrameworkBundleDestinationPaths = AppleBundleDestinationPaths(+ resources = "Resources",+ frameworks = "Frameworks",+ plugins = "PlugIns",+ xpcservices = "XPCServices",+ metadata = "Resources",+ headers = "Headers",+ modules = "Modules",+)++macOS_versioned_path = "Versions/A"+_MacOSVersionedFrameworkBundleDestinationPaths = AppleBundleDestinationPaths(+ resources = paths.join(macOS_versioned_path, "Resources"),+ frameworks = paths.join(macOS_versioned_path, "Frameworks"),+ plugins = paths.join(macOS_versioned_path, "PlugIns"),+ xpcservices = paths.join(macOS_versioned_path, "XPCServices"),+ metadata = paths.join(macOS_versioned_path, "Resources"),+ headers = paths.join(macOS_versioned_path, "Headers"),+ modules = paths.join(macOS_versioned_path, "Modules"),+ executables = macOS_versioned_path,+)++def _get_apple_bundle_destinations_for_sdk_name(name: str) -> AppleBundleDestinationPaths:+ if name == "macosx" or name == "maccatalyst":+ return _MacOSBundleDestinationPaths+ else:+ return _IOSBundleDestinationPaths++def _get_apple_framework_bundle_destinations_for_sdk_name(name: str, versioned_macos_bundle: bool) -> AppleBundleDestinationPaths:+ if name.startswith("mac"):+ if get_apple_versioned_macos_bundle_value_primitive(name, versioned_macos_bundle):+ return _MacOSVersionedFrameworkBundleDestinationPaths+ else:+ return _MacOSFrameworkBundleDestinationPaths+ else:+ return _IOSFrameworkBundleDestinationPaths++def bundle_relative_path_for_destination(destination: AppleBundleDestination, sdk_name: str, extension: str, versioned_macos_bundle: bool) -> str:+ if extension == "framework":+ bundle_destinations = _get_apple_framework_bundle_destinations_for_sdk_name(sdk_name, versioned_macos_bundle)+ else:+ bundle_destinations = _get_apple_bundle_destinations_for_sdk_name(sdk_name)++ if destination == AppleBundleDestination("resources"):+ return bundle_destinations.resources+ elif destination == AppleBundleDestination("frameworks"):+ return bundle_destinations.frameworks+ elif destination == AppleBundleDestination("executables"):+ return bundle_destinations.executables+ elif destination == AppleBundleDestination("extensionkit_extensions"):+ return bundle_destinations.extensionkit_extensions+ elif destination == AppleBundleDestination("plugins"):+ return bundle_destinations.plugins+ elif destination == AppleBundleDestination("xpcservices"):+ return bundle_destinations.xpcservices+ elif destination == AppleBundleDestination("metadata"):+ return bundle_destinations.metadata+ elif destination == AppleBundleDestination("watchapp"):+ return bundle_destinations.watchapp+ elif destination == AppleBundleDestination("headers"):+ return bundle_destinations.headers+ elif destination == AppleBundleDestination("modules"):+ return bundle_destinations.modules+ elif destination == AppleBundleDestination("quicklook"):+ return bundle_destinations.quicklook+ elif destination == AppleBundleDestination("bundleroot"):+ return bundle_destinations.bundleroot+ elif destination == AppleBundleDestination("loginitems"):+ return bundle_destinations.loginitems+ elif destination == AppleBundleDestination("launchagents"):+ return bundle_destinations.launchagents+ elif destination == AppleBundleDestination("appclips"):+ return bundle_destinations.appclips+ fail("Unsupported Apple bundle destination {}".format(destination))
@@ -0,0 +1,666 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load("@prelude//apple:apple_provisioning_profile_sources.bzl", "AppleProvisioningProfileSourcesInfo")+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftToolchainInfo")+load("@prelude//utils:utils.bzl", "value_or")+load(":apple_bundle_destination.bzl", "AppleBundleDestination", "bundle_relative_path_for_destination")+load(+ ":apple_bundle_types.bzl",+ "AppleBundleCodesignManifestTree",+ "AppleBundleManifest",+ "AppleBundleManifestInfo",+ "AppleBundleManifestLogFiles",+ "AppleBundleSigningContextTree",+)+load(":apple_bundle_utility.bzl", "get_extension_attr", "get_product_name")+load(":apple_code_signing_types.bzl", "CodeSignConfiguration", "CodeSignType", "get_code_signing_configuration_attr_value")+load(":apple_entitlements.bzl", "get_entitlements_codesign_args", "should_include_entitlements")+load(":apple_error_handler.bzl", "apple_build_error_handler")+load(":apple_sdk.bzl", "get_apple_sdk_name")+load(":apple_sdk_metadata.bzl", "get_apple_sdk_metadata_for_sdk_name")+load(":apple_swift_stdlib.bzl", "should_copy_swift_stdlib")+load(":apple_toolchain_types.bzl", "AppleToolchainInfo", "AppleToolsInfo")++# Must match the null case returned by `serialize_signing_context_data`:+# https://www.internalfb.com/code/fbsource/fbcode/buck2/prelude/apple/tools/bundling/signing_context_data.py?lines=39%2C58+_EMPTY_SIGNING_CONTEXT_DATA = {+ "provisioning_profile_data_base64": None,+ "selected_identity": None,+ "signing_context": None,+ "version": 1,+}++# Defines where and what should be copied into+AppleBundlePart = record(+ # A file or directory which content should be copied+ source = field(Artifact),+ # Where the source should be copied, the actual destination directory+ # inside bundle depends on target platform+ destination = AppleBundleDestination,+ # New file name if it should be renamed before copying.+ # Empty string value is applicable only when `source` is a directory,+ # in such case only content of the directory will be copied, as opposed to the directory itself.+ # When value is `None`, directory or file will be copied as it is, without renaming.+ new_name = field([str, None], None),+ # Marks parts which should be code signed separately from the whole bundle.+ codesign_on_copy = field(bool, False),+ # Entitlements to use when this part is code signed separately.+ codesign_entitlements = field(Artifact | None, None),+ # If present, override the codesign flags with these flags, when this part is code signed separately.+ codesign_flags_override = field([list[str], None], None),+ # If present, additional paths to be codesigned when copying.+ extra_codesign_paths = field([list[str], None], None),+)++# Represents an `AppleBundlePart` which has an associated codesign manifest+AppleBundleCodesignManifestTreePart = record(+ bundle_part = field(AppleBundlePart),+ codesign_manifest_tree = field(AppleBundleCodesignManifestTree),+)++# Represents an `AppleBundlePart` which has an associated signing context+AppleBundleSigningContextTreePart = record(+ bundle_part = field(AppleBundlePart),+ signing_context_tree = field(AppleBundleSigningContextTree),+)++SwiftStdlibArguments = record(+ primary_binary_rel_path = field(str),+)++AppleBundleConstructionResult = record(+ providers = field(list[Provider]),+ sub_targets = field(dict[str, list[Provider]]),+ codesign_manifest_tree = field(AppleBundleCodesignManifestTree),+ signing_context_tree = field(AppleBundleSigningContextTree),+ signing_info = field(Artifact),+)++def bundle_output(ctx: AnalysisContext) -> Artifact:+ bundle_dir_name = get_bundle_dir_name(ctx)+ output = ctx.actions.declare_output(bundle_dir_name, has_content_based_path = False)+ return output++def _bundling_log_args(ctx: AnalysisContext, output_name: str):+ if not ctx.attrs._bundling_log_file_enabled:+ return ([], None)++ output = ctx.actions.declare_output(output_name, has_content_based_path = False)+ args = ["--log-file", output.as_output()]+ if ctx.attrs._bundling_log_file_level:+ args.extend(["--log-level-file", ctx.attrs._bundling_log_file_level])+ return (args, output)++def assemble_bundle(+ ctx: AnalysisContext,+ bundle: Artifact,+ parts: list[AppleBundlePart],+ codesign_manifest_parts: list[AppleBundleCodesignManifestTreePart],+ signing_context_parts: list[AppleBundleSigningContextTreePart],+ info_plist_part: [AppleBundlePart, None],+ swift_stdlib_args: [SwiftStdlibArguments, None],+ extra_hidden: list[Artifact] = [],+ skip_adhoc_signing: bool = False,+ incremental_bundling_override = None,+) -> AppleBundleConstructionResult:+ """+ Returns extra subtargets related to bundling.+ """+ all_parts = parts + [info_plist_part] if info_plist_part else []+ codesign_type = _detect_codesign_type(ctx, skip_adhoc_signing)+ spec_file = _bundle_spec_json(ctx, all_parts, codesign_type)++ tools = ctx.attrs._apple_tools[AppleToolsInfo]+ tool = tools.assemble_bundle++ codesign_selection_args = []+ codesign_execution_args = []+ codesign_bundle_extra_args = []++ codesign_tool = ctx.attrs._apple_toolchain[AppleToolchainInfo].codesign+ if ctx.attrs._codesign_command_override:+ codesign_tool = ctx.attrs._codesign_command_override[RunInfo]++ code_signing_configuration = get_code_signing_configuration_attr_value(ctx)+ if code_signing_configuration == CodeSignConfiguration("dry-run"):+ codesign_configuration_args = ["--codesign-configuration", "dry-run"]+ codesign_tool = tools.dry_codesign_tool+ elif code_signing_configuration == CodeSignConfiguration("execution-bypass"):+ codesign_configuration_args = ["--codesign-configuration", "execution-bypass"]+ elif code_signing_configuration == CodeSignConfiguration("fast-adhoc"):+ if _get_fast_adhoc_signing_enabled(ctx):+ codesign_configuration_args = ["--codesign-configuration", "fast-adhoc"]+ if getattr(ctx.attrs, "_fast_adhoc_signing_probe_enabled", False):+ codesign_configuration_args = codesign_configuration_args + ["--fast-adhoc-signing-probe-enabled"]+ else:+ codesign_configuration_args = []+ elif code_signing_configuration == CodeSignConfiguration("none"):+ codesign_configuration_args = []+ else:+ fail("Code signing configuration `{}` not supported".format(code_signing_configuration))++ codesign_required = codesign_type != CodeSignType("skip")+ swift_support_required = swift_stdlib_args and (not ctx.attrs.skip_copying_swift_stdlib) and should_copy_swift_stdlib(bundle.extension)++ sdk_name = get_apple_sdk_name(ctx)+ if codesign_required or swift_support_required:+ platform_args = ["--platform", sdk_name]+ else:+ platform_args = []++ if swift_support_required:+ swift_args = [+ "--binary-destination",+ swift_stdlib_args.primary_binary_rel_path,+ "--frameworks-destination",+ bundle_relative_path_for_destination(AppleBundleDestination("frameworks"), sdk_name, ctx.attrs.extension, ctx.attrs.versioned_macos_bundle),+ "--plugins-destination",+ bundle_relative_path_for_destination(AppleBundleDestination("plugins"), sdk_name, ctx.attrs.extension, ctx.attrs.versioned_macos_bundle),+ "--extensionkit-extensions-destination",+ bundle_relative_path_for_destination(+ AppleBundleDestination("extensionkit_extensions"), sdk_name, ctx.attrs.extension, ctx.attrs.versioned_macos_bundle+ ),+ "--appclips-destination",+ bundle_relative_path_for_destination(AppleBundleDestination("appclips"), sdk_name, ctx.attrs.extension, ctx.attrs.versioned_macos_bundle),+ "--swift-stdlib-command",+ cmd_args(ctx.attrs._apple_toolchain[SwiftToolchainInfo].swift_stdlib_tool, delimiter = " ", quote = "shell"),+ "--sdk-root",+ ctx.attrs._apple_toolchain[SwiftToolchainInfo].sdk_path,+ ]+ else:+ swift_args = []++ if codesign_required:+ codesign_execution_args += [+ "--codesign",+ ]++ codesign_bundle_extra_args += [+ "--codesign-tool",+ codesign_tool,+ ]++ profile_selection_required = _should_embed_provisioning_profile(ctx, codesign_type)+ if profile_selection_required:+ sources_info = ctx.attrs._provisioning_profile_sources[AppleProvisioningProfileSourcesInfo]+ for i, source in enumerate(sources_info.sources):+ if source.profiles:+ profiles_dir = ctx.actions.symlinked_dir(+ "provisioning_profile_source_{}".format(i),+ {profile.short_path: profile for profile in source.profiles},+ has_content_based_path = False,+ )+ codesign_selection_args.extend(["--profiles-dir", profiles_dir])+ elif source.directory:+ codesign_selection_args.extend(["--profiles-dir", source.directory])++ identities_command = ctx.attrs._apple_toolchain[AppleToolchainInfo].codesign_identities_command+ if ctx.attrs._codesign_identities_command_override:+ identities_command = ctx.attrs._codesign_identities_command_override[RunInfo]+ identities_command_args = ["--codesign-identities-command", cmd_args(identities_command)] if identities_command else []+ codesign_selection_args.extend(identities_command_args)++ if codesign_type == CodeSignType("adhoc"):+ codesign_selection_args.append("--ad-hoc")+ if ctx.attrs.codesign_identity:+ codesign_selection_args.extend(["--ad-hoc-codesign-identity", ctx.attrs.codesign_identity])+ if profile_selection_required:+ codesign_selection_args.append("--embed-provisioning-profile-when-signing-ad-hoc")++ entitlements_args = get_entitlements_codesign_args(ctx, codesign_type)+ codesign_execution_args += entitlements_args++ if getattr(ctx.attrs, "entitlements_suffixed_key_map", None):+ arg = ["--entitlements-suffixed-key-map", json.encode(ctx.attrs.entitlements_suffixed_key_map)]+ codesign_execution_args += arg+ if getattr(ctx.attrs, "entitlements_removed_keys", None):+ arg = ["--entitlements-removed-keys", json.encode(ctx.attrs.entitlements_removed_keys)]+ codesign_execution_args += arg+ if getattr(ctx.attrs, "entitlements_removed_values_map", None):+ arg = ["--entitlements-removed-values-map", json.encode(ctx.attrs.entitlements_removed_values_map)]+ codesign_execution_args += arg+ codesign_bundle_extra_args += _get_extra_codesign_args(ctx)++ info_plist_args = (+ [+ "--info-plist-source",+ info_plist_part.source,+ "--info-plist-destination",+ get_apple_bundle_part_relative_destination_path(ctx, info_plist_part),+ ]+ if info_plist_part+ else []+ )+ codesign_execution_args.extend(info_plist_args)++ if ctx.attrs.provisioning_profile_filter:+ arg = [+ "--provisioning-profile-filter",+ ctx.attrs.provisioning_profile_filter,+ ]+ codesign_selection_args.extend(arg)++ strict_provisioning_profile_search = value_or(ctx.attrs.strict_provisioning_profile_search, ctx.attrs._strict_provisioning_profile_search_default)+ if strict_provisioning_profile_search:+ codesign_selection_args.append("--strict-provisioning-profile-search")++ if ctx.attrs._fast_provisioning_profile_parsing_enabled:+ codesign_selection_args.append("--fast-provisioning-profile-parsing")++ if ctx.attrs._no_check_certificates:+ codesign_selection_args.append("--no-check-certificates")++ if ctx.attrs.entitlements_verification_check_enabled:+ codesign_selection_args.append("--verify-entitlements")++ elif codesign_type == CodeSignType("skip"):+ pass+ else:+ fail("Code sign type `{}` not supported".format(codesign_type))++ force_local_bundling = codesign_required+ env = {}+ cache_buster = ctx.attrs._bundling_cache_buster+ if cache_buster:+ env["BUCK2_BUNDLING_CACHE_BUSTER"] = cache_buster++ if codesign_required:+ signing_context_path = ctx.actions.declare_output("signing_context.json", has_content_based_path = False)+ resolve_command = [+ tools.resolve_signing_context,+ "--output",+ signing_context_path.as_output(),+ ]+ resolution_log_args, resolution_log_output = _bundling_log_args(ctx, "signing_context_resolution_log.txt")+ resolve_command.extend(resolution_log_args)+ ctx.actions.run(+ cmd_args(+ resolve_command + platform_args + codesign_selection_args + codesign_execution_args,+ ),+ local_only = force_local_bundling,+ prefer_local = not force_local_bundling,+ category = "apple_resolve_signing_context",+ env = env,+ error_handler = apple_build_error_handler,+ )+ signing_context_path_arg = ["--signing-context-path", signing_context_path]++ signing_info_output = ctx.actions.declare_output("signing-info.json", has_content_based_path = False)+ ctx.actions.run(+ cmd_args(+ [+ tools.signing_info,+ "--signing-context-path",+ signing_context_path,+ "--output",+ signing_info_output.as_output(),+ ],+ ),+ category = "apple_signing_info",+ error_handler = apple_build_error_handler,+ )+ else:+ resolution_log_output = None+ # Avoid adding a resolver action to every unsigned bundle target.+ signing_context_path = ctx.actions.write_json(+ "signing_context.json",+ _EMPTY_SIGNING_CONTEXT_DATA,+ )+ signing_context_path_arg = ["--signing-context-path", signing_context_path]+ signing_info_output = ctx.actions.write_json("signing-info.json", {})++ # - Always request codesign manifest, even if signing not required.+ # Removes the need for conditional subtargets and fields in JSON output.+ # - Manifest file name reflects whether signing is required or not.+ # Useful for debugging purposes.+ codesign_manifest_file_name = "codesign_manifest.json" if codesign_required else "placeholder_codesign_manifest.json"+ codesign_manifest = ctx.actions.declare_output(codesign_manifest_file_name, has_content_based_path = False)+ codesign_bundle_extra_args += [+ "--codesign-manifest",+ codesign_manifest.as_output(),+ ]++ extra_context_args = [+ "--resources-destination",+ bundle_relative_path_for_destination(AppleBundleDestination("resources"), sdk_name, ctx.attrs.extension, ctx.attrs.versioned_macos_bundle),+ ]++ command = cmd_args(+ [+ tool,+ "--output",+ bundle.as_output(),+ "--spec",+ spec_file,+ ]+ + codesign_execution_args+ + codesign_bundle_extra_args+ + platform_args+ + swift_args+ + extra_context_args+ + signing_context_path_arg,+ hidden = [part.source for part in all_parts]+ + [part.codesign_entitlements for part in all_parts if part.codesign_entitlements]+ ++ # Ensures any genrule deps get built, such targets are used for validation+ extra_hidden,+ )+ run_incremental_args = {}+ incremental_state = ctx.actions.declare_output("incremental_state.json", has_content_based_path = False).as_output()++ # Fallback to value from buckconfig+ incremental_bundling_enabled = ctx.attrs.incremental_bundling_enabled or ctx.attrs._incremental_bundling_enabled+ if incremental_bundling_override != None:+ incremental_bundling_enabled = incremental_bundling_override++ if incremental_bundling_enabled:+ command.add("--incremental-state", incremental_state)+ run_incremental_args = {+ "metadata_env_var": "ACTION_METADATA",+ "metadata_path": "action_metadata.json",+ "no_outputs_cleanup": True,+ }+ category = "apple_assemble_bundle_incremental"+ else:+ # overwrite file with incremental state so if previous and next builds are incremental+ # (as opposed to the current non-incremental one), next one won't assume there is a+ # valid incremental state.+ command.add(cmd_args(hidden = ctx.actions.write_json(incremental_state, {})))+ category = "apple_assemble_bundle"++ if ctx.attrs._profile_bundling_enabled:+ profile_output = ctx.actions.declare_output("bundling_profile.txt", has_content_based_path = False).as_output()+ command.add("--profile-output", profile_output)++ subtargets = {}+ if resolution_log_output:+ subtargets["signing-context-resolution-log"] = [DefaultInfo(default_output = resolution_log_output)]+ bundling_log_args, bundling_log_output = _bundling_log_args(ctx, "bundling_log.txt")+ command.add(bundling_log_args)+ if bundling_log_output:+ subtargets["bundling-log"] = [DefaultInfo(default_output = bundling_log_output)]++ command.add("--check-conflicts")+ if ctx.attrs.versioned_macos_bundle:+ command.add("--versioned-if-macos")+ if getattr(ctx.attrs, "include_build_info_file", False):+ extension_allowed = ctx.attrs.extension in ctx.attrs.include_build_info_file_in_bundles_with_extensions+ if extension_allowed:+ command.add("--include-build-info-file")+ command.add(codesign_configuration_args)++ bundle_telemetry_logger = tools.bundle_telemetry_logger+ if bundle_telemetry_logger:+ command.add("--bundle-telemetry-logger", bundle_telemetry_logger)++ ctx.actions.run(+ command,+ local_only = force_local_bundling,+ prefer_local = not force_local_bundling,+ category = category,+ env = env,+ error_handler = apple_build_error_handler,+ **run_incremental_args,+ )++ command_json = ctx.actions.declare_output("bundling_command.json", has_content_based_path = False)+ command_json_cmd_args = ctx.actions.write_json(command_json, command, with_inputs = True, pretty = True)+ subtargets["command"] = [DefaultInfo(default_output = command_json, other_outputs = [command_json_cmd_args])]++ bundle_manifest_log_file_map = {+ ctx.label: AppleBundleManifestLogFiles(+ command_file = command_json,+ spec_file = spec_file,+ log_file = bundling_log_output,+ ),+ }++ if hasattr(ctx.attrs, "deps"):+ for dep in ctx.attrs.deps:+ dep_manifest_info = dep.get(AppleBundleManifestInfo)+ if dep_manifest_info:+ bundle_manifest_log_file_map.update(dep_manifest_info.manifest.log_file_map)++ bundle_manifest = AppleBundleManifest(log_file_map = bundle_manifest_log_file_map)+ bundle_manifest_json_object = _convert_bundle_manifest_to_json_object(bundle_manifest)++ bundle_manifest_json_file = ctx.actions.declare_output("bundle_manifest.json", has_content_based_path = False)+ bundle_manifest_cmd_args = ctx.actions.write_json(bundle_manifest_json_file, bundle_manifest_json_object, with_inputs = True, pretty = True)+ subtargets["manifest"] = [DefaultInfo(default_output = bundle_manifest_json_file, other_outputs = [bundle_manifest_cmd_args])]++ providers = [AppleBundleManifestInfo(manifest = bundle_manifest)]++ codesign_manifest_tree = _make_codesign_manifest_tree(ctx, codesign_manifest, codesign_manifest_parts)+ codesign_manifest_tree_json = _get_codesign_manifest_tree_as_json(codesign_manifest_tree)+ codesign_manifest_tree_json_file = ctx.actions.declare_output("codesign_manifest_tree.json", has_content_based_path = False)+ codesign_manifest_tree_json_cmd_args = ctx.actions.write_json(+ codesign_manifest_tree_json_file,+ codesign_manifest_tree_json,+ with_inputs = True,+ pretty = True,+ )++ tools = ctx.attrs._apple_tools[AppleToolsInfo]+ manifest_tree_postprocessor = tools.codesign_manifest_tree_postprocessor++ postprocessed_codesign_manifest_tree = ctx.actions.declare_output("postprocessed_codesign_manifest_tree.json", has_content_based_path = False)+ ctx.actions.run(+ cmd_args(+ [+ manifest_tree_postprocessor,+ "--codesign-manifest-tree",+ codesign_manifest_tree_json_cmd_args,+ "--output",+ postprocessed_codesign_manifest_tree.as_output(),+ ],+ ),+ category = "codesign_manifest_tree_postprocess",+ )++ subtargets["codesign-manifest"] = [+ DefaultInfo(+ default_output = postprocessed_codesign_manifest_tree,+ ),+ ]++ signing_context_output = ctx.actions.declare_output("provisioning-manifest.json", has_content_based_path = False)+ ctx.actions.run(+ cmd_args(+ [+ tools.provisioning_manifest,+ "--output",+ signing_context_output.as_output(),+ ]+ + signing_context_path_arg,+ ),+ category = "apple_provisioning_manifest",+ error_handler = apple_build_error_handler,+ )++ signing_context_tree = _make_signing_context_tree(ctx, signing_context_output, signing_context_parts)+ signing_context_tree_json = _get_signing_context_tree_as_json(signing_context_tree)+ signing_context_tree_json_file = ctx.actions.declare_output("provisioning-manifest-tree.json", has_content_based_path = False)+ signing_context_tree_json_cmd_args = ctx.actions.write_json(+ signing_context_tree_json_file,+ signing_context_tree_json,+ with_inputs = True,+ pretty = True,+ )++ postprocessed_signing_context_tree = ctx.actions.declare_output("postprocessed-provisioning-manifest-tree.json", has_content_based_path = False)+ ctx.actions.run(+ cmd_args(+ [+ tools.signing_context_tree_postprocessor,+ "--signing-context-tree",+ signing_context_tree_json_cmd_args,+ "--output",+ postprocessed_signing_context_tree.as_output(),+ ],+ ),+ category = "apple_provisioning_manifest_tree_postprocess",+ )++ subtargets["provisioning-manifest"] = [DefaultInfo(default_output = postprocessed_signing_context_tree)]+ subtargets["signing-info"] = [DefaultInfo(default_output = signing_info_output)]++ return AppleBundleConstructionResult(+ sub_targets = subtargets,+ providers = providers,+ codesign_manifest_tree = codesign_manifest_tree,+ signing_context_tree = signing_context_tree,+ signing_info = signing_info_output,+ )++def _make_codesign_manifest_tree(+ ctx: AnalysisContext, codesign_manifest: Artifact, inner_parts: list[AppleBundleCodesignManifestTreePart]+) -> AppleBundleCodesignManifestTree:+ inner_manifest_trees = {}++ for codesign_manifest_tree_part in inner_parts:+ relative_path = get_apple_bundle_part_relative_destination_path(ctx, codesign_manifest_tree_part.bundle_part)+ inner_manifest_trees[relative_path] = codesign_manifest_tree_part.codesign_manifest_tree++ return AppleBundleCodesignManifestTree(+ codesign_manifest = codesign_manifest,+ inner_codesign_manifests = inner_manifest_trees,+ )++def _get_codesign_manifest_tree_as_json(codesign_manifest_tree: AppleBundleCodesignManifestTree) -> dict[str, typing.Any]:+ json_obj = {+ "codesign_manifest": codesign_manifest_tree.codesign_manifest,+ }++ inner_manifests = {}+ for relative_path, inner_codesign_manifest_tree in codesign_manifest_tree.inner_codesign_manifests.items():+ inner_manifests[relative_path] = _get_codesign_manifest_tree_as_json(inner_codesign_manifest_tree)++ json_obj["inner_codesign_manifests"] = inner_manifests+ return json_obj++def _make_signing_context_tree(+ ctx: AnalysisContext, signing_context: Artifact, inner_parts: list[AppleBundleSigningContextTreePart]+) -> AppleBundleSigningContextTree:+ inner_context_trees = {}++ for signing_context_tree_part in inner_parts:+ relative_path = get_apple_bundle_part_relative_destination_path(ctx, signing_context_tree_part.bundle_part)+ inner_context_trees[relative_path] = signing_context_tree_part.signing_context_tree++ return AppleBundleSigningContextTree(+ signing_context = signing_context,+ inner_signing_contexts = inner_context_trees,+ )++def _get_signing_context_tree_as_json(signing_context_tree: AppleBundleSigningContextTree) -> dict[str, typing.Any]:+ json_obj = {+ "signing_context": signing_context_tree.signing_context,+ }++ inner_contexts = {}+ for relative_path, inner_signing_context_tree in signing_context_tree.inner_signing_contexts.items():+ inner_contexts[relative_path] = _get_signing_context_tree_as_json(inner_signing_context_tree)++ json_obj["inner_signing_contexts"] = inner_contexts+ return json_obj++def get_bundle_dir_name(ctx: AnalysisContext) -> str:+ return paths.replace_extension(get_product_name(ctx), "." + get_extension_attr(ctx))++def get_apple_bundle_part_relative_destination_path(ctx: AnalysisContext, part: AppleBundlePart) -> str:+ bundle_relative_path = bundle_relative_path_for_destination(+ part.destination, get_apple_sdk_name(ctx), ctx.attrs.extension, ctx.attrs.versioned_macos_bundle+ )+ destination_file_or_directory_name = part.new_name if part.new_name != None else part.source.basename+ return paths.join(bundle_relative_path, destination_file_or_directory_name)++# Returns JSON to be passed into bundle assembling tool. It should contain a dictionary which maps bundle relative destination paths to source paths."+def _bundle_spec_json(ctx: AnalysisContext, parts: list[AppleBundlePart], codesign_type: CodeSignType) -> Artifact:+ specs = []+ include_entitlements = should_include_entitlements(ctx, codesign_type)++ for part in parts:+ part_spec = {+ "dst": get_apple_bundle_part_relative_destination_path(ctx, part),+ "src": part.source,+ }+ if part.codesign_on_copy:+ part_spec["codesign_on_copy"] = True+ if include_entitlements and part.codesign_entitlements:+ part_spec["codesign_entitlements"] = part.codesign_entitlements+ if part.codesign_flags_override:+ part_spec["codesign_flags_override"] = part.codesign_flags_override+ if part.extra_codesign_paths:+ part_spec["extra_codesign_paths"] = part.extra_codesign_paths+ specs.append(part_spec)++ return ctx.actions.write_json("bundle_spec.json", specs, pretty = True, has_content_based_path = False)++def _get_codesign_type_from_attribs(ctx: AnalysisContext) -> [CodeSignType, None]:+ # Target-level attribute takes highest priority+ if ctx.attrs.codesign_type:+ return CodeSignType(ctx.attrs.codesign_type)++ # Config-based global default+ if ctx.attrs._codesign_type:+ return CodeSignType(ctx.attrs._codesign_type)+ return None++def _detect_codesign_type(ctx: AnalysisContext, skip_adhoc_signing: bool) -> CodeSignType:+ def compute_codesign_type():+ if ctx.attrs.extension not in ["app", "appex", "xctest", "driver"]:+ # Only code sign application bundles, extensions and test bundles+ return CodeSignType("skip")++ codesign_type_attrib = _get_codesign_type_from_attribs(ctx)+ if codesign_type_attrib != None:+ return codesign_type_attrib++ sdk_name = get_apple_sdk_name(ctx)+ is_ad_hoc_sufficient = get_apple_sdk_metadata_for_sdk_name(sdk_name).is_ad_hoc_code_sign_sufficient+ return CodeSignType("adhoc" if is_ad_hoc_sufficient else "distribution")++ codesign_type = compute_codesign_type()+ if skip_adhoc_signing and codesign_type == CodeSignType("adhoc"):+ codesign_type = CodeSignType("skip")++ return codesign_type++def _get_extra_codesign_args(ctx: AnalysisContext) -> list[str]:+ codesign_args = ctx.attrs.codesign_flags if hasattr(ctx.attrs, "codesign_flags") else []+ return ["--codesign-args={}".format(flag) for flag in codesign_args]++def _should_embed_provisioning_profile(ctx: AnalysisContext, codesign_type: CodeSignType) -> bool:+ if codesign_type == CodeSignType("distribution"):+ return True++ if codesign_type == CodeSignType("adhoc"):+ # The config-based override value takes priority over target value+ if ctx.attrs._embed_provisioning_profile_when_adhoc_code_signing != None:+ return ctx.attrs._embed_provisioning_profile_when_adhoc_code_signing+ return ctx.attrs.embed_provisioning_profile_when_adhoc_code_signing++ return False++def _convert_bundle_manifest_to_json_object(manifest: AppleBundleManifest) -> dict[Label, typing.Any]:+ manifest_dict = {}+ for target_label, logs in manifest.log_file_map.items():+ manifest_dict[target_label] = {+ "command": logs.command_file,+ "log": logs.log_file,+ "spec": logs.spec_file,+ }+ return manifest_dict++def _get_fast_adhoc_signing_enabled(ctx: AnalysisContext) -> bool:+ fast_adhoc_signing_enabled = ctx.attrs.fast_adhoc_signing_enabled+ if fast_adhoc_signing_enabled != None:+ return fast_adhoc_signing_enabled+ return ctx.attrs._fast_adhoc_signing_enabled_default
@@ -0,0 +1,635 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:artifacts.bzl", "single_artifact")+load("@prelude//:paths.bzl", "paths")+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")+load("@prelude//cxx:headers.bzl", "CHeader")+load(+ "@prelude//linking:link_info.bzl",+ "CxxSanitizerRuntimeInfo",+)+load("@prelude//utils:utils.bzl", "flatten_dict")+load(+ ":apple_asset_catalog.bzl",+ "compile_apple_asset_catalog",+)+load(":apple_bundle_destination.bzl", "AppleBundleDestination")+load(":apple_bundle_part.bzl", "AppleBundleCodesignManifestTreePart", "AppleBundlePart", "AppleBundleSigningContextTreePart")+load(+ ":apple_bundle_types.bzl",+ "AppleBundleInfo",+ "AppleBundleTypeAppClip",+ "AppleBundleTypeDefault",+ "AppleBundleTypeExtensionKitExtension",+ "AppleBundleTypeWatchApp",+)+load(+ ":apple_bundle_utility.bzl",+ "get_bundle_resource_processing_options",+ "get_default_binary_dep",+ "get_extension_attr",+ "get_flattened_binary_deps",+ "get_is_watch_bundle",+ "get_product_name",+)+load(":apple_core_data.bzl", "compile_apple_core_data")+load(":apple_info_plist.bzl", "process_info_plist", "process_plist")+load(":apple_library.bzl", "AppleLibraryForDistributionInfo")+load(":apple_library_types.bzl", "AppleLibraryInfo")+load(+ ":apple_resource_types.bzl",+ "AppleResourceDestination",+ "AppleResourceSelectionOutput",+ "AppleResourceSpec", # @unused Used as a type+)+load(":apple_resource_utility.bzl", "apple_bundle_destination_from_resource_destination")+load(":modulemap.bzl", "create_modulemap")+load(+ ":resource_groups.bzl",+ "create_resource_graph",+ "get_filtered_resources",+ "get_resource_graph_node_map_func",+ "get_resource_group_info",+)+load(":scene_kit_assets.bzl", "compile_scene_kit_assets")++AppleBundleResourcePartListOutput = record(+ # Resource parts to be copied into an Apple bundle, *excluding* binaries+ resource_parts = field(list[AppleBundlePart]),+ # Part that holds the info.plist+ info_plist_part = field(AppleBundlePart),+ # Parts which have an associated codesign manifest, it would contain+ # a _subset_ of the `resource_parts` parts.+ codesign_manifest_parts = field(list[AppleBundleCodesignManifestTreePart]),+ # Parts which have an associated signing context, it would contain+ # a _subset_ of the `resource_parts` parts.+ signing_context_parts = field(list[AppleBundleSigningContextTreePart]),+)++def get_apple_bundle_resource_part_list(ctx: AnalysisContext) -> AppleBundleResourcePartListOutput:+ parts = []++ parts.extend(_create_pkg_info_if_needed(ctx))+ parts.extend(_copy_privacy_manifest_if_needed(ctx))++ selection = _select_resources(ctx)++ # If we've pulled in native/C++ resources from deps, inline them into the+ # bundle under the `CxxResources` namespace.+ cxx_resources = flatten_dict([s.resources for s in selection.cxx_resource_specs])+ if cxx_resources:+ cxx_res_dir = ctx.actions.copied_dir(+ "CxxResources",+ {name: resource.default_output for name, resource in cxx_resources.items()},+ has_content_based_path = False,+ )+ selection.resource_specs.append(+ AppleResourceSpec(+ dirs = [cxx_res_dir],+ destination = AppleResourceDestination("resources"),+ ),+ )++ cxx_sanitizer_runtime_info = get_default_binary_dep(ctx.attrs.binary).get(CxxSanitizerRuntimeInfo) if ctx.attrs.binary else None+ if cxx_sanitizer_runtime_info and get_extension_attr(ctx) != "appex":+ runtime_resource_spec = AppleResourceSpec(+ files = cxx_sanitizer_runtime_info.runtime_files,+ destination = AppleResourceDestination("frameworks"),+ # Sanitizer dylibs require signing, for hardened runtime on macOS and iOS device builds+ codesign_files_on_copy = True,+ )+ selection.resource_specs.append(runtime_resource_spec)++ asset_catalog_result = compile_apple_asset_catalog(ctx, selection.asset_catalog_specs)+ if asset_catalog_result != None:+ asset_catalog_part = AppleBundlePart(+ source = asset_catalog_result.compiled_catalog,+ destination = AppleBundleDestination("resources"),+ # We only interested in directory contents+ new_name = "",+ )+ parts.append(asset_catalog_part)++ extra_plist = asset_catalog_result.catalog_plist if asset_catalog_result != None else None+ info_plist_part = process_info_plist(ctx = ctx, override_input = extra_plist)++ core_data_result = compile_apple_core_data(ctx, selection.core_data_specs, get_product_name(ctx))+ if core_data_result != None:+ core_data_part = AppleBundlePart(+ source = core_data_result,+ destination = AppleBundleDestination("resources"),+ # We only interested in directory contents+ new_name = "",+ )+ parts.append(core_data_part)++ scene_kit_assets_result = compile_scene_kit_assets(ctx, selection.scene_kit_assets_spec)+ if scene_kit_assets_result != None:+ scene_kit_assets_part = AppleBundlePart(+ source = scene_kit_assets_result,+ destination = AppleBundleDestination("resources"),+ # We only interested in directory contents+ new_name = "",+ )+ parts.append(scene_kit_assets_part)++ parts.extend(_copy_resources(ctx, selection.resource_specs))+ first_level_parts, first_level_codesign_manifest_parts, first_level_signing_context_parts = _copy_first_level_bundles(ctx)+ parts.extend(first_level_parts)+ parts.extend(_copy_public_headers(ctx))+ parts.extend(_copy_module_map(ctx))+ parts.extend(_copy_swift_library_evolution_support(ctx))++ return AppleBundleResourcePartListOutput(+ resource_parts = parts,+ info_plist_part = info_plist_part,+ codesign_manifest_parts = first_level_codesign_manifest_parts,+ signing_context_parts = first_level_signing_context_parts,+ )++# Same logic as in v1, see `buck_client/src/com/facebook/buck/apple/ApplePkgInfo.java`+def _create_pkg_info_if_needed(ctx: AnalysisContext) -> list[AppleBundlePart]:+ extension = get_extension_attr(ctx)+ if extension == "xpc" or extension == "qlgenerator":+ return []+ artifact = ctx.actions.write("PkgInfo", "APPLWRUN\n", has_content_based_path = False)+ return [AppleBundlePart(source = artifact, destination = AppleBundleDestination("metadata"))]++def _copy_privacy_manifest_if_needed(ctx: AnalysisContext) -> list[AppleBundlePart]:+ privacy_manifest = ctx.attrs.privacy_manifest+ if privacy_manifest == None:+ return []++ # According to apple docs, privacy manifest has to be named as `PrivacyInfo.xcprivacy`+ if privacy_manifest.short_path.split("/", 1)[-1] == "PrivacyInfo.xcprivacy":+ artifact = privacy_manifest+ else:+ output = ctx.actions.declare_output("PrivacyInfo.xcprivacy", has_content_based_path = False)+ artifact = ctx.actions.copy_file(output.as_output(), privacy_manifest)+ return [AppleBundlePart(source = artifact, destination = AppleBundleDestination("resources"))]++def _select_resources(ctx: AnalysisContext) -> AppleResourceSelectionOutput:+ resource_group_info = get_resource_group_info(ctx)+ if resource_group_info:+ resource_groups_deps = resource_group_info.resource_group_to_implicit_deps_mapping.get(ctx.attrs.resource_group, []) if ctx.attrs.resource_group else []+ resource_group_mappings = resource_group_info.mappings+ else:+ resource_groups_deps = []+ resource_group_mappings = {}++ resource_graph = create_resource_graph(+ ctx = ctx,+ labels = [],+ bundle_binary = get_default_binary_dep(ctx.attrs.binary),+ deps = ctx.attrs.deps + resource_groups_deps,+ exported_deps = [],+ )+ resource_graph_node_map_func = get_resource_graph_node_map_func(resource_graph)+ return get_filtered_resources(ctx.label, resource_graph_node_map_func, ctx.attrs.resource_group, resource_group_mappings)++def _copy_swift_library_evolution_support(ctx: AnalysisContext) -> list[AppleBundlePart]:+ extension = get_extension_attr(ctx)+ if not extension == "framework":+ return []++ binary_deps = getattr(ctx.attrs, "binary")+ if binary_deps == None:+ return []++ swiftmodule_files = {}++ module_name = None+ for binary in get_flattened_binary_deps(binary_deps):+ apple_library_for_distribution_info = binary.get(AppleLibraryForDistributionInfo)+ if apple_library_for_distribution_info == None:+ continue+ module_name = apple_library_for_distribution_info.module_name+ if apple_library_for_distribution_info.swiftinterface != None:+ swiftmodule_files.update({+ apple_library_for_distribution_info.target_triple + ".swiftinterface": apple_library_for_distribution_info.swiftinterface,+ })+ if not getattr(ctx.attrs, "skip_private_swiftinterface", False):+ swiftmodule_files.update({+ apple_library_for_distribution_info.target_triple+ + ".private.swiftinterface": apple_library_for_distribution_info.private_swiftinterface,+ })+ if apple_library_for_distribution_info.swiftdoc != None:+ swiftmodule_files.update({+ apple_library_for_distribution_info.target_triple + ".swiftdoc": apple_library_for_distribution_info.swiftdoc,+ })++ if len(swiftmodule_files) == 0 or module_name == None:+ return []++ framework_module_dir = ctx.actions.declare_output(module_name + "framework.swiftmodule", dir = True, has_content_based_path = False)+ ctx.actions.copied_dir(framework_module_dir.as_output(), swiftmodule_files)+ return [AppleBundlePart(source = framework_module_dir, destination = AppleBundleDestination("modules"), new_name = module_name + ".swiftmodule")]++def _public_headers(ctx: AnalysisContext) -> list[Artifact]:+ if not ctx.attrs.copy_public_framework_headers:+ return []+ binary_deps = getattr(ctx.attrs, "binary")+ if binary_deps == None:+ return []++ binary = get_default_binary_dep(binary_deps)+ apple_library_info = binary.get(AppleLibraryInfo)+ if apple_library_info == None:+ return []+ tset = apple_library_info.public_framework_headers++ headers = []+ if tset._tset:+ for public_framework_headers in tset._tset.traverse():+ for public_framework_header in public_framework_headers:+ for artifact in public_framework_header.artifacts:+ headers.append(artifact)++ return headers++def _copy_public_headers(ctx: AnalysisContext) -> list[AppleBundlePart]:+ if not ctx.attrs.copy_public_framework_headers:+ return []+ binary_deps = getattr(ctx.attrs, "binary")+ if binary_deps == None:+ return []++ binary = get_default_binary_dep(binary_deps)+ apple_library_info = binary.get(AppleLibraryInfo)+ if apple_library_info == None:+ return []+ tset = apple_library_info.public_framework_headers++ bundle_parts = []+ if tset._tset:+ for public_framework_headers in tset._tset.traverse():+ for public_framework_header in public_framework_headers:+ for artifact in public_framework_header.artifacts:+ bundle_parts.append(AppleBundlePart(source = artifact, destination = AppleBundleDestination("headers")))++ if apple_library_info.swift_header:+ bundle_parts.append(AppleBundlePart(source = apple_library_info.swift_header, destination = AppleBundleDestination("headers")))++ return bundle_parts++def _create_framework_module_map(ctx: AnalysisContext) -> Artifact:+ binary = get_default_binary_dep(ctx.attrs.binary)+ apple_library_for_distribution_info = binary.get(AppleLibraryForDistributionInfo)+ if apple_library_for_distribution_info == None:+ fail("Tried to generate an automatic modulemap for an unsupported binary dep. Please make sure it is a modular apple_library")+ headers = _public_headers(ctx)+ cheaders = []+ for header in headers:+ cheaders.append(+ CHeader(+ artifact = header,+ name = header.basename,+ namespace = "",+ named = False,+ )+ )++ module_name = apple_library_for_distribution_info.module_name+ preprocessor_info = create_modulemap(+ ctx,+ name = "module",+ module_name = module_name,+ headers = cheaders,+ is_framework = True,+ )+ return preprocessor_info.modulemap_artifact++def _copy_module_map(ctx: AnalysisContext) -> list[AppleBundlePart]:+ extension = get_extension_attr(ctx)+ if not extension == "framework":+ return []+ module_map = ctx.attrs.module_map+ if module_map == None:+ return []+ if module_map == "auto":+ module_map = _create_framework_module_map(ctx)++ return [AppleBundlePart(source = module_map, destination = AppleBundleDestination("modules"))]++def _copy_resources(ctx: AnalysisContext, specs: list[AppleResourceSpec]) -> list[AppleBundlePart]:+ result = []++ for spec in specs:+ bundle_destination = apple_bundle_destination_from_resource_destination(spec.destination)+ result += [+ _process_apple_resource_file_if_needed(+ ctx = ctx,+ file = single_artifact(x).default_output,+ destination = bundle_destination,+ destination_relative_path = None,+ codesign_on_copy = spec.codesign_files_on_copy,+ codesign_entitlements = spec.codesign_entitlements,+ codesign_flags_override = spec.codesign_flags_override,+ )+ for x in spec.files+ ]+ result += _bundle_parts_for_dirs(spec.dirs, bundle_destination, False)+ result += _bundle_parts_for_dirs(spec.content_dirs, bundle_destination, True)+ result += _bundle_parts_for_variant_files(ctx, spec)++ return result++def _copy_first_level_bundles(+ ctx: AnalysisContext,+) -> (list[AppleBundlePart], list[AppleBundleCodesignManifestTreePart], list[AppleBundleSigningContextTreePart]):+ first_level_bundle_infos = filter(None, [dep.get(AppleBundleInfo) for dep in ctx.attrs.deps])++ bundle_parts = []+ codesign_manifest_parts = []+ signing_context_parts = []+ for bundle_info in first_level_bundle_infos:+ first_level_part = _copied_bundle_spec(bundle_info)+ if first_level_part != None:+ bundle_parts.append(first_level_part)+ if bundle_info.codesign_manifest_tree:+ codesign_manifest_parts.append(+ AppleBundleCodesignManifestTreePart(+ bundle_part = first_level_part,+ codesign_manifest_tree = bundle_info.codesign_manifest_tree,+ )+ )+ if bundle_info.signing_context_tree:+ signing_context_parts.append(+ AppleBundleSigningContextTreePart(+ bundle_part = first_level_part,+ signing_context_tree = bundle_info.signing_context_tree,+ )+ )++ return bundle_parts, codesign_manifest_parts, signing_context_parts++def _copied_bundle_spec(bundle_info: AppleBundleInfo) -> [None, AppleBundlePart]:+ bundle = bundle_info.bundle+ bundle_extension = paths.split_extension(bundle.short_path)[1]+ if bundle_extension == ".framework":+ destination = AppleBundleDestination("frameworks")+ codesign_on_copy = True+ elif bundle_extension == ".app":+ app_destination_type = "plugins"+ if bundle_info.bundle_type == AppleBundleTypeWatchApp:+ app_destination_type = "watchapp"+ elif bundle_info.bundle_type == AppleBundleTypeAppClip:+ app_destination_type = "appclips"+ elif bundle_info.bundle_type != AppleBundleTypeDefault:+ fail("Unhandled bundle type `{}`".format(bundle_info.bundle_type))+ destination = AppleBundleDestination(app_destination_type)+ codesign_on_copy = False+ elif bundle_extension == ".appex":+ # We have two types of extensions: App Extensions and ExtensionKit Extensions+ #+ # +----------------------+-------------------------------+-------------------------------++ # | | App Extension | ExtensionKit Extension |+ # +----------------------+-------------------------------+-------------------------------++ # | xcode project type | com.apple.product-type.app- | com.apple.product-type. |+ # | | extension | extensionkit-extension |+ # +----------------------+-------------------------------+-------------------------------++ # | Info.plist | NSExtensions | EXAppExtensionAttributes |+ # +----------------------+-------------------------------+-------------------------------++ # | bundle folder | *.app/PlugIns | *.app/Extensions |+ # +----------------------+-------------------------------+-------------------------------++ #+ if bundle_info.bundle_type == AppleBundleTypeExtensionKitExtension:+ destination = AppleBundleDestination("extensionkit_extensions")+ else:+ destination = AppleBundleDestination("plugins")+ codesign_on_copy = False+ elif bundle_extension == ".qlgenerator":+ destination = AppleBundleDestination("quicklook")+ codesign_on_copy = True+ elif bundle_extension == ".xpc":+ destination = AppleBundleDestination("xpcservices")+ codesign_on_copy = True+ elif bundle_extension == ".bundle":+ destination = AppleBundleDestination("plugins")+ codesign_on_copy = True+ else:+ fail("Extension `{}` is not yet supported.".format(bundle_extension))+ return AppleBundlePart(+ source = bundle,+ destination = destination,+ codesign_on_copy = codesign_on_copy,+ extra_codesign_paths = bundle_info.extra_codesign_paths,+ )++def _bundle_parts_for_dirs(generated_dirs: list[Artifact], destination: AppleBundleDestination, copy_contents_only: bool) -> list[AppleBundlePart]:+ return [+ AppleBundlePart(+ source = generated_dir,+ destination = destination,+ new_name = "" if copy_contents_only else None,+ )+ for generated_dir in generated_dirs+ ]++def _bundle_parts_for_variant_files(ctx: AnalysisContext, spec: AppleResourceSpec) -> list[AppleBundlePart]:+ result = []++ # By definition, all variant files go into the resources destination+ bundle_destination = AppleBundleDestination("resources")+ for variant_file in spec.variant_files:+ variant_dest_subpath = _get_dest_subpath_for_variant_file(variant_file)+ bundle_part = _process_apple_resource_file_if_needed(+ ctx = ctx,+ file = variant_file,+ destination = bundle_destination,+ destination_relative_path = variant_dest_subpath,+ )+ result.append(bundle_part)++ for locale, variant_files in spec.named_variant_files.items():+ if not locale.endswith(".lproj"):+ fail("Keys for named variant files have to end with '.lproj' suffix, got {}".format(locale))+ result += [+ _process_apple_resource_file_if_needed(+ ctx = ctx,+ file = variant_file,+ destination = bundle_destination,+ destination_relative_path = paths.join(locale, variant_file.basename),+ )+ for variant_file in variant_files+ ]++ return result++def _run_ibtool(+ ctx: AnalysisContext,+ raw_file: Artifact,+ output: OutputArtifact,+ action_flags: list[str],+ target_device: [None, str],+ command_for_identifier: str,+ output_is_dir: bool,+) -> None:+ # TODO(T110378103): detect and add minimum deployment target automatically+ # TODO(T110378113): add support for ibtool modules (turned on by `ibtool_module_flag` field of `apple_bundle` rule)++ # Equivalent of `AppleProcessResources::BASE_IBTOOL_FLAGS` from v1+ base_flags = ["--output-format", "human-readable-text", "--notices", "--warnings", "--errors"]+ ibtool = ctx.attrs._apple_toolchain[AppleToolchainInfo].ibtool+ ibtool_flags = getattr(ctx.attrs, "ibtool_flags", None) or []+ ibtool_command = [ibtool] + base_flags + ibtool_flags+ if target_device != None:+ ibtool_command.extend(["--target-device", target_device])+ ibtool_command.extend(action_flags)+ if output_is_dir:+ ibtool_command.append('"$TMPDIR"')+ copy_back = cmd_args(output, format = 'mkdir -p {} && cp -r "$TMPDIR"/ {}')+ else:+ output_for_tool_invocation = '"$TMPDIR"/"' + output.basename + '"'+ ibtool_command.append(output_for_tool_invocation)+ copy_back = cmd_args(output, format = "cp " + output_for_tool_invocation + " {}")+ ibtool_command.append(cmd_args(raw_file, format = '"$EXEC_ROOT"/{}'))++ # Sandboxing and fs isolation on RE machines results in Xcode tools failing+ # when those are working in freshly created directories in buck-out.+ # See https://fb.workplace.com/groups/1042353022615812/permalink/1872164996301273/+ # As a workaround create a directory in tmp, use it for Xcode tools, then+ # copy the result to buck-out.+ script_lines = [+ cmd_args("set -euo pipefail"),+ cmd_args('EXEC_ROOT="$PWD"'),+ cmd_args('TMPDIR="$(mktemp -d)"'),+ cmd_args(ibtool_command, delimiter = " "),+ copy_back,+ ]++ wrapper_script, _ = ctx.actions.write(+ "ibtool_wrapper_" + _wrapper_suffix(command_for_identifier, raw_file) + ".sh",+ script_lines,+ allow_args = True,+ has_content_based_path = False,+ )+ command = cmd_args(["/bin/sh", wrapper_script], hidden = [ibtool_command, output])+ action_identifier = _ibtool_identifier(command_for_identifier, raw_file)+ processing_options = get_bundle_resource_processing_options(ctx)+ ctx.actions.run(+ command,+ prefer_local = processing_options.prefer_local,+ prefer_remote = processing_options.prefer_remote,+ allow_cache_upload = processing_options.allow_cache_upload,+ category = "apple_ibtool",+ identifier = action_identifier,+ )++def _identifier_parts(raw_file: Artifact) -> list[str]:+ identifier_parts = []+ variant_dirname = _get_variant_dirname(raw_file)+ if variant_dirname:+ # variant_name is like "zh_TW.lproj", and we only want "zh_TW"+ variant_name = paths.replace_extension(variant_dirname, "")+ identifier_parts.append(variant_name)+ identifier_parts += [raw_file.basename]+ return identifier_parts++def _ibtool_identifier(action: str, raw_file: Artifact) -> str:+ "*.xib files can live in .lproj folders and have the same name, so we need to split the id"+ identifier_parts = _identifier_parts(raw_file)+ return "ibtool_" + action + " " + "/".join(identifier_parts)++def _wrapper_suffix(action: str, raw_file: Artifact) -> str:+ return "_".join([action] + _identifier_parts(raw_file))++def _compile_ui_resource(+ ctx: AnalysisContext, raw_file: Artifact, output: OutputArtifact, target_device: [None, str] = None, output_is_dir: bool = False+) -> None:+ _run_ibtool(+ ctx = ctx,+ raw_file = raw_file,+ output = output,+ action_flags = ["--compile"],+ target_device = target_device,+ command_for_identifier = "compile",+ output_is_dir = output_is_dir,+ )++def _link_ui_resource(ctx: AnalysisContext, raw_file: Artifact, output: OutputArtifact, target_device: [None, str] = None, output_is_dir: bool = False) -> None:+ _run_ibtool(+ ctx = ctx,+ raw_file = raw_file,+ output = output,+ action_flags = ["--link"],+ target_device = target_device,+ command_for_identifier = "link",+ output_is_dir = output_is_dir,+ )++def _process_apple_resource_file_if_needed(+ ctx: AnalysisContext,+ file: Artifact,+ destination: AppleBundleDestination,+ destination_relative_path: [str, None],+ codesign_on_copy: bool = False,+ codesign_entitlements: Artifact | None = None,+ codesign_flags_override: list[str] | None = None,+) -> AppleBundlePart:+ output_dir = "_ProcessedResources"+ basename = file.basename+ output_is_contents_dir = False+ if basename.endswith(".plist") or basename.endswith(".stringsdict"):+ processed = ctx.actions.declare_output(paths.join(output_dir, file.short_path), has_content_based_path = False)+ process_plist(+ ctx = ctx,+ input = file,+ output = processed.as_output(),+ action_id = destination_relative_path,+ )+ elif basename.endswith(".storyboard"):+ if destination_relative_path:+ destination_relative_path = paths.replace_extension(destination_relative_path, ".storyboardc")+ compiled = ctx.actions.declare_output(+ paths.join(output_dir, paths.replace_extension(file.short_path, ".storyboardc")), dir = True, has_content_based_path = False+ )+ if get_is_watch_bundle(ctx):+ output_is_contents_dir = True+ _compile_ui_resource(ctx = ctx, raw_file = file, output = compiled.as_output(), target_device = "watch", output_is_dir = True)+ processed = ctx.actions.declare_output(+ paths.join(output_dir, paths.replace_extension(file.short_path, "_linked_storyboard")), dir = True, has_content_based_path = False+ )+ _link_ui_resource(ctx = ctx, raw_file = compiled, output = processed.as_output(), target_device = "watch", output_is_dir = True)+ else:+ processed = compiled+ _compile_ui_resource(ctx, file, processed.as_output(), output_is_dir = True)+ elif basename.endswith(".xib"):+ if destination_relative_path:+ destination_relative_path = paths.replace_extension(destination_relative_path, ".nib")+ processed = ctx.actions.declare_output(paths.join(output_dir, paths.replace_extension(file.short_path, ".nib")), has_content_based_path = False)+ _compile_ui_resource(ctx, file, processed.as_output())+ else:+ processed = file++ # When name is empty string only content of the directory will be copied, as opposed to the directory itself.+ # When name is `None`, directory or file will be copied as it is, without renaming.+ new_name = destination_relative_path if destination_relative_path else ("" if output_is_contents_dir else None)+ return AppleBundlePart(+ source = processed,+ destination = destination,+ new_name = new_name,+ codesign_on_copy = codesign_on_copy,+ codesign_entitlements = codesign_entitlements,+ codesign_flags_override = codesign_flags_override,+ )++# Returns a path relative to the _parent_ of the lproj dir.+# For example, given a variant file with a short path of`XX/YY.lproj/ZZ`+# it would return `YY.lproj/ZZ`.+def _get_dest_subpath_for_variant_file(variant_file: Artifact) -> str:+ dir_name = _get_variant_dirname(variant_file)+ if not dir_name:+ fail("Variant files have to be in a directory with name ending in '.lproj' but `{}` was not.".format(variant_file.short_path))+ file_name = variant_file.basename+ return paths.join(dir_name, file_name)++def _get_variant_dirname(variant_file: Artifact) -> str | None:+ dir_name = paths.basename(paths.dirname(variant_file.short_path))+ return dir_name if dir_name.endswith("lproj") else None
@@ -0,0 +1,144 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(":debug.bzl", "AppleDebuggableInfo")++AppleBundleType = enum(+ "default",+ # Bundle was built for watchOS Apple platform+ "watchapp",+ # Bundle represents an App Clip to be embedded+ "appclip",+ # Bundle represents an ExtensionKit extension to be embedded+ "extensionkit_extension",+)++ApplePackageExtension = enum(+ "ipa",+ "pkg",+ "dmg",+ "zip",+)++AppleBundleManifestLogFiles = record(+ command_file = field(Artifact),+ spec_file = field(Artifact),+ log_file = field([Artifact, None], None),+)++AppleBundleManifest = record(+ log_file_map = dict[Label, AppleBundleManifestLogFiles],+)++AppleBundleCodesignManifestTree = record(+ # Codesign manifest for the bundle itself+ codesign_manifest = field(Artifact),+ # Codesign manifest for inner bundles.+ # Maps from relative bundle destination -> AppleBundleCodesignManifestTree+ inner_codesign_manifests = field(dict[str, typing.Any]),+)++AppleBundleSigningContextTree = record(+ # Signing context for the bundle itself+ signing_context = field(Artifact),+ # Signing contexts for inner bundles.+ # Maps from relative bundle destination -> AppleBundleSigningContextTree+ inner_signing_contexts = field(dict[str, typing.Any]),+)++AppleBundleManifestInfo = provider(+ fields = {+ "manifest": provider_field(AppleBundleManifest),+ },+)++# Provider flagging that result of the rule contains Apple bundle.+# It might be copied into main bundle to appropriate place if rule+# with this provider is a dependency of `apple_bundle`.+AppleBundleInfo = provider(+ # @unsorted-dict-items+ fields = {+ # Result bundle+ "bundle": provider_field(Artifact),+ "bundle_type": provider_field(AppleBundleType),+ # The name of the executable within the bundle.+ "binary_name": provider_field([str, None], default = None),+ # If the bundle contains a Watch bundle, we have to update the packaging.+ # Similar to `is_watchos`, this might be omitted for certain types of bundles which don't depend on it.+ "contains_watchapp": provider_field([bool, None]),+ # By default, non-framework, non-appex binaries copy Swift libraries into the final+ # binary. This is the opt-out for that.+ "skip_copying_swift_stdlib": provider_field([bool, None]),+ # List of extra paths (relative to bundle root) to be codesigned.+ "extra_codesign_paths": provider_field([list[str], None], default = None),+ "codesign_manifest_tree": provider_field(AppleBundleCodesignManifestTree | None, default = None),+ "signing_context_tree": provider_field(AppleBundleSigningContextTree | None, default = None),+ "signing_info": provider_field(Artifact | None, default = None),+ },+)++# Provider which helps to propagate minimum deployment version up the target graph.+AppleMinDeploymentVersionInfo = provider(+ fields = {+ "version": provider_field([str, None]),+ }+)++AppleBundleResourceInfo = provider(+ fields = {+ "resource_output": provider_field(typing.Any, default = None), # AppleBundleResourcePartListOutput+ }+)++AppleBundleLinkerMapInfo = provider(+ fields = {+ "linker_maps": provider_field(list[Artifact]),+ }+)++# Providers used to merge extra linker outputs as a top level output+# of an application bundle.+AppleBinaryExtraOutputsInfo = provider(+ fields = {+ "default_output": provider_field(Artifact),+ "extra_outputs": provider_field(dict[str, list[Artifact]]),+ "name": provider_field(str),+ }+)++AppleBundleExtraOutputsInfo = provider(+ fields = {+ "extra_outputs": provider_field(list[AppleBinaryExtraOutputsInfo]),+ }+)++AppleBundleBinaryOutput = record(+ binary = field(Artifact),+ # If `unstripped_binary` is `None`, then `binary` is unstripped.+ # Otherwise, `unstripped_binary` is distinct from `binary` and is unstripped.+ unstripped_binary = field([Artifact, None]),+ debuggable_info = field([AppleDebuggableInfo, None], None),+)++AppleBundleTypeDefault = AppleBundleType("default")+AppleBundleTypeWatchApp = AppleBundleType("watchapp")+AppleBundleTypeAppClip = AppleBundleType("appclip")+AppleBundleTypeExtensionKitExtension = AppleBundleType("extensionkit_extension")++# Represents the user-visible type which is distinct from the internal one (`AppleBundleType`)+AppleBundleTypeAttributeType = enum(+ "appclip",+ "extensionkit_extension",+ "watchapp",+)++AppleInfoPlistInfo = provider(+ fields = {+ "info_plist": provider_field(Artifact),+ }+)
@@ -0,0 +1,115 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//utils:utils.bzl", "flatten", "value_or")+load(":apple_bundle_types.bzl", "AppleBundleLinkerMapInfo", "AppleMinDeploymentVersionInfo")+load(":apple_library.bzl", "AppleLibraryForDistributionInfo")+load(":apple_resource_types.bzl", "AppleResourceProcessingOptions")+load(":apple_target_sdk_version.bzl", "get_min_deployment_version_for_node")+load(":apple_toolchain_types.bzl", "AppleToolchainInfo")+load(":resource_groups.bzl", "ResourceGraphInfo")++# `ctx` in all functions below is expected to be of `apple_bundle` or `apple_test` rule++def get_is_watch_bundle(ctx: AnalysisContext) -> bool:+ return ctx.attrs._apple_toolchain[AppleToolchainInfo].sdk_name.startswith("watch")++def _get_bundle_target_name(ctx: AnalysisContext):+ if hasattr(ctx.attrs, "_bundle_target_name"):+ # `apple_resource_bundle` rules are proxies for the real rules,+ # so make sure we return the real target name rather the proxy one+ return ctx.attrs._bundle_target_name+ return ctx.attrs.name++def get_product_name(ctx: AnalysisContext) -> str:+ if hasattr(ctx.attrs, "product_name") and ctx.attrs.product_name != None:+ return ctx.attrs.product_name+ if getattr(ctx.attrs, "product_name_from_module_name", False):+ apple_library_info = get_default_binary_dep(ctx.attrs.binary).get(AppleLibraryForDistributionInfo)+ if apple_library_info != None:+ return apple_library_info.module_name+ return _get_bundle_target_name(ctx)++def get_extension_attr(ctx: AnalysisContext) -> typing.Any:+ return ctx.attrs.extension++def get_default_binary_dep(binary_deps: [dict[str, Dependency], Dependency, None]) -> [Dependency, None]:+ if not type(binary_deps) == "dict":+ return binary_deps++ if len(binary_deps.items()) == 1:+ return binary_deps.values()[0]++ return binary_deps["arm64"] if "arm64" in binary_deps else binary_deps["x86_64"]++def get_flattened_binary_deps(binary_deps: dict[str, Dependency]) -> list[Dependency]:+ return binary_deps.values()++# Derives the effective deployment target for the bundle. It's+# usually the deployment target of the binary if present,+# otherwise it falls back to other values (see implementation).+def get_bundle_min_target_version(ctx: AnalysisContext, binary_or_binaries: [dict[str, Dependency], Dependency, None]) -> str:+ binary = get_default_binary_dep(binary_or_binaries)++ binary_min_version = None++ # apple_xcuitest bundles do not have a binary+ if binary != None:+ min_version_info = binary[AppleMinDeploymentVersionInfo] if AppleMinDeploymentVersionInfo in binary else None+ if min_version_info != None:+ binary_min_version = min_version_info.version++ fallback_min_version = get_min_deployment_version_for_node(ctx)+ min_version = binary_min_version or fallback_min_version++ if min_version != None:+ return min_version++ # TODO(T110378109): support default value from SDK `Info.plist`+ fail("Could not determine min target sdk version for bundle: {}".format(ctx.label))++def get_bundle_resource_processing_options(ctx: AnalysisContext) -> AppleResourceProcessingOptions:+ compile_resources_locally = value_or(+ ctx.attrs._compile_resources_locally_override, ctx.attrs._apple_toolchain[AppleToolchainInfo].compile_resources_locally+ )+ is_watch_bundle = get_is_watch_bundle(ctx)+ return AppleResourceProcessingOptions(+ prefer_local = compile_resources_locally and (not is_watch_bundle),+ # TODO: Remote execution preference should be part of `apple_toolchain()`, same as `compile_resources_locally`+ prefer_remote = is_watch_bundle,+ allow_cache_upload = compile_resources_locally,+ )++def get_bundle_infos_from_graph(graph: ResourceGraphInfo) -> list[AppleBundleLinkerMapInfo]:+ bundle_infos = []+ for node in graph.nodes.traverse():+ if not node.resource_spec:+ continue++ resource_spec = node.resource_spec+ for artifact in resource_spec.files:+ if not isinstance(artifact, Dependency):+ continue++ bundle_info = artifact.get(AppleBundleLinkerMapInfo)+ if bundle_info:+ bundle_infos.append(bundle_info)++ return bundle_infos++def merge_bundle_linker_maps_info(infos: list[AppleBundleLinkerMapInfo]) -> AppleBundleLinkerMapInfo:+ return AppleBundleLinkerMapInfo(+ linker_maps = flatten([info.linker_maps for info in infos]),+ )++def get_apple_versioned_macos_bundle_value_primitive(name: str, versioned_macos_bundle: bool) -> bool:+ # versioned_macos_bundle only makes sense on mac, disregard value otherwise+ if name == "macosx" or name == "maccatalyst":+ return versioned_macos_bundle+ else:+ return False
@@ -0,0 +1,34 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# Provider which exposes a field from `apple_binary` to `apple_bundle` as it might be used during code signing.+AppleEntitlementsInfo = provider(+ fields = {+ "entitlements_file": provider_field(Artifact | None, default = None),+ }+)++CodeSignType = enum(+ "skip",+ "adhoc",+ "distribution",+)++CodeSignConfiguration = enum(+ # Produces plists inside the app bundle which contains codesign args+ "dry-run",+ # Runs all codesigning logic except invoking the actual codesign commands+ "execution-bypass",+ # Skips adhoc codesigning when it's not strictly required+ "fast-adhoc",+ "none",+)++def get_code_signing_configuration_attr_value(ctx: AnalysisContext) -> [CodeSignConfiguration, None]:+ configuration_value = ctx.attrs.code_signing_configuration or ctx.attrs._code_signing_configuration+ return CodeSignConfiguration(configuration_value)
@@ -0,0 +1,516 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,+# but should be manually edited going forward. There may be some errors in+# the generated docs, and so those should be verified to be accurate and+# well-formatted (and then delete this TODO)++load("@prelude//:is_full_meta_repo.bzl", "is_full_meta_repo")+load(":apple_toolchain_types.bzl", "AppleToolchainInfo", "AppleToolsInfo")++def _headers_arg():+ return {+ "headers": attrs.named_set(+ attrs.source(),+ sorted = True,+ default = [],+ doc = """+ The set of header files that are made available for inclusion to the source files in this+ target. These should be specified as either a list of header files or a dictionary of header names+ to header files. The header names can contain forward slashes (`/`). If a list of+ header files is specified, the headers can be imported+ with `#import "$HEADER_PATH_PREFIX/$HEADER_NAME"` or `#import+ "$HEADER_NAME"`, where `$HEADER_PATH_PREFIX` is the value of+ the target's `header_path_prefix` attribute, and `$HEADER_NAME` is+ the filename of the header file. If a dictionary is specified, each header can be imported+ with `#import "$HEADER_NAME"`, where `$HEADER_NAME` is the key+ corresponding to this file. In this case, the `header_path_prefix` attribute is+ ignored. In either case, quotes in the import statements can be replaced with angle brackets.+""",+ ),+ }++def _exported_headers_arg():+ return {+ "exported_headers": attrs.named_set(+ attrs.source(),+ sorted = True,+ default = [],+ doc = """+ The set of header files that are made available for inclusion to the source files in this+ target and all targets that transitively depend on this one. These should be specified as+ either a list of header files or a dictionary of header names+ to header files. The header names can contain forward slashes (`/`). If a list of+ header files is specified, the headers can be imported+ with `#import "$HEADER_PATH_PREFIX/$HEADER_NAME"` or, if a header file that belongs to+ the same rule is being imported, with `#import+ "$HEADER_NAME"`, where `$HEADER_PATH_PREFIX` is the value of+ the target's `header_path_prefix` attribute, and `$HEADER_NAME` is+ the filename of the header file. If a dictionary is specified, each header can be imported+ with `#import "$HEADER_NAME"`, where `$HEADER_NAME` is the key+ corresponding to this file. In this case, the `header_path_prefix` attribute is+ ignored. In either case, quotes in the import statements can be replaced with angle brackets.+""",+ ),+ }++def _header_path_prefix_arg():+ return {+ "header_path_prefix": attrs.option(+ attrs.string(),+ default = None,+ doc = """+ A path prefix when including headers of this target. For example, headers from a library defined+ using++ ```+ apple_library(+ name = "Library",+ headers = glob(["**/*.h"]),+ header_path_prefix = "Lib",+ )+ ```++ can be imported using following mapping++ ```+ Library/SubDir/Header1.h -> Lib/Header1.h+ Library/Header2.h -> Lib/Header2.h+ ```++ Defaults to the short name of the target. Can contain forward slashes (`/`), but+ cannot start with one. See `headers` for more information.+""",+ ),+ }++def _frameworks_arg():+ return {+ "frameworks": attrs.list(+ attrs.string(),+ default = [],+ doc = """+ A list of system frameworks that the code in this target uses. Each entry should be a path+ starting with `$SDKROOT` or `$PLATFORM_DIR` to denote that the rest of the+ path is relative to the root of the SDK used for the build or to the platform toolchain+ directory.+""",+ ),+ }++def _target_sdk_version():+ return {+ "target_sdk_version": attrs.option(+ attrs.string(),+ default = None,+ doc = """+ The minimum OS version that the library target should support, overriding the minimum set in+ `.buckconfig`. When set, Buck will automatically add flags to both Objective-C and+ Swift compilation that will allow the use of the new APIs without guarding code inside availability+ checks.+""",+ ),+ }++def _info_plist_arg():+ return {+ "info_plist": attrs.source(+ doc = """+ A path to an `Info.plist` file that will be placed in the bundle. The specified file+ will be processed by substituting variable names with their values+ (see `info_plist_substitutions` for more information).+"""+ ),+ }++def _info_plist_substitutions_arg():+ return {+ "info_plist_substitutions": attrs.dict(+ key = attrs.string(),+ value = attrs.string(),+ sorted = False,+ default = {},+ doc = """+ A dictionary that assigns variable names to their values. It is used for variable+ substitution when processing the file specified in `info_plist`. For example if this+ argument is set to `{\'VAR\': \'MyValue\'}`, then each occurrence of `$(VAR)` or `${VAR}` in the file will be replaced by `MyValue`.+""",+ ),+ }++def _extra_xcode_sources():+ return {+ "extra_xcode_sources": attrs.list(+ attrs.source(allow_directory = True),+ default = [],+ doc = """+ When the project is generated, this is the list of files that will added to the build phase+ "Compile Sources" of the given target.+""",+ ),+ }++def _extra_xcode_files():+ return {+ "extra_xcode_files": attrs.list(+ attrs.source(),+ default = [],+ doc = """+ When the project is generated, this is the list of files that will added to the project.+ Those files won't be added to the build phase "Compile Sources".+""",+ ),+ }++def _privacy_manifest_arg():+ return {+ "privacy_manifest": attrs.option(+ attrs.source(),+ default = None,+ doc = """+ A path to an `.xcprivacy` file that will be placed in the bundle.+""",+ ),+ }++def _serialize_debugging_options_arg():+ return {+ # Need ability to distinguish between no value provided by users+ # vs value explicitly set to `True` (in the latter case, we should+ # show warning if value cannot be respected in mixed modules while+ # in the former, we do not show a warning).+ #+ # Lack of value defaults to enabling serialized debugging options.+ "serialize_debugging_options": attrs.option(attrs.bool(), default = None),+ }++def _uses_explicit_modules_arg():+ return {+ "uses_explicit_modules": attrs.bool(default = False),+ }++def _meta_apple_library_validation_enabled_default_value():+ if not is_full_meta_repo():+ return False++ meta_apple_library_validation_enabled_default = read_root_config("apple", "meta_apple_library_validation", "false").lower() == "true"++ is_arvr_build = read_root_config("fb", "arvr_build", "false").lower() == "true"+ if is_arvr_build:+ # Not all arvr builds have `arvr_mode_enabled` constraint, so under arvr+ # build mode, always disable suffixing checks as those graphs are not suffixed+ return False++ return select({+ "DEFAULT": select({+ "DEFAULT": meta_apple_library_validation_enabled_default,+ "config//features/apple:fb_xplat_suffixing_check_disabled": False,+ "config//features/apple:fb_xplat_suffixing_check_enabled": True,+ }),+ # arvr targets do not use suffixed targets, as any xplat target deps+ # get rewritten without the Apple-specific suffixes.+ "config//build_mode:arvr_mode[enabled]": False,+ })++def _meta_apple_library_validation_enabled_arg():+ return {+ "_meta_apple_library_validation_enabled": attrs.bool(default = _meta_apple_library_validation_enabled_default_value()),+ }++def _skip_universal_resource_dedupe_default_value():+ if not is_full_meta_repo():+ return False++ return select({+ "DEFAULT": False,+ "config//features/apple:skip_universal_resource_dedupe_disabled": False,+ "config//features/apple:skip_universal_resource_dedupe_enabled": True,+ })++def _skip_universal_resource_dedupe_arg():+ return {+ "skip_universal_resource_dedupe": attrs.bool(default = _skip_universal_resource_dedupe_default_value()),+ }++def _apple_sanitizer_compatibility_arg():+ if not is_full_meta_repo():+ return {}++ return {+ "_sanitizer_compatibility": attrs.default_only(attrs.dep(default = "fbsource//tools/build_defs/apple/sanitizers:sanitizer_compatibility")),+ }++def _apple_tools_arg():+ return {+ "_apple_tools": attrs.dep(default = "prelude//apple/tools:apple-tools", providers = [AppleToolsInfo]),+ }++def _product_name_from_module_name_arg():+ return {+ "product_name_from_module_name": attrs.bool(default = False),+ }++def _executable_name_for_universal_arg():+ return {+ "executable_name": attrs.option(+ attrs.string(),+ default = None,+ doc = """+ By default, the name of the universal executable is same as the name of the binary+ from the `binary` target attribute. Set `executable_name` to override the default.+ """,+ ),+ }++def _executable_name_arg():+ return {+ "executable_name": attrs.option(attrs.string(), default = None),+ }++def _apple_toolchain_arg():+ return {+ "_apple_toolchain": attrs.toolchain_dep(default = "toolchains//:apple-default", providers = [AppleToolchainInfo]),+ }++def _asset_catalogs_compilation_options_arg():+ return {+ "asset_catalogs_compilation_options": attrs.dict(+ key = attrs.string(),+ value = attrs.any(),+ default = {},+ doc = """+ A dict holding parameters for asset catalogs compiler (actool). Its options include:++ * `notices` (defaults to `True`)+ * `warnings` (defaults to `True`)+ * `errors` (defaults to `True`)+ * `compress_pngs` (defaults to `True`)+ * `optimization` (defaults to `'space'`)+ * `output_format` (defaults to `'human-readable-text'`)+ * `extra_flags` (defaults to `[]`)+ """,+ ),+ }++def _apple_installer_arg():+ installer_target = "fbsource//xplat/buck2/platform/apple/python_installer:apple_installer"+ return {+ "installer": attrs.default_only(attrs.exec_dep(default = installer_target)),+ }++def _enforce_minimum_os_plist_key():+ return {+ "enforce_minimum_os_plist_key": attrs.bool(default = False),+ }++def _default_platform_arg():+ return {"default_platform": attrs.option(attrs.string(), default = None)}++def _codesign_flags_arg():+ return {"codesign_flags": attrs.list(attrs.string(), default = [])}++def _codesign_identity_arg():+ return {"codesign_identity": attrs.option(attrs.string(), default = None)}++def _defaults_arg():+ return {"defaults": attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False, default = {})}++def _deps_arg():+ return {"deps": attrs.list(attrs.dep(), default = [])}++def _devirt_enabled_arg():+ return {"devirt_enabled": attrs.bool(default = False)}++def _diagnostics_arg():+ return {"diagnostics": attrs.dict(key = attrs.string(), value = attrs.source(), sorted = False, default = {})}++def _enable_cxx_interop_arg():+ return {"enable_cxx_interop": attrs.bool(default = False)}++def _fat_lto_arg():+ return {"fat_lto": attrs.bool(default = False)}++def _ibtool_flags_arg():+ return {"ibtool_flags": attrs.option(attrs.list(attrs.string()), default = None)}++def _libraries_arg():+ return {"libraries": attrs.list(attrs.string(), default = [])}++def _link_group_arg():+ return {"link_group": attrs.option(attrs.string(), default = None)}++def _minimum_os_version_arg():+ return {"minimum_os_version": attrs.option(attrs.string(), default = None)}++def _modular_arg():+ return {"modular": attrs.bool(default = False)}++def _module_name_arg():+ return {"module_name": attrs.option(attrs.string(), default = None)}++def _module_requires_cxx_arg():+ return {"module_requires_cxx": attrs.bool(default = False)}++def _product_name_arg():+ return {"product_name": attrs.option(attrs.string(), default = None)}++def _resource_group_arg():+ return {"resource_group": attrs.option(attrs.string(), default = None)}++def _sdk_modules_arg():+ return {"sdk_modules": attrs.list(attrs.string(), default = [])}++def _static_library_basename_arg():+ return {"static_library_basename": attrs.option(attrs.string(), default = None)}++def _strip_level_arg():+ return {+ "strip_level": attrs.enum(+ ["unstripped", "all", "non_global", "debug"],+ default = read_root_config("apple", "strip_level", "unstripped"),+ )+ }++def _swift_module_skip_function_bodies_arg():+ return {"swift_module_skip_function_bodies": attrs.bool(default = True)}++def _disable_generated_umbrella_header_arg():+ # When True, the Swift compilation will not auto-generate an umbrella+ # header for mixed ObjC/Swift modules. Modules that opt in must provide+ # their own umbrella header (or an empty one) named after the module so+ # that `#import <ModuleName/ModuleName.h>` emitted in the -Swift.h header+ # still resolves.+ return {"disable_generated_umbrella_header": attrs.bool(default = True)}++def _swift_package_name_arg():+ return {"swift_package_name": attrs.option(attrs.string(), default = None)}++def _skip_private_swiftinterface_arg():+ return {"skip_private_swiftinterface": attrs.bool(default = False)}++def _thin_lto_arg():+ return {"thin_lto": attrs.bool(default = False)}++def _use_submodules_arg():+ return {"use_submodules": attrs.bool(default = True)}++def _uses_cxx_explicit_modules_arg():+ return {"uses_cxx_explicit_modules": attrs.bool(default = False)}++def _uses_modules_arg():+ return {"uses_modules": attrs.bool(default = False)}++def _xcode_product_type_arg():+ return {"xcode_product_type": attrs.option(attrs.string(), default = None)}++def _entitlements_suffixed_key_map_arg():+ return {+ "entitlements_suffixed_key_map": attrs.dict(+ key = attrs.string(),+ value = attrs.string(),+ sorted = False,+ default = {},+ doc = """+ A map of entitlement key to suffix string. For each entry, the corresponding value(s) in the+ entitlements plist will have the suffix appended. Values can be a single string or a list of+ strings; both are handled. For example, `{"keychain-access-groups": ".suffix"}` will append+ `.suffix` to every value under the `keychain-access-groups` key.+""",+ ),+ }++def _entitlements_removed_keys_arg():+ return {+ "entitlements_removed_keys": attrs.list(+ attrs.string(),+ default = [],+ doc = """+ A list of entitlement keys to remove from the entitlements plist. Any key present in this list+ will be deleted from the final entitlements before code signing. For example,+ `["com.apple.developer.icloud-services"]` will remove the `com.apple.developer.icloud-services`+ key from the entitlements.+""",+ ),+ }++def _entitlements_removed_values_map_arg():+ return {+ "entitlements_removed_values_map": attrs.dict(+ key = attrs.string(),+ value = attrs.list(attrs.string()),+ sorted = False,+ default = {},+ doc = """+ A map of entitlement keys to a list of values to remove from that key's value in the+ entitlements plist. If the entitlement value is a list, the specified values are removed+ from it. If the entitlement value is a dict, the specified values are removed as keys+ from it. For example, `{"keychain-access-groups": ["group1"]}` will remove "group1"+ from the `keychain-access-groups` list.+""",+ ),+ }++apple_common = struct(+ headers_arg = _headers_arg,+ exported_headers_arg = _exported_headers_arg,+ header_path_prefix_arg = _header_path_prefix_arg,+ frameworks_arg = _frameworks_arg,+ target_sdk_version = _target_sdk_version,+ info_plist_arg = _info_plist_arg,+ info_plist_substitutions_arg = _info_plist_substitutions_arg,+ extra_xcode_sources = _extra_xcode_sources,+ extra_xcode_files = _extra_xcode_files,+ privacy_manifest_arg = _privacy_manifest_arg,+ serialize_debugging_options_arg = _serialize_debugging_options_arg,+ uses_explicit_modules_arg = _uses_explicit_modules_arg,+ meta_apple_library_validation_enabled_arg = _meta_apple_library_validation_enabled_arg,+ skip_universal_resource_dedupe_arg = _skip_universal_resource_dedupe_arg,+ apple_sanitizer_compatibility_arg = _apple_sanitizer_compatibility_arg,+ apple_tools_arg = _apple_tools_arg,+ product_name_from_module_name_arg = _product_name_from_module_name_arg,+ executable_name_for_universal_arg = _executable_name_for_universal_arg,+ executable_name_arg = _executable_name_arg,+ apple_toolchain_arg = _apple_toolchain_arg,+ asset_catalogs_compilation_options_arg = _asset_catalogs_compilation_options_arg,+ apple_installer_arg = _apple_installer_arg,+ enforce_minimum_os_plist_key = _enforce_minimum_os_plist_key,+ default_platform_arg = _default_platform_arg,+ codesign_flags_arg = _codesign_flags_arg,+ codesign_identity_arg = _codesign_identity_arg,+ defaults_arg = _defaults_arg,+ deps_arg = _deps_arg,+ devirt_enabled_arg = _devirt_enabled_arg,+ diagnostics_arg = _diagnostics_arg,+ enable_cxx_interop_arg = _enable_cxx_interop_arg,+ fat_lto_arg = _fat_lto_arg,+ ibtool_flags_arg = _ibtool_flags_arg,+ libraries_arg = _libraries_arg,+ link_group_arg = _link_group_arg,+ minimum_os_version_arg = _minimum_os_version_arg,+ modular_arg = _modular_arg,+ module_name_arg = _module_name_arg,+ module_requires_cxx_arg = _module_requires_cxx_arg,+ product_name_arg = _product_name_arg,+ resource_group_arg = _resource_group_arg,+ sdk_modules_arg = _sdk_modules_arg,+ static_library_basename_arg = _static_library_basename_arg,+ strip_level_arg = _strip_level_arg,+ swift_module_skip_function_bodies_arg = _swift_module_skip_function_bodies_arg,+ disable_generated_umbrella_header_arg = _disable_generated_umbrella_header_arg,+ swift_package_name_arg = _swift_package_name_arg,+ skip_private_swiftinterface_arg = _skip_private_swiftinterface_arg,+ thin_lto_arg = _thin_lto_arg,+ use_submodules_arg = _use_submodules_arg,+ uses_cxx_explicit_modules_arg = _uses_cxx_explicit_modules_arg,+ uses_modules_arg = _uses_modules_arg,+ xcode_product_type_arg = _xcode_product_type_arg,+ entitlements_suffixed_key_map_arg = _entitlements_suffixed_key_map_arg,+ entitlements_removed_keys_arg = _entitlements_removed_keys_arg,+ entitlements_removed_values_map_arg = _entitlements_removed_values_map_arg,+)
@@ -0,0 +1,122 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")+load(+ "@prelude//ide_integrations/xcode:data.bzl",+ "XCODE_DATA_SUB_TARGET",+ "XcodeDataInfoKeys",+ "generate_xcode_data",+)+load(":apple_bundle_utility.bzl", "get_bundle_min_target_version", "get_bundle_resource_processing_options")+load(":apple_core_data_types.bzl", "AppleCoreDataSpec")+load(":apple_sdk.bzl", "get_apple_sdk_name")+load(":apple_target_sdk_version.bzl", "get_platform_name_for_sdk", "get_platform_version_for_sdk_version")+load(":resource_groups.bzl", "create_resource_graph")++def apple_core_data_impl(ctx: AnalysisContext) -> list[Provider]:+ spec = AppleCoreDataSpec(+ module = ctx.attrs.module,+ path = ctx.attrs.path,+ )+ graph = create_resource_graph(+ ctx = ctx,+ labels = ctx.attrs.labels,+ deps = [],+ exported_deps = [],+ core_data_spec = spec,+ )++ xcode_data_default_info, xcode_data_info = generate_xcode_data(ctx, "core_data_model", None, _xcode_populate_attributes)++ return [+ DefaultInfo(+ sub_targets = {+ XCODE_DATA_SUB_TARGET: xcode_data_default_info,+ },+ ),+ graph,+ xcode_data_info,+ ]++def compile_apple_core_data(ctx: AnalysisContext, specs: list[AppleCoreDataSpec], product_name: str) -> Artifact | None:+ if len(specs) == 0:+ return None++ output = ctx.actions.declare_output("AppleCoreDataCompiled", has_content_based_path = False)++ # Aggregate all the coredata momc and mapc commands together+ tool_commands = []+ for spec in specs:+ tool, output_path = _get_model_args(ctx, spec)+ tool_command = _get_tool_command(ctx, spec, product_name, tool, output_path)+ tool_commands.append(tool_command)++ # Sandboxing and fs isolation on RE machines results in Xcode tools failing+ # when those are working in freshly created directories in buck-out.+ # See https://fb.workplace.com/groups/1042353022615812/permalink/1872164996301273/+ # As a workaround create a directory in tmp, use it for Xcode tools, then+ # copy the result to buck-out.+ wrapper_script, _ = ctx.actions.write(+ "tool_wrapper.sh",+ [+ cmd_args("set -euo pipefail"),+ cmd_args('export TMPDIR="$(mktemp -d)"'),+ cmd_args(tool_commands),+ cmd_args(output, format = 'mkdir -p {} && cp -r "$TMPDIR"/ {}'),+ ],+ allow_args = True,+ has_content_based_path = False,+ )+ combined_command = cmd_args(["/bin/sh", wrapper_script], hidden = tool_commands + [output.as_output()])+ processing_options = get_bundle_resource_processing_options(ctx)+ ctx.actions.run(+ combined_command,+ prefer_local = processing_options.prefer_local,+ prefer_remote = processing_options.prefer_remote,+ allow_cache_upload = processing_options.allow_cache_upload,+ category = "apple_core_data",+ )+ return output++def _get_model_args(ctx: AnalysisContext, core_data_spec: AppleCoreDataSpec):+ toolchain = ctx.attrs._apple_toolchain[AppleToolchainInfo]++ if core_data_spec.path.extension == ".xcmappingmodel":+ filename = paths.replace_extension(core_data_spec.path.basename, ".cdm")+ return toolchain.mapc, cmd_args("$TMPDIR/" + filename)+ else:+ return toolchain.momc, cmd_args("$TMPDIR")++def _get_tool_command(ctx: AnalysisContext, core_data_spec: AppleCoreDataSpec, product_name: str, tool: RunInfo, output: cmd_args) -> cmd_args:+ sdk_name = get_apple_sdk_name(ctx)+ deployment_target = get_platform_version_for_sdk_version(+ sdk_name = sdk_name,+ sdk_version = get_bundle_min_target_version(ctx, ctx.attrs.binary),+ )++ return cmd_args(+ [+ tool,+ "--sdkroot",+ ctx.attrs._apple_toolchain[AppleToolchainInfo].sdk_path,+ "--" + get_platform_name_for_sdk(sdk_name) + "-deployment-target",+ deployment_target,+ "--module",+ core_data_spec.module if core_data_spec.module else product_name,+ cmd_args(core_data_spec.path, format = "./{}"),+ output,+ ],+ delimiter = " ",+ hidden = core_data_spec.path,+ )++def _xcode_populate_attributes(ctx) -> dict[str, typing.Any]:+ data = {XcodeDataInfoKeys.EXTRA_XCODE_FILES: [ctx.attrs.path]}+ return data
@@ -0,0 +1,12 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++AppleCoreDataSpec = record(+ module = field(str | None),+ path = field(Artifact),+)
@@ -0,0 +1,92 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//utils:arglike.bzl", "ArgLike") # @unused Used as a type+load(":apple_toolchain_types.bzl", "AppleToolchainInfo")+load(":debug.bzl", "AppleDebuggableInfo", "AppleSelectiveDebuggableMetadata") # @unused Used as a type++DSYM_SUBTARGET = "dsym"+DSYM_INFO_SUBTARGET = "dsym-info"+EXTENDED_DSYM_INFO_SUBTARGET = "extended-dsym-info"+DWARF_AND_DSYM_SUBTARGET = "dwarf-and-dsym"++def get_apple_dsym(+ ctx: AnalysisContext, executable: Artifact, debug_info: list[ArgLike], action_identifier: str, output_path_override: [str, None] = None+) -> Artifact:+ output_path = output_path_override or "{}.dSYM".format(executable.short_path)+ return get_apple_dsym_ext(ctx, executable, debug_info, action_identifier, output_path)++# TODO(T110672942): Things which are still unsupported:+# - oso_prefix+def get_apple_dsym_ext(ctx: AnalysisContext, executable: [ArgLike, Artifact], debug_info: list[ArgLike], action_identifier: str, output_path: str) -> Artifact:+ dsymutil = ctx.attrs._apple_toolchain[AppleToolchainInfo].dsymutil+ output = ctx.actions.declare_output(output_path, dir = True, has_content_based_path = False)+ cmd = cmd_args(+ [+ dsymutil,+ # Reproducers are not useful, we can reproduce from the action digest.+ "--reproducer=Off",+ ],+ # Mach-O executables don't contain DWARF data.+ # Instead, they contain paths to the object files which themselves contain DWARF data.+ # So, those object files are needed for dsymutil to be to create the dSYM bundle.+ hidden = debug_info,+ )+ cmd.add(+ "-o",+ output.as_output(),+ executable,+ )+ ctx.actions.run(cmd, category = "apple_dsym", identifier = action_identifier)+ return output++AppleDsymJsonInfo = record(+ # JSON object containing the list of dSYMs+ json_object = field(dict[str, typing.Any]),+ # A list of all artifacts referenced in `json_object`+ outputs = field(list[Artifact]),+)++def get_apple_dsym_info_json(+ binary_dsyms: list[Artifact], dep_dsyms: list[Artifact], metadata: list[AppleSelectiveDebuggableMetadata] | None = None+) -> AppleDsymJsonInfo:+ dsym_info = {}++ if len(binary_dsyms) == 1:+ dsym_info["binary"] = binary_dsyms[0]+ else:+ fail("There can only be one binary dSYM")++ if dep_dsyms:+ # `dedupe` needed as it's possible for the same dSYM to bubble up+ # through multiple paths in a graph (e.g., including both a binary+ # + bundle in the `deps` field of a parent bundle).+ dsym_info["deps"] = dedupe(dep_dsyms)++ metadata_dsym_outputs = []+ if metadata != None:+ metadata_json_obj = {}+ for debuggable_metadata in metadata:+ metadata_json_obj[debuggable_metadata.dsym] = debuggable_metadata.metadata+ metadata_dsym_outputs += [debuggable_metadata.dsym, debuggable_metadata.metadata]+ dsym_info["selective_metadata"] = metadata_json_obj++ return AppleDsymJsonInfo(+ json_object = dsym_info,+ outputs = binary_dsyms + dep_dsyms + metadata_dsym_outputs,+ )++def get_deps_debuggable_infos(ctx: AnalysisContext) -> list[AppleDebuggableInfo]:+ binary_labels = filter(None, [getattr(binary_dep, "label", None) for binary_dep in (ctx.attrs.binary.values() if ctx.attrs.binary else {})])+ deps_debuggable_infos = filter(+ None,+ # It's allowed for `ctx.attrs.binary` to appear in `ctx.attrs.deps` as well,+ # in this case, do not duplicate the debugging info for the binary coming from two paths.+ [dep.get(AppleDebuggableInfo) for dep in ctx.attrs.deps if dep.label not in binary_labels],+ )+ return deps_debuggable_infos
@@ -0,0 +1,71 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//utils:arglike.bzl", "ArgLike") # @unused Used as a type+load(":apple_bundle_utility.bzl", "get_default_binary_dep")+load(":apple_code_signing_types.bzl", "AppleEntitlementsInfo", "CodeSignType")+load(":apple_sdk_metadata.bzl", "IPhoneSimulatorSdkMetadata", "MacOSXCatalystSdkMetadata")+load(":apple_toolchain_types.bzl", "AppleToolchainInfo")++def get_entitlements_codesign_args(ctx: AnalysisContext, codesign_type: CodeSignType) -> list[ArgLike]:+ include_entitlements = should_include_entitlements(ctx, codesign_type)+ maybe_entitlements = _entitlements_file(ctx) if include_entitlements else None+ entitlements_args = ["--entitlements", maybe_entitlements] if maybe_entitlements else []+ return entitlements_args++def should_include_entitlements(ctx: AnalysisContext, codesign_type: CodeSignType) -> bool:+ if codesign_type == CodeSignType("distribution"):+ return True++ if codesign_type == CodeSignType("adhoc"):+ # The config-based override value takes priority over target value+ if ctx.attrs._use_entitlements_when_adhoc_code_signing != None:+ return ctx.attrs._use_entitlements_when_adhoc_code_signing+ return ctx.attrs.use_entitlements_when_adhoc_code_signing++ return False++def _entitlements_file(ctx: AnalysisContext) -> Artifact | None:+ if hasattr(ctx.attrs, "entitlements_file"):+ # Bundling `apple_test` which doesn't have a binary to provide the entitlements, so they are provided via `entitlements_file` attribute directly.+ return ctx.attrs.entitlements_file++ if not ctx.attrs.binary:+ return None++ # The `binary` attribute can be either an apple_binary or a dynamic library from apple_library+ binary_entitlement_info = get_default_binary_dep(ctx.attrs.binary).get(AppleEntitlementsInfo)+ if binary_entitlement_info and binary_entitlement_info.entitlements_file:+ return binary_entitlement_info.entitlements_file++ return ctx.attrs._codesign_entitlements++_SDK_NAMES_NEED_ENTITLEMENTS_IN_BINARY = [+ IPhoneSimulatorSdkMetadata.name,+ MacOSXCatalystSdkMetadata.name,+]++def _needs_entitlements_in_binary(ctx: AnalysisContext) -> bool:+ apple_toolchain_info = ctx.attrs._apple_toolchain[AppleToolchainInfo]+ return apple_toolchain_info.sdk_name in _SDK_NAMES_NEED_ENTITLEMENTS_IN_BINARY++def entitlements_link_flags(ctx: AnalysisContext) -> list[typing.Any]:+ return (+ [+ "-Xlinker",+ "-sectcreate",+ "-Xlinker",+ "__TEXT",+ "-Xlinker",+ "__entitlements",+ "-Xlinker",+ ctx.attrs.entitlements_file,+ ]+ if (ctx.attrs.entitlements_file and _needs_entitlements_in_binary(ctx))+ else []+ )
@@ -0,0 +1,229 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# @oss-disable[end= ]: load(+ # @oss-disable[end= ]: "@prelude//apple/meta_only:apple_extra_error_categories.bzl",+ # @oss-disable[end= ]: "APPLE_CXX_FLAG_MESSAGES",+ # @oss-disable[end= ]: "APPLE_CXX_MESSAGE_CATEGORIES",+ # @oss-disable[end= ]: "APPLE_CXX_STDERR_CATEGORIES",+ # @oss-disable[end= ]: "APPLE_META_STDERR_ERROR_CATEGORIES",+ # @oss-disable[end= ]: "SWIFT_CATEGORY_REMEDIATION",+ # @oss-disable[end= ]: "SWIFT_STDERR_CATEGORIES",+# @oss-disable[end= ]: )+load("@prelude//apple/swift:swift_toolchain.bzl", "get_swift_toolchain_info")+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")+load("@prelude//error_handler:error_enricher_types.bzl", "ErrorEnricher")++APPLE_CXX_FLAG_MESSAGES = {} # @oss-enable+APPLE_CXX_MESSAGE_CATEGORIES = [] # @oss-enable+APPLE_CXX_STDERR_CATEGORIES = [] # @oss-enable+APPLE_META_STDERR_ERROR_CATEGORIES = [] # @oss-enable+SWIFT_CATEGORY_REMEDIATION = {} # @oss-enable+SWIFT_STDERR_CATEGORIES = [] # @oss-enable++_APPLE_STDERR_ERROR_CATEGORIES = [+ # STOP! @oss-disable+ # If you work at Meta, you probably want to include things in APPLE_META_STDERR_ERROR_CATEGORIES @oss-disable+ # so you can include a link to an internal resource (wiki, task, etc) @oss-disable+ # I would only add additional categories here if you think someone in open-source would benefit @oss-disable+ # codesigning issues+ ErrorEnricher(matcher = "codesignprovisioningerror", category = "code_sign_error"), # @oss-enable+ ErrorEnricher(matcher = "the timestamp service is not available", category = "code_sign_error"),+ # compilation issues+ ErrorEnricher(matcher = "failed to emit precompiled module", category = "pcm_compilation_failure"),+ ErrorEnricher(matcher = "please rebuild precompiled header", category = "pcm_compilation_failure"),+ ErrorEnricher(matcher = "llvm-lipo", category = "lipo_failure"),+ ErrorEnricher(matcher = ".modulemap:", category = "modulemap_compilation_failure"),+ ErrorEnricher(matcher = "missing required modules", category = "missing_required_modules_error"),+ ErrorEnricher(matcher = "has a minimum deployment target", category = "deployment_target_error"),+ # toolchain / genrule issues+ ErrorEnricher(matcher = "stack dump:", category = "binary_execution_failure"),+ ErrorEnricher(matcher = "thread 'main' panicked", category = "binary_execution_failure"),+ ErrorEnricher(matcher = "error while loading shared libraries", category = "binary_execution_failure"),+ ErrorEnricher(matcher = "traceback (most recent call last)", category = "python_execution_failure"),+ ErrorEnricher(matcher = "command not found", category = "command_not_found_failure"),+ ErrorEnricher(matcher = "command timed out", category = "timeout_failure"),+ ErrorEnricher(matcher = "no such file or directory", category = "no_such_file_failure"),+ # user errors+ ErrorEnricher(matcher = "unknown target", category = "unknown_buck_target_failure"),+ # buck configuration issues+ ErrorEnricher(matcher = "unknown cell alias", category = "unknown_cell_alias_failure"),+]++def _match(matcher: str | BuckRegex, lowercase_stderr: str) -> bool:+ if isinstance(matcher, str):+ return matcher in lowercase_stderr+ elif isinstance(matcher, BuckRegex):+ return matcher.match(lowercase_stderr)+ else:+ fail("Unknown matcher type: {}", type(matcher))++def _add_category_strings(ctx: ActionErrorCtx, lowercase_stderr: str, errors: list[ActionSubError], source: list[ErrorEnricher]):+ for enricher in source:+ if not _match(enricher.matcher, lowercase_stderr):+ continue++ subcategory = None+ remediation = None+ if enricher.subcategory_extractor:+ subcategory = enricher.subcategory_extractor(lowercase_stderr)+ if subcategory and enricher.subcategory_remediations and subcategory in enricher.subcategory_remediations:+ remediation = enricher.subcategory_remediations[subcategory]++ errors.append(+ ctx.new_sub_error(+ category = "apple_" + enricher.category,+ message = enricher.message,+ subcategory = subcategory,+ remediation = remediation,+ show_in_stderr = remediation != None,+ )+ )++def _category_match(message: str, path: str, categories: list[ErrorEnricher]) -> ErrorEnricher | None:+ for error_category in categories:+ if error_category.file_matcher and error_category.file_matcher not in path:+ continue++ if _match(error_category.matcher, message):+ return error_category++ return None++def apple_build_error_handler(ctx: ActionErrorCtx) -> list[ActionSubError]:+ errors = []++ lowercase_stderr = ctx.stderr.lower()+ _add_category_strings(ctx, lowercase_stderr, errors, _APPLE_STDERR_ERROR_CATEGORIES)+ _add_category_strings(ctx, lowercase_stderr, errors, APPLE_META_STDERR_ERROR_CATEGORIES)++ return errors++def cxx_error_deserializer(ctx: AnalysisContext) -> RunInfo | None:+ return get_cxx_toolchain_info(ctx).binary_utilities_info.custom_tools.get("serialized-diags-to-json", None)++def swift_error_deserializer(ctx: AnalysisContext) -> RunInfo | None:+ return get_swift_toolchain_info(ctx).serialized_diags_to_json++def _valid_error(error: dict) -> bool:+ return "path" in error and "line" in error and "message" in error and "severity" in error++def cxx_error_handler(ctx: ActionErrorCtx) -> list[ActionSubError]:+ errors = []+ for val in ctx.output_artifacts.values():+ for error_json in val.read_json():+ if not _valid_error(error_json):+ continue++ # Clang optionally populates a category and flag field. We are only+ # interested in the flag for now, which helps to know which flag to+ # disable to bypass an error.+ remediation = None+ postfix = ""+ subcategory = None+ error_flag = error_json.get("flag", None)+ if error_flag:+ subcategory = error_flag.replace("-", "_")+ remediation = APPLE_CXX_FLAG_MESSAGES.get(error_flag, None)+ postfix = " [-W{}]".format(error_flag)++ # Fall back to per-error message matching when no flag-based+ # remediation matched, mirroring swift_error_handler.+ if remediation == None:+ custom_category = _category_match(+ message = error_json["message"],+ path = error_json["path"],+ categories = APPLE_CXX_MESSAGE_CATEGORIES,+ )+ if custom_category:+ subcategory = custom_category.category+ if custom_category.message:+ remediation = custom_category.message++ errors.append(+ ctx.new_sub_error(+ category = "apple_cxx_" + error_json["severity"],+ message = error_json["message"] + postfix,+ file = error_json["path"],+ lnum = error_json["line"],+ col = error_json["col"],+ remediation = remediation,+ show_in_stderr = remediation != None,+ subcategory = subcategory,+ ),+ )++ # The cxx error handler is also used for linking, which will not have any+ # serialzed diagnostics, so go through the stderr matcher here.+ if not ctx.output_artifacts.values():+ _add_category_strings(ctx, ctx.stderr.lower(), errors, APPLE_CXX_STDERR_CATEGORIES)++ return errors++def _get_error_type(severity: str) -> str | None:+ error_type = None+ if severity == "error":+ error_type = "E"+ elif severity == "warning":+ error_type = "W"+ elif severity == "note":+ error_type = "N"++ return error_type++def swift_error_handler(ctx: ActionErrorCtx) -> list[ActionSubError]:+ errors = []+ for val in ctx.output_artifacts.values():+ for error_json in val.read_json():+ if not _valid_error(error_json):+ continue++ severity = error_json["severity"]+ message = error_json["message"]+ remediation = None+ subcategory = None++ # Swift serializes the category in the form:+ # SendableClosureCaptures@https://docs.swift.org/compiler/documentation/diagnostics/sendable-closure-captures+ category = error_json.get("category", "")+ if "@" in category:+ # Convert to markdown links for phabricator+ components = error_json["category"].split("@")+ message += " [{}]({})".format(components[0], components[1])+ subcategory = components[0].lower()+ if components[0] in SWIFT_CATEGORY_REMEDIATION:+ remediation = SWIFT_CATEGORY_REMEDIATION[components[0]]+ elif category in SWIFT_CATEGORY_REMEDIATION:+ remediation = SWIFT_CATEGORY_REMEDIATION[category]+ else:+ # With no category in the error itself we categorise based on+ # the message content.+ custom_category = _category_match(+ message = message,+ path = error_json["path"],+ categories = SWIFT_STDERR_CATEGORIES,+ )+ if custom_category:+ subcategory = custom_category.category+ if custom_category.message:+ remediation = custom_category.message+ errors.append(+ ctx.new_sub_error(+ category = "swift_" + severity,+ message = message,+ file = error_json["path"],+ lnum = error_json["line"],+ col = error_json["col"],+ error_type = _get_error_type(severity),+ remediation = remediation,+ show_in_stderr = remediation != None,+ subcategory = subcategory,+ ),+ )++ return errors
@@ -0,0 +1,68 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//xplugins:types.bzl", "XPluginsFunctionMappingManifestInfo")+load(+ ":apple_bundle_types.bzl",+ "AppleBundleInfo",+ "AppleBundleLinkerMapInfo",+ "AppleInfoPlistInfo",+)+load(+ ":debug.bzl",+ "AppleDebuggableInfo",+)++def _apple_finalize_bundle_impl(ctx):+ original_bundle = ctx.attrs.bundle+ original_bundle_info = original_bundle[AppleBundleInfo]+ bundle_artifact = original_bundle_info.bundle+ finalized_bundle = ctx.actions.declare_output(bundle_artifact.basename, has_content_based_path = False)++ cmd = cmd_args([+ ctx.attrs.finalizer[RunInfo],+ "--input-bundle-path",+ bundle_artifact,+ "--output-bundle-path",+ finalized_bundle.as_output(),+ "--sign-key",+ ctx.attrs.sign_key,+ ])+ ctx.actions.run(+ cmd,+ category = "apple_finalize_bundle",+ identifier = bundle_artifact.basename,+ )++ finalized_bundle_info = AppleBundleInfo(+ bundle = finalized_bundle,+ bundle_type = original_bundle_info.bundle_type,+ binary_name = original_bundle_info.binary_name,+ contains_watchapp = original_bundle_info.contains_watchapp,+ skip_copying_swift_stdlib = original_bundle_info.skip_copying_swift_stdlib,+ signing_info = original_bundle_info.signing_info,+ )++ forwarded_providers = [original_bundle[AppleDebuggableInfo], original_bundle[AppleInfoPlistInfo], original_bundle[AppleBundleLinkerMapInfo]]+ xplugins_function_mapping_manifest_info = original_bundle.get(XPluginsFunctionMappingManifestInfo)+ if xplugins_function_mapping_manifest_info:+ forwarded_providers.append(xplugins_function_mapping_manifest_info)++ return [+ DefaultInfo(default_output = finalized_bundle),+ finalized_bundle_info,+ ] + forwarded_providers++apple_finalize_bundle = rule(+ attrs = {+ "bundle": attrs.dep(providers = [AppleBundleInfo]),+ "finalizer": attrs.exec_dep(providers = [RunInfo]),+ "sign_key": attrs.string(default = "fbios-debug"),+ },+ impl = _apple_finalize_bundle_impl,+)
@@ -0,0 +1,1195 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(":apple_sdk.bzl", "get_apple_sdk_name")+load(":apple_target_sdk_version.bzl", "get_min_deployment_version_for_node")+load(":apple_utility.bzl", "has_apple_toolchain")++FRAMEWORK_INTRODUCED_VERSIONS = {+ "AGL": {"macosx": (10, 0, 0)},+ "ARKit": {"iphoneos": (11, 0, 0), "maccatalyst": (14, 0, 0)},+ "AVFAudio": {+ "appletvos": (14, 5, 0),+ "iphoneos": (14, 5, 0),+ "maccatalyst": (14, 5, 0),+ "macosx": (11, 3, 0),+ "watchos": (9, 0, 0),+ },+ "AVFoundation": {+ "appletvos": (9, 0, 0),+ "iphoneos": (2, 2, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 7, 0),+ "watchos": (3, 0, 0),+ },+ "AVKit": {+ "appletvos": (9, 0, 0),+ "iphoneos": (8, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 9, 0),+ "watchos": (9, 0, 0),+ },+ "AVRouting": {+ "iphoneos": (16, 0, 0),+ "maccatalyst": (16, 0, 0),+ "macosx": (13, 0, 0),+ },+ "Accelerate": {+ "appletvos": (9, 0, 0),+ "iphoneos": (4, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 3, 0),+ "watchos": (2, 0, 0),+ },+ "Accessibility": {+ "appletvos": (14, 0, 0),+ "iphoneos": (14, 0, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (11, 0, 0),+ "watchos": (7, 0, 0),+ },+ "AccessoryNotifications": {+ "iphoneos": (26, 4, 0),+ },+ "AccessorySetupKit": {+ "iphoneos": (18, 0, 0),+ },+ "AccessoryTransportExtension": {+ "iphoneos": (26, 2, 0),+ },+ "Accounts": {+ "iphoneos": (5, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 8, 0),+ },+ "ActivityKit": {"iphoneos": (16, 1, 0), "maccatalyst": (16, 1, 0)},+ "AdServices": {+ "iphoneos": (14, 3, 0),+ "maccatalyst": (14, 3, 0),+ "macosx": (11, 1, 0),+ },+ "AdSupport": {+ "appletvos": (9, 0, 0),+ "iphoneos": (6, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 14, 0),+ },+ "AddressBook": {+ "iphoneos": (2, 0, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (10, 2, 0),+ },+ "AddressBookUI": {"iphoneos": (2, 0, 0), "maccatalyst": (14, 0, 0)},+ "AlarmKit": {"iphoneos": (26, 0, 0)},+ "AppClip": {"iphoneos": (14, 0, 0), "maccatalyst": (14, 0, 0)},+ "AppIntents": {+ "appletvos": (16, 0, 0),+ "iphoneos": (16, 0, 0),+ "maccatalyst": (16, 0, 0),+ "macosx": (13, 0, 0),+ "watchos": (9, 0, 0),+ },+ "AppKit": {"maccatalyst": (13, 0, 0), "macosx": (10, 0, 0)},+ "AppMigrationKit": {"iphoneos": (26, 1, 0)},+ "AppTrackingTransparency": {+ "appletvos": (14, 0, 0),+ "iphoneos": (14, 0, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (11, 0, 0),+ },+ "AppleScriptKit": {"macosx": (10, 0, 0)},+ "AppleScriptObjC": {"macosx": (10, 6, 0)},+ "ApplicationServices": {"maccatalyst": (13, 0, 0), "macosx": (10, 0, 0)},+ "AssetsLibrary": {"iphoneos": (4, 0, 0), "maccatalyst": (14, 0, 0)},+ "AudioToolbox": {+ "appletvos": (9, 0, 0),+ "iphoneos": (2, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 0, 0),+ },+ "AudioUnit": {+ "appletvos": (9, 0, 0),+ "iphoneos": (2, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 0, 0),+ },+ "AudioVideoBridging": {"macosx": (10, 8, 0)},+ "AuthenticationServices": {+ "appletvos": (13, 0, 0),+ "iphoneos": (12, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 15, 0),+ "watchos": (6, 0, 0),+ },+ "AutomatedDeviceEnrollment": {"iphoneos": (16, 1, 0)},+ "AutomaticAssessmentConfiguration": {+ "iphoneos": (13, 4, 0),+ "maccatalyst": (13, 4, 0),+ "macosx": (10, 15, 4),+ },+ "Automator": {"maccatalyst": (14, 0, 0), "macosx": (10, 4, 0)},+ "BackgroundAssets": {+ "iphoneos": (16, 0, 0),+ "maccatalyst": (16, 0, 0),+ "macosx": (13, 0, 0),+ },+ "BackgroundTasks": {+ "appletvos": (13, 0, 0),+ "iphoneos": (13, 0, 0),+ "maccatalyst": (13, 0, 0),+ },+ "BusinessChat": {"iphoneos": (11, 3, 0), "macosx": (10, 13, 4)},+ "CFNetwork": {+ "appletvos": (9, 0, 0),+ "iphoneos": (2, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 8, 0),+ },+ "CalendarStore": {"macosx": (10, 5, 0)},+ "CallKit": {+ "iphoneos": (10, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (13, 0, 0),+ "watchos": (9, 0, 0),+ },+ "CarKey": {"iphoneos": (16, 0, 0), "maccatalyst": (16, 0, 0)},+ "CarPlay": {"iphoneos": (12, 0, 0), "maccatalyst": (14, 0, 0)},+ "Carbon": {"macosx": (10, 0, 0)},+ "Charts": {+ "appletvos": (16, 0, 0),+ "iphoneos": (16, 0, 0),+ "maccatalyst": (16, 0, 0),+ "macosx": (13, 0, 0),+ "watchos": (9, 0, 0),+ },+ "ClassKit": {+ "iphoneos": (11, 4, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (11, 0, 0),+ },+ "ClockKit": {+ "iphoneos": (14, 0, 0),+ "maccatalyst": (14, 0, 0),+ "watchos": (2, 0, 0),+ },+ "CloudKit": {+ "appletvos": (9, 0, 0),+ "iphoneos": (8, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 10, 0),+ "watchos": (3, 0, 0),+ },+ "Cocoa": {"macosx": (10, 0, 0)},+ "Collaboration": {"macosx": (10, 5, 0)},+ "ColorSync": {+ "appletvos": (16, 0, 0),+ "iphoneos": (16, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 13, 0),+ "watchos": (9, 0, 0),+ },+ "Combine": {+ "appletvos": (13, 0, 0),+ "iphoneos": (13, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 15, 0),+ "watchos": (6, 0, 0),+ },+ "ContactProvider": {+ "iphoneos": (18, 0, 0),+ },+ "Contacts": {+ "iphoneos": (9, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 11, 0),+ "watchos": (2, 0, 0),+ },+ "ContactsUI": {+ "iphoneos": (9, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 11, 0),+ },+ "CoreAudio": {+ "appletvos": (9, 0, 0),+ "iphoneos": (2, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 0, 0),+ "watchos": (3, 0, 0),+ },+ "CoreAudioKit": {+ "iphoneos": (8, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 4, 0),+ },+ "CoreAudioTypes": {+ "appletvos": (13, 0, 0),+ "iphoneos": (13, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 15, 0),+ "watchos": (6, 0, 0),+ },+ "CoreBluetooth": {+ "appletvos": (9, 0, 0),+ "iphoneos": (5, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 10, 0),+ "watchos": (4, 0, 0),+ },+ "CoreData": {+ "appletvos": (9, 0, 0),+ "iphoneos": (3, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 4, 0),+ "watchos": (2, 0, 0),+ },+ "CoreDisplay": {+ "macosx": (10, 8, 0),+ },+ "CoreFoundation": {+ "appletvos": (9, 0, 0),+ "iphoneos": (2, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 0, 0),+ "watchos": (2, 0, 0),+ },+ "CoreGraphics": {+ "appletvos": (9, 0, 0),+ "iphoneos": (2, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 8, 0),+ "watchos": (2, 0, 0),+ },+ "CoreHID": {+ "macosx": (15, 0, 0),+ },+ "CoreHaptics": {+ "appletvos": (14, 0, 0),+ "iphoneos": (13, 0, 0),+ "maccatalyst": (13, 0, 0),+ },+ "CoreImage": {+ "appletvos": (9, 0, 0),+ "iphoneos": (5, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 11, 0),+ },+ "CoreLocation": {+ "appletvos": (9, 0, 0),+ "iphoneos": (2, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 6, 0),+ "watchos": (2, 0, 0),+ },+ "CoreLocationUI": {+ "iphoneos": (15, 0, 0),+ "maccatalyst": (15, 0, 0),+ "watchos": (8, 0, 0),+ },+ "CoreMIDI": {+ "appletvos": (15, 0, 0),+ "iphoneos": (4, 2, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 0, 0),+ "watchos": (8, 0, 0),+ },+ "CoreML": {+ "appletvos": (11, 0, 0),+ "iphoneos": (11, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 13, 0),+ "watchos": (4, 0, 0),+ },+ "CoreMedia": {+ "appletvos": (9, 0, 0),+ "iphoneos": (4, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 7, 0),+ "watchos": (6, 0, 0),+ },+ "CoreMediaIO": {"maccatalyst": (13, 0, 0), "macosx": (10, 7, 0)},+ "CoreMotion": {+ "iphoneos": (4, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 15, 0),+ "watchos": (2, 0, 0),+ },+ "CoreNFC": {"iphoneos": (11, 0, 0), "maccatalyst": (13, 0, 0)},+ "CoreServices": {+ "appletvos": (12, 0, 0),+ "iphoneos": (12, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 0, 0),+ "watchos": (5, 0, 0),+ },+ "CoreSpotlight": {+ "iphoneos": (9, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 13, 0),+ },+ "CoreTelephony": {+ "iphoneos": (4, 0, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (10, 10, 0),+ },+ "CoreText": {+ "appletvos": (9, 0, 0),+ "iphoneos": (3, 2, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 8, 0),+ "watchos": (2, 0, 0),+ },+ "CoreTransferable": {+ "appletvos": (16, 0, 0),+ "iphoneos": (16, 0, 0),+ "maccatalyst": (16, 0, 0),+ "macosx": (13, 0, 0),+ "watchos": (9, 0, 0),+ },+ "CoreVideo": {+ "appletvos": (9, 0, 0),+ "iphoneos": (4, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 4, 0),+ "watchos": (4, 0, 0),+ },+ "CoreWLAN": {"maccatalyst": (13, 0, 0), "macosx": (10, 6, 0)},+ "CreateML": {+ "appletvos": (16, 0, 0),+ "iphoneos": (15, 0, 0),+ "maccatalyst": (15, 0, 0),+ "macosx": (10, 14, 0),+ },+ "CreateMLComponents": {+ "appletvos": (16, 0, 0),+ "iphoneos": (16, 0, 0),+ "macosx": (13, 0, 0),+ },+ "CryptoKit": {+ "appletvos": (15, 0, 0),+ "iphoneos": (13, 0, 0),+ "maccatalyst": (15, 0, 0),+ "macosx": (10, 15, 0),+ "watchos": (8, 0, 0),+ },+ "CryptoTokenKit": {+ "appletvos": (13, 0, 0),+ "iphoneos": (13, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 10, 0),+ "watchos": (8, 0, 0),+ },+ "DVDPlayback": {"macosx": (10, 3, 0)},+ "DataDetection": {+ "appletvos": (15, 0, 0),+ "iphoneos": (15, 0, 0),+ "maccatalyst": (15, 0, 0),+ "macosx": (12, 0, 0),+ "watchos": (8, 0, 0),+ },+ "DeclaredAgeRange": {+ "iphoneos": (26, 0, 0),+ "maccatalyst": (26, 0, 0),+ "macosx": (26, 0, 0),+ },+ "DeveloperToolsSupport": {+ "appletvos": (14, 0, 0),+ "iphoneos": (14, 0, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (11, 0, 0),+ "watchos": (7, 0, 0),+ },+ "DeviceActivity": {"iphoneos": (15, 0, 0), "maccatalyst": (15, 0, 0)},+ "DeviceCheck": {+ "appletvos": (11, 0, 0),+ "iphoneos": (11, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 15, 0),+ "watchos": (9, 0, 0),+ },+ "DeviceDiscoveryExtension": {"iphoneos": (16, 0, 0)},+ "DeviceDiscoveryUI": {"appletvos": (16, 0, 0)},+ "DirectoryService": {"macosx": (10, 0, 0)},+ "DiscRecording": {"macosx": (10, 2, 0)},+ "DiscRecordingUI": {"macosx": (10, 2, 0)},+ "DiskArbitration": {"maccatalyst": (13, 0, 0), "macosx": (10, 4, 0)},+ "DriverKit": {"iphoneos": (16, 0, 0), "macosx": (10, 15, 0)},+ "EventKit": {+ "iphoneos": (4, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 8, 0),+ "watchos": (2, 0, 0),+ },+ "EventKitUI": {"iphoneos": (4, 0, 0), "maccatalyst": (13, 0, 0)},+ "ExceptionHandling": {"maccatalyst": (13, 0, 0), "macosx": (10, 0, 0)},+ "ExecutionPolicy": {"maccatalyst": (13, 0, 0), "macosx": (10, 15, 0)},+ "ExposureNotification": {+ "iphoneos": (13, 5, 0),+ "maccatalyst": (15, 0, 0),+ "macosx": (12, 0, 0),+ },+ "ExtensionFoundation": {+ "appletvos": (16, 0, 0),+ "iphoneos": (16, 0, 0),+ "maccatalyst": (16, 0, 0),+ "macosx": (13, 0, 0),+ "watchos": (9, 0, 0),+ },+ "ExtensionKit": {+ "appletvos": (16, 0, 0),+ "iphoneos": (16, 1, 0),+ "maccatalyst": (16, 0, 0),+ "macosx": (13, 0, 0),+ "watchos": (9, 0, 0),+ },+ "ExternalAccessory": {+ "appletvos": (10, 0, 0),+ "iphoneos": (3, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 13, 0),+ },+ "FSKit": {+ "macosx": (15, 0, 0),+ },+ "FamilyControls": {"iphoneos": (15, 0, 0), "maccatalyst": (15, 0, 0)},+ "FileProvider": {"iphoneos": (11, 0, 0), "macosx": (10, 15, 0)},+ "FileProviderUI": {+ "iphoneos": (11, 0, 0),+ "maccatalyst": (15, 0, 0),+ "macosx": (10, 15, 0),+ },+ "FinderSync": {"macosx": (10, 10, 0)},+ "ForceFeedback": {"maccatalyst": (13, 0, 0), "macosx": (10, 2, 0)},+ "Foundation": {+ "appletvos": (9, 0, 0),+ "iphoneos": (2, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 0, 0),+ "watchos": (2, 0, 0),+ },+ "FoundationModels": {+ "iphoneos": (26, 0, 0),+ "maccatalyst": (26, 0, 0),+ "macosx": (26, 0, 0),+ },+ "GLKit": {+ "appletvos": (9, 0, 0),+ "iphoneos": (5, 0, 0),+ "macosx": (10, 8, 0),+ },+ "GLUT": {"macosx": (10, 0, 0)},+ "GSS": {+ "iphoneos": (5, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 14, 0),+ },+ "GameController": {+ "appletvos": (9, 0, 0),+ "iphoneos": (7, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 9, 0),+ },+ "GameKit": {+ "appletvos": (9, 0, 0),+ "iphoneos": (3, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 8, 0),+ "watchos": (3, 0, 0),+ },+ "GameplayKit": {+ "appletvos": (9, 0, 0),+ "iphoneos": (9, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 11, 0),+ },+ "GroupActivities": {+ "appletvos": (15, 0, 0),+ "iphoneos": (15, 0, 0),+ "maccatalyst": (15, 0, 0),+ "macosx": (12, 0, 0),+ },+ "HealthKit": {+ "iphoneos": (8, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (13, 0, 0),+ "watchos": (2, 0, 0),+ },+ "HealthKitUI": {+ "iphoneos": (8, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (13, 0, 0),+ "watchos": (2, 0, 0),+ },+ "HomeKit": {+ "appletvos": (10, 0, 0),+ "iphoneos": (8, 0, 0),+ "maccatalyst": (14, 0, 0),+ "watchos": (2, 0, 0),+ },+ "Hypervisor": {"macosx": (10, 10, 0)},+ "ICADevices": {"macosx": (10, 3, 0)},+ "IMServicePlugIn": {"macosx": (10, 7, 0)},+ "IOBluetooth": {"maccatalyst": (13, 0, 0), "macosx": (10, 2, 0)},+ "IOBluetoothUI": {"maccatalyst": (14, 0, 0), "macosx": (10, 2, 0)},+ "IOKit": {+ "iphoneos": (2, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 0, 0),+ },+ "IOSurface": {+ "appletvos": (11, 0, 0),+ "iphoneos": (11, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 6, 0),+ },+ "IOUSBHost": {"maccatalyst": (14, 0, 0), "macosx": (10, 15, 0)},+ "IdentityLookup": {+ "iphoneos": (11, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 15, 0),+ },+ "IdentityLookupUI": {+ "iphoneos": (11, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 15, 0),+ },+ "ImageCaptureCore": {+ "iphoneos": (13, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 6, 0),+ },+ "ImageIO": {+ "appletvos": (9, 0, 0),+ "iphoneos": (4, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 8, 0),+ "watchos": (2, 0, 0),+ },+ "ImagePlayground": {+ "iphoneos": (18, 1, 0),+ "maccatalyst": (18, 1, 0),+ "macosx": (15, 1, 0),+ },+ "InputMethodKit": {"macosx": (10, 5, 0)},+ "InstallerPlugins": {"macosx": (10, 4, 0)},+ "InstantMessage": {"macosx": (10, 4, 0)},+ "Intents": {+ "appletvos": (14, 0, 0),+ "iphoneos": (10, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (12, 0, 0),+ "watchos": (3, 2, 0),+ },+ "IntentsUI": {+ "appletvos": (14, 0, 0),+ "iphoneos": (10, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (12, 0, 0),+ "watchos": (3, 2, 0),+ },+ "JavaNativeFoundation": {"macosx": (11, 0, 0)},+ "JavaRuntimeSupport": {"macosx": (11, 0, 0)},+ "JavaScriptCore": {+ "appletvos": (9, 0, 0),+ "iphoneos": (7, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 5, 0),+ },+ "Kerberos": {"macosx": (10, 0, 0)},+ "Kernel": {"macosx": (10, 0, 0)},+ "KernelManagement": {"maccatalyst": (14, 2, 0), "macosx": (11, 0, 0)},+ "LDAP": {"macosx": (10, 0, 0)},+ "LatentSemanticMapping": {"maccatalyst": (13, 0, 0), "macosx": (10, 5, 0)},+ "LinkPresentation": {+ "appletvos": (14, 0, 0),+ "iphoneos": (13, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 15, 0),+ },+ "LiveCommunicationKit": {+ "iphoneos": (17, 4, 0),+ "maccatalyst": (17, 4, 0),+ "visionos": (1, 1, 0),+ "watchos": (10, 4, 0),+ },+ "LocalAuthentication": {+ "iphoneos": (8, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 10, 0),+ "watchos": (9, 0, 0),+ },+ "LocalAuthenticationEmbeddedUI": {+ "iphoneos": (16, 0, 0),+ "maccatalyst": (16, 0, 0),+ "macosx": (12, 0, 0),+ },+ "LockedCameraCapture": {+ "iphoneos": (18, 0, 0),+ "maccatalyst": (18, 0, 0),+ },+ "MLCompute": {+ "appletvos": (14, 0, 0),+ "iphoneos": (14, 0, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (11, 0, 0),+ },+ "MailKit": {"macosx": (12, 0, 0)},+ "ManagedSettings": {"iphoneos": (15, 0, 0)},+ "ManagedSettingsUI": {"iphoneos": (15, 0, 0)},+ "MapKit": {+ "appletvos": (9, 2, 0),+ "iphoneos": (3, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 9, 0),+ "watchos": (2, 0, 0),+ },+ "MarketplaceKit": {"iphoneos": (17, 4, 0)},+ "Matter": {+ "appletvos": (16, 0, 0),+ "iphoneos": (16, 0, 0),+ "maccatalyst": (16, 1, 0),+ "macosx": (13, 0, 0),+ "watchos": (9, 0, 0),+ },+ "MatterSupport": {"iphoneos": (16, 1, 0)},+ "MediaAccessibility": {+ "appletvos": (9, 0, 0),+ "iphoneos": (7, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 9, 0),+ },+ "MediaExtension": {+ "maccatalyst": (18, 0, 0),+ "macosx": (15, 0, 0),+ },+ "MediaLibrary": {"maccatalyst": (13, 0, 0), "macosx": (10, 9, 0)},+ "MediaPlayer": {+ "appletvos": (9, 0, 0),+ "iphoneos": (2, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (13, 0, 0),+ "watchos": (5, 0, 0),+ },+ "MediaSetup": {"iphoneos": (14, 0, 0), "maccatalyst": (15, 4, 0)},+ "MediaToolbox": {+ "iphoneos": (6, 0, 0),+ "macosx": (10, 9, 0),+ },+ "MessageUI": {"iphoneos": (3, 0, 0), "maccatalyst": (13, 0, 0)},+ "Messages": {"iphoneos": (10, 0, 0), "maccatalyst": (14, 0, 0)},+ "Metal": {+ "appletvos": (9, 0, 0),+ "iphoneos": (8, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 11, 0),+ },+ "MetalFX": {+ "iphoneos": (16, 0, 0),+ "maccatalyst": (16, 0, 0),+ "macosx": (13, 0, 0),+ },+ "MetalKit": {+ "appletvos": (9, 0, 0),+ "iphoneos": (9, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 11, 0),+ },+ "MetalPerformanceShaders": {+ "appletvos": (9, 0, 0),+ "iphoneos": (9, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 13, 0),+ },+ "MetalPerformanceShadersGraph": {+ "appletvos": (14, 0, 0),+ "iphoneos": (14, 0, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (11, 0, 0),+ },+ "MetricKit": {+ "iphoneos": (13, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (12, 0, 0),+ },+ "MobileCoreServices": {+ "appletvos": (9, 0, 0),+ "iphoneos": (2, 0, 0),+ "maccatalyst": (14, 0, 0),+ "watchos": (1, 0, 0),+ },+ "ModelIO": {+ "appletvos": (9, 0, 0),+ "iphoneos": (9, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 11, 0),+ },+ "MultipeerConnectivity": {+ "appletvos": (10, 0, 0),+ "iphoneos": (7, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 10, 0),+ },+ "MusicKit": {+ "appletvos": (15, 0, 0),+ "iphoneos": (15, 0, 0),+ "maccatalyst": (15, 0, 0),+ "macosx": (12, 0, 0),+ "watchos": (8, 0, 0),+ },+ "NaturalLanguage": {+ "appletvos": (12, 0, 0),+ "iphoneos": (12, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 14, 0),+ "watchos": (5, 0, 0),+ },+ "NearbyInteraction": {+ "iphoneos": (14, 0, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (11, 0, 0),+ "watchos": (8, 0, 0),+ },+ "NetFS": {"macosx": (10, 6, 0)},+ "Network": {+ "appletvos": (12, 0, 0),+ "iphoneos": (12, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 14, 0),+ "watchos": (6, 0, 0),+ },+ "NetworkExtension": {+ "iphoneos": (8, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 10, 0),+ "watchos": (7, 0, 0),+ },+ "NewsstandKit": {"iphoneos": (5, 0, 0)},+ "NotificationCenter": {"iphoneos": (8, 0, 0), "macosx": (10, 10, 0)},+ "OSAKit": {"macosx": (10, 4, 0)},+ "OSLog": {+ "appletvos": (15, 0, 0),+ "iphoneos": (15, 0, 0),+ "maccatalyst": (15, 0, 0),+ "macosx": (10, 15, 0),+ "watchos": (8, 0, 0),+ },+ "Observation": {+ "iphoneos": (17, 0, 0),+ "maccatalyst": (17, 0, 0),+ "macosx": (14, 0, 0),+ "tvos": (17, 0, 0),+ "visionos": (1, 0, 0),+ "watchos": (10, 0, 0),+ },+ "OpenCL": {"macosx": (10, 6, 0)},+ "OpenDirectory": {"maccatalyst": (13, 0, 0), "macosx": (10, 6, 0)},+ "OpenGL": {"macosx": (10, 0, 0)},+ "OpenGLES": {"appletvos": (9, 0, 0), "iphoneos": (2, 0, 0)},+ "PCSC": {"macosx": (10, 0, 0)},+ "PDFKit": {"iphoneos": (11, 0, 0), "macosx": (10, 4, 0)},+ "PHASE": {+ "appletvos": (15, 0, 0),+ "iphoneos": (15, 0, 0),+ "maccatalyst": (15, 0, 0),+ "macosx": (12, 0, 0),+ },+ "ParavirtualizedGraphics": {+ "maccatalyst": (14, 0, 0),+ "macosx": (11, 0, 0),+ },+ "PassKit": {+ "iphoneos": (6, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (11, 0, 0),+ "watchos": (2, 0, 0),+ },+ "PencilKit": {+ "iphoneos": (13, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 15, 0),+ },+ "Photos": {+ "appletvos": (10, 0, 0),+ "iphoneos": (8, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 11, 0),+ "watchos": (9, 0, 0),+ },+ "PhotosUI": {+ "appletvos": (10, 0, 0),+ "iphoneos": (8, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 11, 0),+ "watchos": (9, 0, 0),+ },+ "PreferencePanes": {"maccatalyst": (14, 0, 0), "macosx": (10, 1, 0)},+ "ProximitReaderStub": {+ "maccatalyst": (18, 0, 0),+ "macosx": (15, 0, 0),+ },+ "ProximityReader": {"iphoneos": (15, 4, 0), "maccatalyst": (15, 4, 0)},+ "PushKit": {+ "iphoneos": (8, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 15, 0),+ "watchos": (6, 0, 0),+ },+ "PushToTalk": {"iphoneos": (16, 0, 0)},+ "Quartz": {"macosx": (10, 4, 0)},+ "QuartzCore": {+ "appletvos": (9, 0, 0),+ "iphoneos": (2, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 3, 0),+ },+ "QuickLook": {+ "iphoneos": (4, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 5, 0),+ },+ "QuickLookThumbnailing": {+ "iphoneos": (13, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 15, 0),+ },+ "QuickLookUI": {"macosx": (12, 0, 0)},+ "RealityKit": {+ "iphoneos": (13, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 15, 0),+ },+ "ReplayKit": {+ "appletvos": (10, 0, 0),+ "iphoneos": (9, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (11, 0, 0),+ },+ "RoomPlan": {"iphoneos": (16, 0, 0), "maccatalyst": (16, 0, 0)},+ "Ruby": {"macosx": (10, 5, 0)},+ "SafariServices": {+ "iphoneos": (7, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 12, 0),+ },+ "SafetyKit": {+ "iphoneos": (16, 0, 0),+ "maccatalyst": (16, 1, 0),+ "macosx": (13, 0, 0),+ "watchos": (9, 1, 0),+ },+ "SceneKit": {+ "appletvos": (9, 0, 0),+ "iphoneos": (8, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 8, 0),+ "watchos": (3, 0, 0),+ },+ "ScreenCaptureKit": {"maccatalyst": (15, 4, 0), "macosx": (12, 3, 0)},+ "ScreenSaver": {"macosx": (10, 0, 0)},+ "ScreenTime": {+ "iphoneos": (14, 0, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (11, 0, 0),+ },+ "ScriptingBridge": {"maccatalyst": (13, 0, 0), "macosx": (10, 5, 0)},+ "Security": {+ "appletvos": (9, 0, 0),+ "iphoneos": (2, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 0, 0),+ "watchos": (2, 0, 0),+ },+ "SecurityFoundation": {"maccatalyst": (13, 0, 0), "macosx": (10, 3, 0)},+ "SecurityInterface": {"macosx": (10, 3, 0)},+ "SensitiveContentAnalysis": {+ "iphoneos": (17, 0, 0),+ "maccatalyst": (17, 0, 0),+ "macosx": (14, 0, 0),+ },+ "SensorKit": {+ "iphoneos": (14, 0, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (12, 3, 0),+ },+ "ServiceManagement": {+ "appletvos": (12, 1, 0),+ "iphoneos": (12, 1, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 6, 0),+ "watchos": (5, 1, 0),+ },+ "SharedWithYou": {+ "appletvos": (16, 0, 0),+ "iphoneos": (16, 0, 0),+ "maccatalyst": (16, 0, 0),+ "macosx": (13, 0, 0),+ },+ "ShazamKit": {+ "appletvos": (15, 0, 0),+ "iphoneos": (15, 0, 0),+ "maccatalyst": (15, 0, 0),+ "macosx": (12, 0, 0),+ "watchos": (8, 0, 0),+ },+ "Social": {+ "iphoneos": (6, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 8, 0),+ },+ "SoundAnalysis": {+ "appletvos": (13, 0, 0),+ "iphoneos": (13, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 15, 0),+ "watchos": (9, 0, 0),+ },+ "Speech": {+ "iphoneos": (10, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 15, 0),+ },+ "SpriteKit": {+ "appletvos": (9, 0, 0),+ "iphoneos": (7, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 9, 0),+ "watchos": (3, 0, 0),+ },+ "StateReporting": {+ "appletvos": (27, 0, 0),+ "iphoneos": (27, 0, 0),+ "macosx": (27, 0, 0),+ "visionos": (27, 0, 0),+ "watchos": (27, 0, 0),+ },+ "StickerKit": {+ "iphoneos": (18, 0, 0),+ "macosx": (15, 0, 0),+ },+ "StoreKit": {+ "appletvos": (9, 0, 0),+ "iphoneos": (3, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 7, 0),+ "watchos": (6, 2, 0),+ },+ "StoreKitTest": {+ "appletvos": (14, 0, 0),+ "iphoneos": (14, 0, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (11, 0, 0),+ "watchos": (7, 4, 0),+ },+ "SwiftData": {+ "appletvos": (17, 0, 0),+ "iphoneos": (17, 0, 0),+ "maccatalyst": (17, 0, 0),+ "macosx": (14, 0, 0),+ "watchos": (10, 0, 0),+ },+ "SwiftUI": {+ "appletvos": (13, 0, 0),+ "iphoneos": (13, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 15, 0),+ "watchos": (6, 0, 0),+ },+ "SyncServices": {"macosx": (10, 4, 0)},+ "Synchronization": {+ "iphoneos": (18, 0, 0),+ "maccatalyst": (18, 0, 0),+ "macosx": (15, 0, 0),+ "tvos": (18, 0, 0),+ "visionos": (2, 0, 0),+ "watchos": (11, 0, 0),+ },+ "System": {+ "appletvos": (14, 0, 0),+ "iphoneos": (14, 0, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (11, 0, 0),+ "watchos": (7, 0, 0),+ },+ "SystemConfiguration": {+ "appletvos": (9, 0, 0),+ "iphoneos": (2, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 1, 0),+ },+ "SystemExtensions": {"macosx": (10, 15, 0)},+ "TVMLKit": {"appletvos": (9, 0, 0)},+ "TVServices": {"appletvos": (9, 0, 0)},+ "TVUIKit": {"appletvos": (12, 0, 0)},+ "TWAIN": {"macosx": (10, 2, 0)},+ "TabletopKit": {+ "visionos": (2, 0, 0),+ },+ "TabularData": {+ "appletvos": (15, 0, 0),+ "iphoneos": (15, 0, 0),+ "maccatalyst": (15, 0, 0),+ "macosx": (12, 0, 0),+ "watchos": (8, 0, 0),+ },+ "Tcl": {"macosx": (10, 3, 0)},+ "ThreadNetwork": {+ "iphoneos": (15, 0, 0),+ "maccatalyst": (16, 1, 0),+ "macosx": (13, 0, 0),+ },+ "Tk": {"macosx": (10, 4, 0)},+ "Translation": {+ "iphoneos": (17, 4, 0),+ "maccatalyst": (26, 0, 0),+ "macosx": (14, 4, 0),+ },+ "UIKit": {+ "appletvos": (9, 0, 0),+ "iphoneos": (2, 0, 0),+ "maccatalyst": (13, 0, 0),+ "watchos": (2, 0, 0),+ },+ "UniformTypeIdentifiers": {+ "appletvos": (14, 0, 0),+ "iphoneos": (14, 0, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (11, 0, 0),+ "watchos": (7, 0, 0),+ },+ "UserNotifications": {+ "appletvos": (10, 0, 0),+ "iphoneos": (10, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 14, 0),+ "watchos": (3, 0, 0),+ },+ "UserNotificationsUI": {+ "iphoneos": (10, 0, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (11, 0, 0),+ },+ "VideoDecodeAcceleration": {"macosx": (10, 7, 0)},+ "VideoSubscriberAccount": {+ "appletvos": (10, 0, 0),+ "iphoneos": (10, 0, 0),+ "macosx": (10, 14, 0),+ },+ "VideoToolbox": {+ "appletvos": (10, 2, 0),+ "iphoneos": (6, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 8, 0),+ },+ "Virtualization": {"macosx": (11, 0, 0)},+ "Vision": {+ "appletvos": (11, 0, 0),+ "iphoneos": (11, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 13, 0),+ },+ "VisionKit": {+ "iphoneos": (13, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (13, 0, 0),+ },+ "WatchConnectivity": {+ "iphoneos": (9, 0, 0),+ "maccatalyst": (13, 0, 0),+ "watchos": (2, 0, 0),+ },+ "WatchKit": {"watchos": (2, 0, 0)},+ "WeatherKit": {+ "appletvos": (16, 0, 0),+ "iphoneos": (16, 0, 0),+ "maccatalyst": (16, 0, 0),+ "macosx": (13, 0, 0),+ "watchos": (9, 0, 0),+ },+ "WebKit": {+ "iphoneos": (8, 0, 0),+ "maccatalyst": (13, 0, 0),+ "macosx": (10, 2, 0),+ },+ "WiFiAware": {+ "iphoneos": (26, 0, 0),+ },+ "WidgetKit": {+ "iphoneos": (14, 0, 0),+ "maccatalyst": (14, 0, 0),+ "macosx": (11, 0, 0),+ "watchos": (9, 0, 0),+ },+ "iAd": {"iphoneos": (4, 0, 0), "maccatalyst": (13, 0, 0)},+ "iTunesLibrary": {"maccatalyst": (14, 0, 0), "macosx": (10, 13, 0)},+ "vecLib": {"macosx": (10, 0, 0)},+ "vmnet": {"maccatalyst": (13, 0, 0), "macosx": (10, 10, 0)},+}++def _parse_version(version: str) -> (int, int, int):+ result = [0, 0, 0]+ components = [int(x) if x != "0" else 0 for x in version.split(".")]+ for i in range(0, len(components)):+ result[i] = components[i]+ return (result[0], result[1], result[2])++def validate_sdk_frameworks(frameworks: list[str]) -> None:+ for framework in frameworks:+ if framework.startswith("$SDKROOT/System/Library/Frameworks"):+ framework_name = framework[len("$SDKROOT/System/Library/Frameworks/") : -len(".framework")]+ if framework_name not in FRAMEWORK_INTRODUCED_VERSIONS:+ fail("Framework {} is missing version information".format(framework_name))++def get_framework_linker_args(ctx: AnalysisContext, framework_names: list[str]) -> cmd_args:+ if not has_apple_toolchain(ctx):+ return _get_unchecked_framework_linker_args(framework_names)++ # Convert deployment target string into tuple of ints for easier comparison+ deployment_target_str = get_min_deployment_version_for_node(ctx)+ if not deployment_target_str:+ return _get_unchecked_framework_linker_args(framework_names)++ deployment_target = _parse_version(deployment_target_str)++ # Simulator and device platforms have the same framework versions+ sdk_name = get_apple_sdk_name(ctx)+ if sdk_name.endswith("simulator"):+ sdk_name = sdk_name[: -len("simulator")] + "os"++ weak_frameworks = []+ strong_frameworks = []++ args = cmd_args()+ for name in framework_names:+ is_weak = False+ versions = FRAMEWORK_INTRODUCED_VERSIONS.get(name, None)+ if versions:+ introduced = versions.get(sdk_name, None)+ if not introduced:+ message = "SDK framework {} is not compatible with platform {}".format(name, sdk_name)+ # @oss-disable[end= ]: message += "\n\nFor help, see: https://fburl.com/apple_build_errors/sdk_framework_is_not_compatible\n"+ fail(message)++ if _version_is_greater_than(introduced, deployment_target):+ is_weak = True++ if is_weak:+ weak_frameworks.append(name)+ else:+ strong_frameworks.append(name)++ if strong_frameworks:+ args.add(cmd_args(strong_frameworks, prepend = "-framework"))+ if weak_frameworks:+ args.add(cmd_args(weak_frameworks, prepend = "-weak_framework"))++ return args++def _get_unchecked_framework_linker_args(framework_names: list[str]) -> cmd_args:+ return cmd_args(framework_names, prepend = "-framework")++def _version_is_greater_than(x: (int, int, int), y: (int, int, int)) -> bool:+ return x[0] > y[0] or (x[0] == y[0] and x[1] > y[1]) or (x[0] == y[0] and x[1] == y[1] and x[2] > y[2])
@@ -0,0 +1,239 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load("@prelude//apple/swift:swift_compilation.bzl", "extract_swiftmodule_linkables", "get_swiftmodule_linker_flags")+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo", "LinkerType")+load(+ "@prelude//cxx:transformation_spec.bzl",+ "TransformationSpecContext", # @unused Used as a type+)+load(+ "@prelude//linking:link_info.bzl",+ "FrameworksLinkable",+ "LinkArgs",+ "LinkInfo",+ "LinkStrategy", # @unused Used as a type+ "MergedLinkInfo",+ "SwiftmoduleLinkable", # @unused Used as a type+ "get_link_args_for_strategy",+ "has_framework_linkable",+ "merge_swiftmodule_linkables",+)+load("@prelude//utils:expect.bzl", "expect")+load(":apple_framework_versions.bzl", "get_framework_linker_args", "validate_sdk_frameworks")+load(":apple_toolchain_types.bzl", "AppleToolchainInfo")+load(":apple_utility.bzl", "has_apple_toolchain")++_IMPLICIT_SDKROOT_FRAMEWORK_SEARCH_PATHS = [+ "$SDKROOT/Library/Frameworks",+ "$SDKROOT/System/Library/Frameworks",+ "$SDKROOT/System/Library/PrivateFrameworks",+]++def apple_create_frameworks_linkable(ctx: AnalysisContext) -> [FrameworksLinkable, None]:+ if not ctx.attrs.libraries and not ctx.attrs.frameworks:+ return None++ return FrameworksLinkable(+ libraries = ctx.attrs.libraries,+ frameworks = ctx.attrs.frameworks,+ )++def _has_darwin_linker(ctx: AnalysisContext) -> bool:+ return has_apple_toolchain(ctx) or ctx.attrs._cxx_toolchain[CxxToolchainInfo].linker_info.type == LinkerType("darwin")++def _get_apple_frameworks_linker_flags(ctx: AnalysisContext, linkables: list[[FrameworksLinkable, None]]) -> cmd_args:+ if not has_framework_linkable(linkables):+ return cmd_args()++ frameworks = set()+ libraries = set()+ for linkable in linkables:+ if not linkable:+ continue++ frameworks.update(linkable.frameworks)+ libraries.update(linkable.libraries)++ framework_names = [to_framework_name(framework) for framework in frameworks]+ unresolved_framework_paths = _get_non_sdk_unresolved_framework_directories(frameworks)++ expanded_frameworks_paths = _expand_sdk_framework_paths(ctx, unresolved_framework_paths)+ flags = _get_framework_search_path_flags(expanded_frameworks_paths)+ flags.add(get_framework_linker_args(ctx, framework_names))+ flags.add(cmd_args([_library_name(library) for library in libraries], format = "-l{}"))++ return flags++def get_framework_search_path_flags(ctx: AnalysisContext) -> cmd_args:+ if not _has_darwin_linker(ctx):+ return cmd_args()++ validate_sdk_frameworks(ctx.attrs.frameworks)+ unresolved_framework_dirs = _get_non_sdk_unresolved_framework_directories(ctx.attrs.frameworks)+ expanded_framework_dirs = _expand_sdk_framework_paths(ctx, unresolved_framework_dirs)+ return _get_framework_search_path_flags(expanded_framework_dirs)++def _get_framework_search_path_flags(frameworks: list[cmd_args]) -> cmd_args:+ flags = cmd_args()+ for directory in frameworks:+ flags.add(cmd_args(directory, format = "-F{}"))++ return flags++def _get_non_sdk_unresolved_framework_directories(frameworks: typing.Iterable) -> set[str]:+ # We don't want to include SDK directories as those are already added via `isysroot` flag in toolchain definition.+ # Adding those directly via `-F` will break building Catalyst applications as frameworks from support directory+ # won't be found and those for macOS platform will be used.+ directories = set()+ for framework in frameworks:+ directory = _non_sdk_unresolved_framework_directory(framework)+ if directory:+ directories.add(directory)++ return directories++def to_framework_name(framework_path: str) -> str:+ name, ext = paths.split_extension(paths.basename(framework_path))+ expect(ext == ".framework", "framework `{}` missing `.framework` suffix", framework_path)+ return name++def _library_name(library: str) -> str:+ if ":" in library:+ fail("Invalid library: {}. Use the field 'linker_flags' with $(location ) macro if you want to pass in a BUCK target for libraries.".format(library))++ name = paths.basename(library)+ if not name.startswith("lib"):+ fail("unexpected library: {}".format(library))+ return paths.split_extension(name[3:])[0]++def _expand_sdk_framework_paths(ctx: AnalysisContext, unresolved_framework_paths: set[str]) -> list[cmd_args]:+ # When _apple_toolchain is not available (e.g., cxx_library used as apple_library swap),+ # we cannot expand $PLATFORM_DIR or $SDKROOT paths. Skip those paths gracefully.+ if not hasattr(ctx.attrs, "_apple_toolchain"):+ return [cmd_args(p) for p in unresolved_framework_paths if not p.startswith("$")]+ return [_expand_sdk_framework_path(ctx, unresolved_framework_path) for unresolved_framework_path in unresolved_framework_paths]++def _expand_sdk_framework_path(ctx: AnalysisContext, framework_path: str) -> cmd_args:+ apple_toolchain_info = ctx.attrs._apple_toolchain[AppleToolchainInfo]+ path_expansion_map = {+ "$PLATFORM_DIR/": apple_toolchain_info.platform_path,+ "$SDKROOT/": apple_toolchain_info.sdk_path,+ }++ for trailing_path_variable, path_value in path_expansion_map.items():+ (before, separator, relative_path) = framework_path.partition(trailing_path_variable)+ if separator == trailing_path_variable:+ if len(before) > 0:+ fail("Framework symbolic path not anchored at the beginning, tried expanding `{}`".format(framework_path))+ if relative_path.count("$") > 0:+ fail("Framework path contains multiple symbolic paths, tried expanding `{}`".format(framework_path))+ if len(relative_path) == 0:+ fail(+ "Framework symbolic path contains no relative path to expand, tried expanding `{}`, relative path: `{}`, before: `{}`, separator `{}`".format(+ framework_path, relative_path, before, separator+ )+ )++ return cmd_args([path_value, relative_path], delimiter = "/")++ if framework_path.find("$") == 0:+ fail("Failed to expand framework path: {}".format(framework_path))++ return cmd_args(framework_path)++def _non_sdk_unresolved_framework_directory(framework_path: str) -> [str, None]:+ # We must only drop any framework paths that are part of the implicit+ # framework search paths in the linker + compiler, all other paths+ # must be expanded and included as part of the command.+ for implicit_search_path in _IMPLICIT_SDKROOT_FRAMEWORK_SEARCH_PATHS:+ if framework_path.find(implicit_search_path) == 0:+ return None+ return paths.dirname(framework_path)++def apple_build_link_args_with_deduped_flags(+ ctx: AnalysisContext,+ deps_merged_link_infos: list[MergedLinkInfo],+ frameworks_linkable: [FrameworksLinkable, None],+ link_strategy: LinkStrategy,+ transformation_spec_context: TransformationSpecContext | None,+ swiftmodule_linkable: [SwiftmoduleLinkable, None] = None,+ prefer_stripped: bool = False,+) -> LinkArgs:+ if _has_darwin_linker(ctx):+ frameworks_linkables = [x.frameworks[link_strategy] for x in deps_merged_link_infos] + [frameworks_linkable]+ swiftmodule_linkables = [x.swiftmodules[link_strategy] for x in deps_merged_link_infos] + [swiftmodule_linkable]+ link_info = _apple_link_info_from_linkables(+ ctx,+ frameworks_linkables,+ swiftmodule_linkables,+ )+ else:+ link_info = None++ return get_link_args_for_strategy(+ ctx.actions,+ ctx.label,+ get_cxx_toolchain_info(ctx).linker_info,+ deps_merged_link_infos,+ link_strategy,+ prefer_stripped,+ transformation_spec_context,+ additional_link_info = link_info,+ )++def apple_get_link_info_by_deduping_link_infos(+ ctx: AnalysisContext,+ infos: list[[LinkInfo, None]],+ framework_linkable: [FrameworksLinkable, None] = None,+ swiftmodule_linkable: [SwiftmoduleLinkable, None] = None,+) -> [LinkInfo, None]:+ if not _has_darwin_linker(ctx):+ return None++ # When building a framework or executable, all frameworks used by the statically-linked+ # deps in the subtree need to be linked.+ #+ # Without deduping, we've seen the linking step fail because the argsfile+ # exceeds the acceptable size by the linker.+ framework_linkables = _extract_framework_linkables(infos)+ if framework_linkable:+ framework_linkables.append(framework_linkable)++ swiftmodule_linkables = extract_swiftmodule_linkables(infos)+ swiftmodule_linkables.append(swiftmodule_linkable)++ return _apple_link_info_from_linkables(ctx, framework_linkables, swiftmodule_linkables)++def _extract_framework_linkables(link_infos: [list[LinkInfo], None]) -> list[FrameworksLinkable]:+ linkables = []+ for merged in link_infos:+ for linkable in merged.linkables:+ if isinstance(linkable, FrameworksLinkable):+ linkables.append(linkable)++ return linkables++def _apple_link_info_from_linkables(+ ctx: AnalysisContext, framework_linkables: list[[FrameworksLinkable, None]], swiftmodule_linkables: list[[SwiftmoduleLinkable, None]] = []+) -> [LinkInfo, None]:+ """+ Returns a LinkInfo for the frameworks, swiftmodules, and swiftruntimes or None if there's none of those.+ """+ framework_link_args = _get_apple_frameworks_linker_flags(ctx, framework_linkables)+ sdk_swift_module_link_args = get_swiftmodule_linker_flags(ctx, merge_swiftmodule_linkables(ctx, swiftmodule_linkables))++ return (+ LinkInfo(+ pre_flags = [framework_link_args, sdk_swift_module_link_args],+ )+ if (framework_link_args or sdk_swift_module_link_args)+ else None+ )
@@ -0,0 +1,223 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(":apple_bundle_destination.bzl", "AppleBundleDestination")+load(":apple_bundle_part.bzl", "AppleBundlePart")+load(":apple_bundle_utility.bzl", "get_bundle_min_target_version", "get_default_binary_dep", "get_product_name")+load(":apple_sdk.bzl", "get_apple_sdk_name")+load(+ ":apple_sdk_metadata.bzl",+ "AppleSdkMetadata", # @unused Used as a type+ "MacOSXCatalystSdkMetadata",+ "MacOSXSdkMetadata",+ "WatchOSSdkMetadata",+ "WatchSimulatorSdkMetadata",+ "get_apple_sdk_metadata_for_sdk_name",+)+load(":apple_target_sdk_version.bzl", "get_platform_name_for_sdk", "get_platform_version_for_sdk_version")+load(":apple_toolchain_types.bzl", "AppleToolchainInfo", "AppleToolsInfo")++UpdateOperations = enum("set", "insert")+MergeOperations = enum("merge")+RestrictedMergeOperations = enum("copy")++def process_info_plist(ctx: AnalysisContext, override_input: Artifact | None) -> AppleBundlePart:+ input = _preprocess_info_plist(ctx)+ output = ctx.actions.declare_output("Info.plist", has_content_based_path = False)+ additional_keys = _additional_keys_as_json_file(ctx)+ override_keys = _override_keys_as_json_file(ctx)+ process_plist(+ ctx = ctx,+ input = input,+ output = output.as_output(),+ override_input = override_input,+ additional_keys = additional_keys,+ override_keys = override_keys,+ )+ return AppleBundlePart(source = output, destination = AppleBundleDestination("metadata"))++def _get_plist_run_options() -> dict[str, bool]:+ return {+ # Output is deterministic, so can be cached+ "allow_cache_upload": True,+ # plist generation is cheap and fast, RE network overhead not worth it+ "prefer_local": True,+ }++def _preprocess_info_plist(ctx: AnalysisContext) -> Artifact:+ input = ctx.attrs.info_plist+ output = ctx.actions.declare_output("PreprocessedInfo.plist", has_content_based_path = False)+ substitutions_json = _plist_substitutions_as_json_file(ctx)+ apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]+ processor = apple_tools.info_plist_processor+ command = cmd_args([+ processor,+ "preprocess",+ "--input",+ input,+ "--output",+ output.as_output(),+ "--product-name",+ get_product_name(ctx),+ ])+ if substitutions_json != None:+ command.add(["--substitutions-json", substitutions_json])+ if getattr(ctx.attrs, "enforce_minimum_os_plist_key", False):+ sdk_name = get_apple_sdk_name(ctx)+ sdk_metadata = get_apple_sdk_metadata_for_sdk_name(sdk_name)+ command.add(["--enforce-minimum-os-plist-key", sdk_metadata.min_version_plist_info_key])++ ctx.actions.run(command, category = "apple_preprocess_info_plist", **_get_plist_run_options())+ return output++def _plist_substitutions_as_json_file(ctx: AnalysisContext) -> Artifact | None:+ info_plist_substitutions = ctx.attrs.info_plist_substitutions+ if not info_plist_substitutions:+ return None++ substitutions_json = ctx.actions.write_json("plist_substitutions.json", info_plist_substitutions, has_content_based_path = False)+ return substitutions_json++def process_plist(+ ctx: AnalysisContext,+ input: Artifact,+ output: OutputArtifact,+ override_input: Artifact | None = None,+ additional_keys: Artifact | None = None,+ override_keys: Artifact | None = None,+ action_id: [str, None] = None,+):+ apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]+ processor = apple_tools.info_plist_processor+ override_input_arguments = ["--override-input", override_input] if override_input != None else []+ additional_keys_arguments = ["--additional-keys", additional_keys] if additional_keys != None else []+ override_keys_arguments = ["--override-keys", override_keys] if override_keys != None else []+ command = cmd_args(+ [+ processor,+ "process",+ "--input",+ input,+ "--output",+ output,+ ]+ + override_input_arguments+ + additional_keys_arguments+ + override_keys_arguments+ )+ ctx.actions.run(command, category = "apple_process_info_plist", identifier = action_id or input.basename, **_get_plist_run_options())++def _additional_keys_as_json_file(ctx: AnalysisContext) -> Artifact:+ additional_keys = _info_plist_additional_keys(ctx)+ return ctx.actions.write_json("plist_additional.json", additional_keys, has_content_based_path = False)++def _info_plist_additional_keys(ctx: AnalysisContext) -> dict[str, typing.Any]:+ sdk_name = get_apple_sdk_name(ctx)+ platform_name = get_platform_name_for_sdk(sdk_name)+ sdk_metadata = get_apple_sdk_metadata_for_sdk_name(sdk_name)+ result = _extra_mac_info_plist_keys(sdk_metadata, ctx.attrs.extension)+ result["CFBundleSupportedPlatforms"] = sdk_metadata.info_plist_supported_platforms_values+ result["DTPlatformName"] = platform_name+ sdk_version = ctx.attrs._apple_toolchain[AppleToolchainInfo].sdk_version+ if sdk_version:+ platform_version = get_platform_version_for_sdk_version(+ sdk_name = sdk_name,+ sdk_version = sdk_version,+ )+ result["DTPlatformVersion"] = platform_version+ result["DTSDKName"] = platform_name + platform_version+ sdk_build_version = ctx.attrs._apple_toolchain[AppleToolchainInfo].sdk_build_version+ if sdk_build_version:+ result["DTPlatformBuild"] = sdk_build_version+ result["DTSDKBuild"] = sdk_build_version+ xcode_build_version = ctx.attrs._apple_toolchain[AppleToolchainInfo].xcode_build_version+ if xcode_build_version:+ result["DTXcodeBuild"] = xcode_build_version+ xcode_version = ctx.attrs._apple_toolchain[AppleToolchainInfo].xcode_version+ if xcode_version:+ result["DTXcode"] = xcode_version+ result[sdk_metadata.min_version_plist_info_key] = get_platform_version_for_sdk_version(+ sdk_name = sdk_name,+ sdk_version = get_bundle_min_target_version(ctx, get_default_binary_dep(ctx.attrs.binary)),+ )++ identify_build_system = ctx.attrs._info_plist_identify_build_system_default+ if ctx.attrs.info_plist_identify_build_system != None:+ identify_build_system = ctx.attrs.info_plist_identify_build_system+ if identify_build_system and ctx.attrs.extension == "app":+ # Only top-level .app bundle will contain special key.+ result["FBBuck2"] = True++ return result++def _extra_mac_info_plist_keys(sdk_metadata: AppleSdkMetadata, extension: str) -> dict[str, typing.Any]:+ if sdk_metadata.name == MacOSXSdkMetadata.name and extension != "xpc":+ return {+ "NSHighResolutionCapable": True,+ "NSSupportsAutomaticGraphicsSwitching": True,+ }+ else:+ return {}++def _override_keys_as_json_file(ctx: AnalysisContext) -> Artifact:+ override_keys = _info_plist_override_keys(ctx)+ return ctx.actions.write_json("plist_override.json", override_keys, has_content_based_path = False)++def _info_plist_override_keys(ctx: AnalysisContext) -> dict[str, typing.Any]:+ sdk_name = get_apple_sdk_name(ctx)+ result = {}+ if sdk_name == MacOSXSdkMetadata.name:+ if ctx.attrs.extension != "xpc":+ result["LSRequiresIPhoneOS"] = False+ elif sdk_name in [WatchOSSdkMetadata.name, WatchSimulatorSdkMetadata.name]:+ result["UIDeviceFamily"] = [4]+ result["WKApplication"] = True+ elif sdk_name not in [MacOSXCatalystSdkMetadata.name]:+ result["LSRequiresIPhoneOS"] = True+ return result++def apple_info_plist_impl(ctx: AnalysisContext) -> list[Provider]:+ """+ Implementation for the apple_info_plist rule.++ This rule takes a source plist file and processes it to create an output plist.+ """+ apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]+ processor = apple_tools.info_plist_processor++ input_plist = ctx.attrs.src+ output_plist = ctx.actions.declare_output("Info.plist", has_content_based_path = False)++ # Basic plist processing command+ command = cmd_args([+ processor,+ "process",+ "--input",+ input_plist,+ "--output",+ output_plist.as_output(),+ ])++ if ctx.attrs.xml:+ command = cmd_args(command, ["--output-xml"])++ # Add mutations if provided+ if ctx.attrs.mutations:+ mutations_file = ctx.actions.write_json("mutations.json", ctx.attrs.mutations, has_content_based_path = False)+ command.add("--mutations")+ command.add(mutations_file)+ for mutation in ctx.attrs.mutations:+ operation = mutation[0]+ if operation in MergeOperations.values() or operation in RestrictedMergeOperations.values():+ command.add(cmd_args(hidden = mutation[1]))++ ctx.actions.run(command, category = "apple_info_plist", identifier = input_plist.basename, **_get_plist_run_options())++ return [+ DefaultInfo(default_output = output_plist),+ ]
@@ -0,0 +1,68 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//utils:selects.bzl", "selects")++# `apple_bundle.info_plist_substitutions` might contain `CODE_SIGN_ENTITLEMENTS` key which (as per v1 documentation):+#+# > Code signing will embed entitlements pointed to by the entitlements_file arg in the bundle's apple_binary.+# > This is the preferred way to specify entitlements when building with Buck.+# > If the entitlements file is not present, it falls back to the CODE_SIGN_ENTITLEMENTS entry in info_plist_substitutions.+#+# In order to properly depend on this fallback entitlements file (and manipulate it) we have to convert this text entry into the source artifact.+# We only can do that on macro layer, hence the purpose of the following code.++_SOURCE_ROOT_PREFIX = "$(SOURCE_ROOT)/"+_CODE_SIGN_ENTITLEMENTS_KEY = "CODE_SIGN_ENTITLEMENTS"++def _find_first_variable(string: str) -> [(str, (str, str)), None]:+ """+ If variable like `$(FOO)` is not found in `string` returns `None`, else returns tuple+ with first element equal to variable name (e.g. `FOO`) and second element equal to tuple+ of part before and after this variable.+ """+ expansion_start = "$("+ expansion_end = ")"+ variable_start = string.find(expansion_start)+ if variable_start == -1:+ return None+ variable_end = string.find(expansion_end, variable_start)+ if variable_end == -1:+ fail("Expected variable expansion in string: `{}`".format(string))+ variable = string[variable_start + len(expansion_start) : variable_end - len(expansion_end) + 1]+ prefix = string[:variable_start]+ suffix = string[variable_end + 1 :]+ return (variable, (prefix, suffix))++def _expand_codesign_entitlements_path(info_plist_substitutions: dict[str, str | Select], path: str) -> str:+ path = path.strip()+ for _ in range(100):+ if path.startswith(_SOURCE_ROOT_PREFIX):+ path = path[len(_SOURCE_ROOT_PREFIX) :]+ maybe_variable = _find_first_variable(path)+ if not maybe_variable:+ return path+ (key, (prefix, suffix)) = maybe_variable+ maybe_value = info_plist_substitutions.get(key)+ if not maybe_value:+ fail("Expected to find value for `{}` in `info_plist_substitutions` dictionary `{}`".format(key, info_plist_substitutions))+ path = prefix + maybe_value + suffix+ fail("Too many iteration (loop might be present) to expand `{}` with substitutions `{}`".format(path, info_plist_substitutions))++def parse_codesign_entitlements(info_plist_substitutions: [dict | Select, None]) -> [str | Select, None]:+ if not info_plist_substitutions:+ return None+ return selects.apply(info_plist_substitutions, _parse_codesign_entitlements)++def _parse_codesign_entitlements(info_plist_substitutions: [dict, None]) -> [str | Select, None]:+ if not info_plist_substitutions:+ return None+ maybe_path = info_plist_substitutions.get(_CODE_SIGN_ENTITLEMENTS_KEY)+ if not maybe_path:+ return None+ return selects.apply(maybe_path, lambda maybe_path: _expand_codesign_entitlements_path(info_plist_substitutions, maybe_path))
@@ -0,0 +1,771 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "make_artifact_tset",+ "project_artifacts",+)+load("@prelude//:paths.bzl", "paths")+load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")+load("@prelude//apple:apple_dsym.bzl", "DSYM_SUBTARGET", "get_apple_dsym")+load("@prelude//apple:apple_stripping.bzl", "apple_strip_args")+load("@prelude//apple:xcassets_asset_symbols.bzl", "meta_xcassets_asset_symbol_usage_providers_and_subtargets")+# @oss-disable[end= ]: load("@prelude//apple/meta_only:apple_library_meta_validation.bzl", "apple_library_validate_for_meta_restrictions")+# @oss-disable[end= ]: load(+ # @oss-disable[end= ]: "@prelude//apple/meta_only:linker_outputs.bzl",+ # @oss-disable[end= ]: "extra_distributed_thin_lto_opt_outputs_merger",+ # @oss-disable[end= ]: "get_extra_linker_output_flags",+ # @oss-disable[end= ]: "get_extra_linker_outputs",+# @oss-disable[end= ]: )+load(+ "@prelude//apple/mockingbird:mockingbird_types.bzl",+ "MockingbirdLibraryInfo",+ "MockingbirdLibraryInfoTSet",+ "MockingbirdLibraryRecord",+ "MockingbirdSourcesInfo",+ "MockingbirdTargetType",+)+load(+ "@prelude//apple/swift:swift_compilation.bzl",+ "SwiftLibraryForDistributionOutput", # @unused Used as a type+ "compile_swift",+ "get_swift_anonymous_targets",+ "get_swift_debug_infos",+ "get_swift_dependency_info",+ "get_swift_pcm_uncompile_info",+ "get_swiftmodule_linkable",+)+load("@prelude//apple/swift:swift_helpers.bzl", "uses_explicit_modules")+load(+ "@prelude//apple/swift:swift_incremental_support.bzl",+ "get_uses_content_based_paths",+)+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftToolchainInfo")+load("@prelude//apple/swift:swift_types.bzl", "SWIFT_EXTENSION")+load(+ "@prelude//cxx:argsfiles.bzl",+ "CompileArgsfile", # @unused Used as a type+ "CompileArgsfiles",+)+load(+ "@prelude//cxx:compile_types.bzl",+ "AsmExtensions",+ "CxxSrcCompileCommand", # @unused Used as a type+ "DeclaredIndexStore",+ "IndexStoreFactory",+)+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")+load(+ "@prelude//cxx:cxx_library.bzl",+ "CxxLibraryOutput", # @unused Used as a type+ "cxx_library_parameterized",+)+load(+ "@prelude//cxx:cxx_library_utility.bzl",+ "cxx_attr_deps",+ "cxx_attr_exported_deps",+ "cxx_attr_link_style",+)+load(+ "@prelude//cxx:cxx_sources.bzl",+ "CxxSrcWithFlags", # @unused Used as a type+ "get_srcs_with_flags",+)+load(+ "@prelude//cxx:cxx_toolchain_types.bzl",+ "CxxToolchainInfo", # @unused Used as type+ "LinkerType",+)+load(+ "@prelude//cxx:cxx_types.bzl",+ "CxxRuleAdditionalParams",+ "CxxRuleConstructorParams",+ "CxxRuleProviderParams",+ "CxxRuleSubTargetParams",+ "xcode_data_enabled",+)+load("@prelude//cxx:cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload")+load("@prelude//cxx:headers.bzl", "cxx_attr_exported_headers", "cxx_attr_headers_list")+load(+ "@prelude//cxx:link_groups.bzl",+ "get_link_group_info",+)+load("@prelude//cxx:link_types.bzl", "ExtraLinkerOutputCategory")+load(+ "@prelude//cxx:linker.bzl",+ "LINKERS",+ "SharedLibraryFlagOverrides",+)+load(+ "@prelude//cxx:preprocessor.bzl",+ "CPreprocessor",+ "CPreprocessorInfo", # @unused Used as a type+ "EMPTY_CPREPROCESSOR",+)+load("@prelude//cxx:target_sdk_version.bzl", "get_unversioned_target_triple")+load("@prelude//graphql:graphql.bzl", "graphql_providers")+load(+ "@prelude//linking:link_info.bzl",+ "ExtraLinkerOutputs",+ "LibOutputStyle",+ "to_link_strategy",+)+load(+ "@prelude//linking:linkable_graph.bzl",+ "LinkableGraph",+)+load("@prelude//utils:arglike.bzl", "ArgLike")+load(+ "@prelude//utils:utils.bzl",+ "filter_and_map_idx",+)+load(":apple_bundle_types.bzl", "AppleBundleLinkerMapInfo", "AppleMinDeploymentVersionInfo")+load(":apple_error_handler.bzl", "apple_build_error_handler", "cxx_error_deserializer", "cxx_error_handler")+load(":apple_frameworks.bzl", "get_framework_search_path_flags")+load(":apple_library_types.bzl", "AppleLibraryInfo")+load(":apple_modular_utility.bzl", "MODULE_CACHE_PATH")+load(":apple_rpaths.bzl", "get_rpath_flags_for_library")+load(":apple_target_sdk_version.bzl", "get_min_deployment_version_for_node")+load(":apple_utility.bzl", "get_apple_cxx_headers_layout", "get_apple_stripped_attr_value_with_default_fallback", "get_module_name", "target_stats_header_name")+load(+ ":debug.bzl",+ "AppleDebuggableInfo",+ "DEBUGINFO_SUBTARGET",+)+load(":modulemap.bzl", "create_modulemap")+load(":resource_groups.bzl", "create_resource_graph")+load(":xcode.bzl", "apple_populate_xcode_attributes")+load(":xctest_swift_support.bzl", "xctest_swift_support_info")++AppleSharedLibraryMachOFileType = enum(+ # dynamically bound shared library file+ "dylib",+ # dynamically bound bundle file aka Mach-O bundle+ "bundle",+)++AppleLibraryAdditionalParams = record(+ # Name of the top level rule utilizing the apple_library rule.+ rule_type = str,+ # Extra flags to be passed to the linker.+ extra_exported_link_flags = field(list[ArgLike], []),+ # Extra flags to be passed to the Swift compiler.+ extra_swift_compiler_flags = field(list[ArgLike], []),+ # Linker flags that tell the linker to create shared libraries, overriding the default shared library flags.+ # e.g. when building Apple tests, we want to link with `-bundle` instead of `-shared` to allow+ # linking against the bundle loader.+ shared_library_flags = field([SharedLibraryFlagOverrides, None], None),+ # Function to use for setting Xcode attributes for the Xcode data sub target.+ populate_xcode_attributes_func = field(typing.Callable, apple_populate_xcode_attributes),+ # Define which sub targets to generate.+ generate_sub_targets = field(CxxRuleSubTargetParams, CxxRuleSubTargetParams()),+ # Define which providers to generate.+ generate_providers = field(CxxRuleProviderParams, CxxRuleProviderParams()),+ # Forces link group linking logic, even when there's no mapping. Link group linking+ # without a mapping is equivalent to statically linking the whole transitive dep graph.+ force_link_group_linking = field(bool, False),+)++AppleLibraryForDistributionInfo = provider(+ fields = {+ "module_name": str,+ "private_swiftinterface": [Artifact, None],+ "provider_type": provider_field(str, default = "AppleLibraryForDistributionInfo"),+ "swiftdoc": [Artifact, None],+ "swiftinterface": [Artifact, None],+ "target_triple": str,+ },+)++def apple_library_impl(ctx: AnalysisContext) -> [Promise, list[Provider]]:+ # @oss-disable[end= ]: apple_library_validate_for_meta_restrictions(ctx)++ def get_apple_library_providers(deps_providers) -> list[Provider]:+ shared_type = AppleSharedLibraryMachOFileType(ctx.attrs.shared_library_macho_file_type)+ if shared_type == AppleSharedLibraryMachOFileType("bundle"):+ shared_library_flags_overrides = SharedLibraryFlagOverrides(+ # When `-bundle` is used we can't use the `-install_name` args, thus we keep this field empty.+ shared_library_name_linker_flags_format = [],+ shared_library_flags = ["-bundle"] + get_rpath_flags_for_library(ctx),+ )+ elif shared_type == AppleSharedLibraryMachOFileType("dylib"):+ # Copying the default value and appending from cxx/linker.bzl+ linker = LINKERS[LinkerType("darwin")]+ shared_library_flags_overrides = SharedLibraryFlagOverrides(+ shared_library_name_linker_flags_format = linker.shared_library_name_linker_flags_format,+ shared_library_flags = linker.shared_library_flags + get_rpath_flags_for_library(ctx),+ )+ else:+ fail("Unsupported `shared_library_macho_file_type` attribute value: `{}`".format(shared_type))+ constructor_params = apple_library_rule_constructor_params_and_swift_providers(+ ctx,+ AppleLibraryAdditionalParams(+ rule_type = "apple_library",+ generate_sub_targets = CxxRuleSubTargetParams(xcode_data = xcode_data_enabled()),+ generate_providers = CxxRuleProviderParams(+ java_packaging_info = False,+ java_global_code_info = False,+ android_packageable_info = False,+ omnibus_root = False,+ # We generate a provider on our own, disable to avoid several providers of same type.+ cxx_resources_as_apple_resources = False,+ transitive_diagnostics = True,+ ),+ shared_library_flags = shared_library_flags_overrides,+ ),+ deps_providers,+ )+ output = cxx_library_parameterized(ctx, constructor_params)++ return output.providers + _make_mockingbird_library_info_provider(ctx) + graphql_providers(ctx)++ if uses_explicit_modules(ctx):+ providers = get_swift_anonymous_targets(ctx, get_apple_library_providers)+ else:+ providers = get_apple_library_providers([])+ if hasattr(ctx.attrs, "distribution_dep"):+ # Rule is apple_library_for_distribution+ providers = _create_apple_library_for_distribution_providers(ctx, providers)+ return providers++def _declare_index_store(actions: AnalysisActions, src_compile_cmd: CxxSrcCompileCommand) -> DeclaredIndexStore | None:+ """+ Declare index store output artifact upfront during analysis.+ This is called before the dynamic action is created.+ """+ if src_compile_cmd.src.extension in AsmExtensions.values():+ return None++ identifier = src_compile_cmd.src.short_path+ if src_compile_cmd.index != None:+ # Add a unique postfix if we have duplicate source files with different flags+ identifier = identifier + "_" + str(src_compile_cmd.index)+ filename_base = identifier++ index_store = actions.declare_output(paths.join("__indexstore__", filename_base, "index_store"), dir = True, has_content_based_path = False)+ return DeclaredIndexStore(+ output = index_store,+ filename_base = filename_base,+ )++def _compile_index_store(+ actions: AnalysisActions, target_label: Label, index_store_output: OutputArtifact, filename_base: str, toolchain: CxxToolchainInfo, compile_cmd: cmd_args+) -> None:+ """+ Compile index store inside the dynamic action.+ This is called after outputs are declared, during execution.+ """+ identifier = filename_base + " (index_store)"++ # Use remap_cwd.py to set -ffile-prefix-map, so we have paths relative to the+ # working directory.+ cmd = cmd_args(toolchain.internal_tools.remap_cwd)+ cmd.add(compile_cmd)++ # We use `-fsyntax-only` flag, so output will be not generated.+ # The output here is used for the identifier of the index unit file+ output_name = paths.join(+ target_label.cell,+ target_label.package,+ target_label.name,+ "{}.{}".format(filename_base, toolchain.linker_info.object_file_extension),+ )+ cmd.add(["-o", output_name])++ # Haven't use `-fdebug-prefix-map` for now, will use index-import to remap the path. But it's not ideal.+ cmd.add([+ "-fsyntax-only",+ "-index-ignore-system-symbols",+ "-index-store-path",+ index_store_output,+ ])++ actions.run(+ cmd,+ category = "apple_cxx_index_store",+ identifier = identifier,+ allow_cache_upload = False,+ local_only = True,+ )++def _make_apple_library_for_distribution_info_provider(+ ctx: AnalysisContext, swift_library_for_distribution: [None, SwiftLibraryForDistributionOutput]+) -> list[AppleLibraryForDistributionInfo]:+ return [+ AppleLibraryForDistributionInfo(+ target_triple = get_unversioned_target_triple(ctx).replace("macosx", "macos"),+ swiftinterface = swift_library_for_distribution.swiftinterface if swift_library_for_distribution else None,+ private_swiftinterface = swift_library_for_distribution.private_swiftinterface if swift_library_for_distribution else None,+ swiftdoc = swift_library_for_distribution.swiftdoc if swift_library_for_distribution else None,+ module_name = get_module_name(ctx),+ )+ ]++def _make_apple_library_info_provider(ctx: AnalysisContext, swift_header: [None, Artifact]) -> list[AppleLibraryInfo]:+ public_framework_headers = cxx_attr_headers_list(ctx, ctx.attrs.public_framework_headers, get_apple_cxx_headers_layout(ctx))+ all_deps = cxx_attr_deps(ctx) + cxx_attr_exported_deps(ctx)+ apple_library_infos = filter(None, [dep.get(AppleLibraryInfo) for dep in all_deps])++ public_framework_header_tset = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ artifacts = [header.artifact for header in public_framework_headers],+ children = [apple_library.public_framework_headers for apple_library in apple_library_infos],+ )++ return [+ AppleLibraryInfo(+ public_framework_headers = public_framework_header_tset,+ swift_header = swift_header,+ target = ctx.label,+ labels = ctx.attrs.labels,+ )+ ]++def _make_mockingbird_library_info_provider(ctx: AnalysisContext) -> list[MockingbirdLibraryInfo]:+ _, swift_sources = _filter_swift_srcs(ctx)++ if len(swift_sources) == 0:+ return []++ mockingbird_module_name = get_module_name(ctx)+ deps_mockingbird_infos = filter(None, [dep.get(MockingbirdLibraryInfo) for dep in cxx_attr_deps(ctx)])+ exported_deps_mockingbird_infos = filter(None, [dep.get(MockingbirdLibraryInfo) for dep in cxx_attr_exported_deps(ctx)])++ children = []+ dep_module_names = []+ exported_dep_module_names = []+ for info in deps_mockingbird_infos:+ dep_module_names.append(info.name)+ children.append(info.tset)++ for info in exported_deps_mockingbird_infos:+ exported_dep_module_names.append(info.name)+ children.append(info.tset)++ mockingbird_srcs_folder = ctx.actions.declare_output("mockingbird_srcs_" + ctx.attrs.name, dir = True, has_content_based_path = False)++ ctx.actions.symlinked_dir(+ mockingbird_srcs_folder,+ {source.file.basename: source.file for source in swift_sources},+ )++ mockingbird_record = MockingbirdLibraryRecord(+ name = mockingbird_module_name,+ srcs = [src.file for src in swift_sources],+ dep_names = dep_module_names,+ exported_dep_names = exported_dep_module_names,+ type = MockingbirdTargetType("library"),+ src_dir = mockingbird_srcs_folder,+ )++ mockingbird_tset = ctx.actions.tset(MockingbirdLibraryInfoTSet, value = mockingbird_record, children = children)++ return [+ MockingbirdLibraryInfo(+ name = mockingbird_module_name,+ tset = mockingbird_tset,+ )+ ]++def apple_library_rule_constructor_params_and_swift_providers(+ ctx: AnalysisContext, params: AppleLibraryAdditionalParams, deps_providers: list = [], is_test_target: bool = False+) -> CxxRuleConstructorParams:+ mockingbird_gen_sources = []+ if not "dummy_library" in ctx.attrs.labels:+ for dep in cxx_attr_deps(ctx) + cxx_attr_exported_deps(ctx):+ if MockingbirdSourcesInfo in dep:+ for src in dep[MockingbirdSourcesInfo].srcs:+ mockingbird_gen_sources.append(src)++ cxx_srcs, swift_srcs = _filter_swift_srcs(ctx, mockingbird_gen_sources)++ header_layout = get_apple_cxx_headers_layout(ctx)+ exported_hdrs = cxx_attr_exported_headers(ctx, header_layout)++ module_name = get_module_name(ctx)++ # First create a modulemap if necessary. This is required for importing+ # ObjC code in Swift so must be done before Swift compilation.+ if ctx.attrs.modular or swift_srcs:+ modulemap_name = module_name+ exported_modulemap_pre = (+ create_modulemap(+ ctx,+ name = modulemap_name,+ module_name = module_name,+ headers = exported_hdrs,+ swift_header = None,+ )+ if exported_hdrs+ else None+ )+ else:+ exported_modulemap_pre = None++ framework_search_paths_flags = get_framework_search_path_flags(ctx)+ swift_compile_result = compile_swift(+ ctx,+ swift_srcs,+ True, # parse_as_library+ deps_providers,+ module_name,+ exported_hdrs,+ exported_modulemap_pre,+ framework_search_paths_flags,+ params.extra_swift_compiler_flags,+ )+ swift_compile = swift_compile_result.swift_compilation+ objc_swift_interface = swift_compile_result.objc_swift_interface+ swift_object_files = swift_compile.object_files if swift_compile else []++ swift_pre = EMPTY_CPREPROCESSOR+ if swift_compile:+ # If we have Swift we export the extended modulemap that includes+ # the ObjC exported headers and the -Swift.h header.+ exported_pre = swift_compile.exported_pre++ # We also include the -Swift.h header to this libraries preprocessor+ # info, so that we can import it unprefixed in this module.+ swift_pre = swift_compile.pre+ elif exported_modulemap_pre:+ # Otherwise if this library is modular we export a modulemap of+ # the ObjC exported headers.+ exported_pre = exported_modulemap_pre+ else:+ exported_pre = None++ swift_dependency_info = swift_compile.dependency_info if swift_compile else get_swift_dependency_info(ctx, None, deps_providers, False)+ swift_debug_info = get_swift_debug_infos(+ ctx,+ swift_dependency_info,+ swift_compile,+ )++ swift_toolchain = ctx.attrs._apple_toolchain[SwiftToolchainInfo]+ if swift_toolchain and swift_toolchain.supports_relative_resource_dir:+ resource_dir_args = []+ else:+ # We have to use this hack to make compilation work when Clang modules+ # are enabled and using toolchains that don't support relative resource+ # directories correctly. The builtin headers will be embedded relative+ # to the CWD, so need to add . to be located correctly.+ resource_dir_args = ["-I."]++ modular_pre = CPreprocessor(+ uses_modules = ctx.attrs.uses_modules,+ modular_args = [+ "-fcxx-modules",+ "-fmodules",+ "-fmodule-name=" + get_module_name(ctx),+ "-fmodules-cache-path=" + MODULE_CACHE_PATH,+ ]+ + resource_dir_args,+ )++ contains_swift_sources = bool(swift_srcs)+ xctest_swift_support_provider = xctest_swift_support_info(ctx, contains_swift_sources, is_test_target)++ def additional_providers_factory(propagated_exported_preprocessor_info: [CPreprocessorInfo, None]) -> list[Provider]:+ # Expose `SwiftPCMUncompiledInfo` which represents the ObjC part of a target,+ # if a target also has a Swift part, the provider will expose the generated `-Swift.h` header.+ # This is used for Swift Explicit Modules, and allows compiling a PCM file out of the exported headers.+ swift_pcm_uncompile_info = get_swift_pcm_uncompile_info(+ ctx,+ propagated_exported_preprocessor_info,+ exported_pre,+ )+ providers = [swift_pcm_uncompile_info] if swift_pcm_uncompile_info else []+ providers.append(swift_dependency_info)+ providers.append(xctest_swift_support_provider)++ return providers++ validation_deps_outputs = get_validation_deps_outputs(ctx)+ if swift_compile:+ swift_objc_header = swift_compile.exported_swift_header+ swift_library_for_distribution_output = swift_compile.swift_library_for_distribution_output+ else:+ swift_objc_header = None+ swift_library_for_distribution_output = None++ extra_apple_providers = []+ if not is_test_target:+ extra_apple_providers = _make_apple_library_info_provider(ctx, swift_objc_header) + _make_apple_library_for_distribution_info_provider(+ ctx, swift_library_for_distribution_output+ )+ meta_xcassets_usage_providers, meta_xcassets_usage_subtargets = (+ ([], {}) if is_test_target else meta_xcassets_asset_symbol_usage_providers_and_subtargets(ctx, cxx_srcs, swift_srcs)+ )+ extra_apple_providers += meta_xcassets_usage_providers++ # Always provide a valid JSON object, so that tooling can depend on its existance+ modulemap_info_json = {"modulemap": exported_pre.modulemap_artifact} if (exported_pre and exported_pre.modulemap_artifact) else {}+ modulemap_info_json_file = ctx.actions.declare_output("modulemap-info.json", has_content_based_path = False)+ modulemap_info_json_cmd_args = ctx.actions.write_json(modulemap_info_json_file, modulemap_info_json, with_inputs = True, pretty = True)+ modulemap_info_providers = [DefaultInfo(default_output = modulemap_info_json_file, other_outputs = [modulemap_info_json_cmd_args])]++ subtargets = {+ "ast": [DefaultInfo(default_output = swift_compile_result.ast)],+ "modulemap-info": modulemap_info_providers,+ "objc-swift-interface": [objc_swift_interface],+ "swift-compilation-database": [DefaultInfo(default_output = None)],+ "swift-compile": [DefaultInfo(default_output = None)],+ "swiftinterface": [DefaultInfo(default_output = swift_compile_result.swiftinterface)],+ "swiftmodule": [DefaultInfo(default_output = None)],+ }+ subtargets.update(meta_xcassets_usage_subtargets)+ if swift_compile and swift_compile.compiled_underlying_pcm_artifact:+ subtargets["underlying-pcm"] = [DefaultInfo(default_output = swift_compile.compiled_underlying_pcm_artifact)]++ if swift_compile:+ subtargets["swift-compilation-database"] = [+ DefaultInfo(+ default_output = swift_compile.compilation_database.db,+ other_outputs = [swift_compile.compilation_database.other_outputs],+ ),+ ]+ subtargets["swift-compile"] = [+ DefaultInfo(+ default_output = swift_compile.object_files[0],+ other_outputs = swift_compile.object_files[1:],+ ),+ ]++ if swift_compile.output_map_artifact:+ subtargets["swift-output-file-map"] = [DefaultInfo(default_output = swift_compile.output_map_artifact)]++ if swift_compile.swift_module_map_artifact:+ subtargets["swift-module-map"] = [DefaultInfo(default_output = swift_compile.swift_module_map_artifact)]++ if swift_compile.swiftdeps:+ subtargets["swiftdeps"] = [+ DefaultInfo(+ default_output = swift_compile.swiftdeps[0],+ other_outputs = swift_compile.swiftdeps[1:],+ ),+ ]++ subtargets["swiftmodule"] = [DefaultInfo(default_output = swift_compile.swiftmodule)]+ subtargets["swift-objc-header"] = [DefaultInfo(default_output = swift_compile.exported_swift_header)]++ # Always provide the subtarget, so that clients don't need to handle conditional existence+ subtargets["swift.check"] = [DefaultInfo(default_output = swift_compile.typecheck_file if swift_compile else None)]++ swift_sources_list = ctx.actions.write(+ "swift-sources.txt",+ [s.file for s in swift_srcs],+ with_inputs = True,+ has_content_based_path = False,+ )+ subtargets["swift-sources"] = [DefaultInfo(default_output = swift_sources_list)]++ link_strategy = to_link_strategy(cxx_attr_link_style(ctx))+ link_group_info = get_link_group_info(+ ctx,+ filter_and_map_idx(LinkableGraph, cxx_attr_deps(ctx)),+ link_strategy,+ )++ return CxxRuleConstructorParams(+ rule_type = params.rule_type,+ is_test = (params.rule_type == "apple_test"),+ headers_layout = get_apple_cxx_headers_layout(ctx),+ extra_exported_link_flags = params.extra_exported_link_flags,+ extra_hidden = validation_deps_outputs,+ extra_link_input = swift_object_files,+ extra_link_input_has_external_debug_info = True,+ extra_preprocessors = [swift_pre, modular_pre],+ extra_exported_preprocessors = filter(None, [exported_pre]),+ srcs = cxx_srcs,+ target_stats_cycle_mode = "file",+ target_stats_module_name = get_module_name(ctx),+ target_stats_extra_srcs = {+ target_stats_header_name(header): header.artifact for header in cxx_attr_headers_list(ctx, ctx.attrs.headers, header_layout) + exported_hdrs+ },+ target_stats_swift_dot = swift_compile.modularization_dependency_graph if swift_compile else None,+ additional = CxxRuleAdditionalParams(+ srcs = swift_srcs,+ argsfiles = swift_compile.argsfiles if swift_compile else CompileArgsfiles(),+ # We need to add any swift modules that we include in the link, as+ # these will end up as `N_AST` entries that `dsymutil` will need to+ # follow.+ static_external_debug_info = swift_debug_info.static,+ shared_external_debug_info = swift_debug_info.shared,+ subtargets = subtargets,+ additional_providers_factory = additional_providers_factory,+ ),+ build_empty_so = hasattr(ctx.attrs, "distribution_dep"),+ output_style_sub_targets_and_providers_factory = _get_link_style_sub_targets_and_providers(+ extra_providers = extra_apple_providers,+ ),+ shared_library_flags = params.shared_library_flags,+ # apple_library's 'stripped' arg only applies to shared subtargets, or,+ # targets with 'preferred_linkage = "shared"'+ strip_executable = get_apple_stripped_attr_value_with_default_fallback(ctx),+ strip_args_factory = apple_strip_args,+ force_link_group_linking = params.force_link_group_linking,+ cxx_populate_xcode_attributes_func = lambda local_ctx, **kwargs: _xcode_populate_attributes(+ ctx = local_ctx, populate_xcode_attributes_func = params.populate_xcode_attributes_func, contains_swift_sources = contains_swift_sources, **kwargs+ ),+ generate_sub_targets = params.generate_sub_targets,+ generate_providers = params.generate_providers,+ # Some apple rules rely on `static` libs *not* following dependents.+ link_groups_force_static_follows_dependents = False,+ link_group_info = link_group_info,+ extra_linker_outputs_factory = _get_extra_linker_outputs,+ extra_linker_outputs_flags_factory = _get_extra_linker_outputs_flags,+ extra_distributed_thin_lto_opt_outputs_merger = _extra_distributed_thin_lto_opt_outputs_merger,+ swiftmodule_linkable = get_swiftmodule_linkable(swift_compile),+ compiler_flags = ctx.attrs.compiler_flags,+ lang_compiler_flags = ctx.attrs.lang_compiler_flags,+ preprocessor_flags = ctx.attrs.preprocessor_flags,+ lang_preprocessor_flags = ctx.attrs.lang_preprocessor_flags,+ swift_objc_header = swift_objc_header,+ error_handler = cxx_error_handler if cxx_error_deserializer(ctx) else apple_build_error_handler,+ index_store_factory = IndexStoreFactory(declare = _declare_index_store, compile = _compile_index_store),+ index_stores = [swift_compile.index_store] if swift_compile else None,+ modularization_dependency_graph = swift_compile.modularization_dependency_graph if swift_compile else None,+ extra_transitive_diagnostics = [swift_compile.typecheck_file] if swift_compile else [],+ extra_diagnostics = {"swift": swift_compile.typecheck_file} if swift_compile else None,+ allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs, get_cxx_toolchain_info(ctx).cxx_compiler_info.allow_cache_upload),+ precompiled_header = ctx.attrs.precompiled_header,+ prefix_header = ctx.attrs.prefix_header,+ use_content_based_paths = get_uses_content_based_paths(ctx),+ )++def _get_extra_linker_outputs(+ ctx: AnalysisContext, extra_linker_output_category: ExtraLinkerOutputCategory = ExtraLinkerOutputCategory("produced-during-local-link")+) -> ExtraLinkerOutputs:+ _ = ctx # buildifier: disable=unused-variable+ # @oss-disable[end= ]: return get_extra_linker_outputs(ctx, extra_linker_output_category)+ return ExtraLinkerOutputs() # @oss-enable++def _get_extra_linker_outputs_flags(+ ctx: AnalysisContext,+ outputs: dict[str, Artifact],+ extra_linker_output_category: ExtraLinkerOutputCategory = ExtraLinkerOutputCategory("produced-during-local-link"),+) -> list[ArgLike]:+ _ = ctx # buildifier: disable=unused-variable+ # @oss-disable[end= ]: return get_extra_linker_output_flags(ctx, outputs, extra_linker_output_category)+ return [] # @oss-enable++def _extra_distributed_thin_lto_opt_outputs_merger(ctx: AnalysisContext, outputs_to_bind: dict[str, Artifact], outputs_to_merge: list[dict[str, Artifact]]):+ # @oss-disable[end= ]: return extra_distributed_thin_lto_opt_outputs_merger(ctx, outputs_to_bind, outputs_to_merge)+ return # @oss-enable++def _filter_swift_srcs(ctx: AnalysisContext, additional_srcs: list = []) -> (list[CxxSrcWithFlags], list[CxxSrcWithFlags]):+ cxx_srcs = []+ swift_srcs = []+ for s in get_srcs_with_flags(ctx, additional_srcs):+ if s.file.extension == SWIFT_EXTENSION:+ swift_srcs.append(s)+ else:+ cxx_srcs.append(s)++ return cxx_srcs, swift_srcs++def _get_link_style_sub_targets_and_providers(extra_providers: list[Provider]) -> typing.Callable:+ def get_link_style_sub_targets_impl(+ output_style: LibOutputStyle, ctx: AnalysisContext, output: [CxxLibraryOutput, None]+ ) -> (dict[str, list[Provider]], list[Provider]):+ # We always propagate a resource graph regardless of link style or empty output+ resource_graph = create_resource_graph(+ ctx = ctx,+ labels = ctx.attrs.labels,+ deps = cxx_attr_deps(ctx),+ exported_deps = cxx_attr_exported_deps(ctx),+ # Shared libraries should not propagate their resources to rdeps,+ # they should only be contained in their frameworks apple_bundle.+ should_propagate = output_style != LibOutputStyle("shared_lib"),+ )++ if output_style != LibOutputStyle("shared_lib") or output == None:+ static_providers = [resource_graph] + extra_providers+ return ({}, static_providers)++ min_version = get_min_deployment_version_for_node(ctx)+ min_version_providers = [AppleMinDeploymentVersionInfo(version = min_version)]++ debug_info = project_artifacts(+ actions = ctx.actions,+ tsets = output.external_debug_info,+ )++ if get_apple_stripped_attr_value_with_default_fallback(ctx):+ dsym_executable = output.unstripped+ else:+ dsym_executable = output.default++ dsym_artifact = get_apple_dsym(+ ctx = ctx,+ executable = dsym_executable,+ debug_info = debug_info,+ action_identifier = dsym_executable.short_path,+ )+ debug_info_artifacts_manifest = ctx.actions.write(+ "debuginfo.artifacts",+ debug_info,+ with_inputs = True,+ has_content_based_path = False,+ )+ subtargets = {+ DSYM_SUBTARGET: [DefaultInfo(default_output = dsym_artifact)],+ DEBUGINFO_SUBTARGET: [DefaultInfo(default_output = debug_info_artifacts_manifest)],+ }++ providers = (+ [+ AppleDebuggableInfo(dsyms = [dsym_artifact], binaries = [dsym_executable], debug_info_tset = output.external_debug_info),+ resource_graph,+ ]+ + min_version_providers+ + extra_providers+ )++ if output.linker_map != None:+ subtargets["linker-map"] = [DefaultInfo(default_output = output.linker_map.map, other_outputs = [output.linker_map.binary])]+ providers += [AppleBundleLinkerMapInfo(linker_maps = [output.linker_map.map])]++ return (subtargets, providers)++ return get_link_style_sub_targets_impl++def _xcode_populate_attributes(+ ctx,+ srcs: list[CxxSrcWithFlags],+ argsfiles: dict[str, CompileArgsfile],+ populate_xcode_attributes_func: typing.Callable,+ contains_swift_sources: bool,+ **_kwargs,+) -> dict[str, typing.Any]:+ # Overwrite the product name+ data = populate_xcode_attributes_func(ctx, srcs = srcs, argsfiles = argsfiles, product_name = ctx.attrs.name, contains_swift_sources = contains_swift_sources)+ return data++def _create_apple_library_for_distribution_providers(ctx: AnalysisContext, providers: list[Provider]) -> list[Provider]:+ appleLibraryForDistributionInfo = ctx.attrs.distribution_dep.get(AppleLibraryForDistributionInfo)+ appleLibraryInfo = ctx.attrs.distribution_dep.get(AppleLibraryInfo)++ merged_providers = [appleLibraryForDistributionInfo]++ for provider in providers:+ if not getattr(provider, "provider_type", "") == "AppleLibraryForDistributionInfo":+ if getattr(provider, "provider_type", "") == "AppleLibraryInfo":+ merged_provider = AppleLibraryInfo(+ labels = provider.labels,+ public_framework_headers = appleLibraryInfo.public_framework_headers,+ swift_header = appleLibraryInfo.swift_header,+ target = provider.target,+ )+ merged_providers.append(merged_provider)+ else:+ merged_providers.append(provider)++ return merged_providers
@@ -0,0 +1,22 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactTSet",+)++AppleLibraryInfo = provider(+ fields = {+ "labels": list[str],+ "provider_type": provider_field(str, default = "AppleLibraryInfo"),+ "public_framework_headers": ArtifactTSet,+ "swift_header": [Artifact, None],+ "target": Label,+ },+)
@@ -0,0 +1,154 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple/user:apple_ipa_package.bzl", "make_apple_ipa_package_target")+load("@prelude//utils:selects.bzl", "selects")+load(":apple_bundle_config.bzl", "apple_bundle_config")+load(":apple_info_plist_substitutions_parsing.bzl", "parse_codesign_entitlements")+load(":apple_package_config.bzl", "apple_package_config")+load(":apple_resource_bundle.bzl", "make_resource_bundle_rule")+load(+ ":apple_rules_impl_utility.bzl",+ "APPLE_ARCHIVE_OBJECTS_LOCALLY_OVERRIDE_ATTR_NAME",+)++AppleBuckConfigAttributeOverride = record(+ name = field(str),+ section = field(str, default = "apple"),+ key = field(str),+ positive_values = field([list[str], list[bool]], default = ["True", "true"]),+ value_if_true = field([str, bool, None], default = True),+ value_if_false = field([str, bool, None], default = False),+ skip_if_false = field(bool, default = False),+)++APPLE_LINK_LIBRARIES_LOCALLY_OVERRIDE = AppleBuckConfigAttributeOverride(+ name = "link_execution_preference",+ key = "link_libraries_locally_override",+ value_if_true = "local",+ skip_if_false = True,+)++APPLE_LINK_LIBRARIES_REMOTELY_OVERRIDE = AppleBuckConfigAttributeOverride(+ name = "link_execution_preference",+ key = "link_libraries_remotely_override",+ value_if_true = "remote",+ skip_if_false = True,+)++_APPLE_LIBRARY_LOCAL_EXECUTION_OVERRIDES = [+ APPLE_LINK_LIBRARIES_LOCALLY_OVERRIDE,+ APPLE_LINK_LIBRARIES_REMOTELY_OVERRIDE,+ AppleBuckConfigAttributeOverride(name = APPLE_ARCHIVE_OBJECTS_LOCALLY_OVERRIDE_ATTR_NAME, key = "archive_objects_locally_override"),+]++# If both configs are set the last one wins+_APPLE_BINARY_EXECUTION_OVERRIDES = [+ AppleBuckConfigAttributeOverride(+ name = "link_execution_preference",+ key = "link_binaries_locally_override",+ value_if_true = "local",+ skip_if_false = True,+ ),+ AppleBuckConfigAttributeOverride(+ name = "link_execution_preference",+ key = "link_binaries_remotely_override",+ value_if_true = "remote",+ skip_if_false = True,+ ),+]++_APPLE_TEST_LOCAL_EXECUTION_OVERRIDES = [+ APPLE_LINK_LIBRARIES_LOCALLY_OVERRIDE,+ APPLE_LINK_LIBRARIES_REMOTELY_OVERRIDE,+]++def apple_macro_layer_set_bool_override_attrs_from_config(overrides: list[AppleBuckConfigAttributeOverride]) -> dict[str, Select]:+ attribs = {}+ for override in overrides:+ config_value = read_root_config(override.section, override.key, None)+ if config_value != None:+ config_is_true = config_value in override.positive_values+ if not config_is_true and override.skip_if_false:+ continue+ attribs[override.name] = select({+ "DEFAULT": override.value_if_true if config_is_true else override.value_if_false,+ # Do not set attribute value for host tools+ "ovr_config//platform/execution/constraints:execution-platform-transitioned": None,+ })+ return attribs++def apple_test_macro_impl(apple_test_rule, apple_resource_bundle_rule, **kwargs):+ kwargs.update(apple_bundle_config())+ kwargs.update(apple_macro_layer_set_bool_override_attrs_from_config(_APPLE_TEST_LOCAL_EXECUTION_OVERRIDES))++ # `extension` is used both by `apple_test` and `apple_resource_bundle`, so provide default here+ kwargs["extension"] = kwargs.pop("extension", "xctest")++ apple_test_rule(_resource_bundle = make_resource_bundle_rule(apple_resource_bundle_rule, **kwargs), **kwargs)++def apple_xcuitest_macro_impl(apple_xcuitest_rule, **kwargs):+ kwargs.update(apple_bundle_config())+ apple_xcuitest_rule(**kwargs)++def apple_bundle_macro_impl(apple_bundle_rule, apple_resource_bundle_rule, **kwargs):+ info_plist_substitutions = kwargs.get("info_plist_substitutions")+ kwargs.update(apple_bundle_config())+ codesign_entitlements = selects.apply(info_plist_substitutions, parse_codesign_entitlements)++ apple_bundle_rule(_codesign_entitlements = codesign_entitlements, _resource_bundle = make_resource_bundle_rule(apple_resource_bundle_rule, **kwargs), **kwargs)++def apple_library_macro_impl(apple_library_rule = None, **kwargs):+ kwargs.update(apple_macro_layer_set_bool_override_attrs_from_config(_APPLE_LIBRARY_LOCAL_EXECUTION_OVERRIDES))+ apple_library_rule(**kwargs)++def apple_metal_library_macro_impl(apple_metal_library_rule = None, **kwargs):+ if "exec_compatible_with" in kwargs:+ fail("Cannot set `exec_compatible_with` for apple_metal_library()")+ kwargs["exec_compatible_with"] = [+ # It's possible a buck2 daemon host machine has the correct Xcode+ # version selected but does not have the Metal toolchain installed.+ # Because this would lead to a build failure, we have to send actions+ # remotely where we it's guaranteed the Metal toolchain will be+ # installed alongside Xcode.+ "prelude//platforms:runs_only_remote",+ ]+ apple_metal_library_rule(**kwargs)++def apple_library_for_distribution_macro_impl(apple_library_for_distribution_rule = None, **kwargs):+ apple_library_macro_impl(apple_library_rule = apple_library_for_distribution_rule, **kwargs)++def prebuilt_apple_framework_macro_impl(prebuilt_apple_framework_rule = None, **kwargs):+ prebuilt_apple_framework_rule(**kwargs)++def apple_binary_macro_impl(apple_binary_rule = None, apple_universal_executable = None, **kwargs):+ kwargs.update(apple_macro_layer_set_bool_override_attrs_from_config(_APPLE_BINARY_EXECUTION_OVERRIDES))++ original_binary_name = kwargs.pop("name")++ if kwargs.pop("supports_universal", False):+ binary_name = original_binary_name + "ThinBinary"+ apple_universal_executable(+ name = original_binary_name,+ executable = ":" + binary_name,+ executable_name = original_binary_name,+ labels = kwargs.get("labels"),+ visibility = kwargs.get("visibility"),+ default_target_platform = kwargs.get("default_target_platform"),+ )+ else:+ binary_name = original_binary_name++ apple_binary_rule(name = binary_name, **kwargs)++def apple_package_macro_impl(apple_package_rule = None, apple_ipa_package_rule = None, **kwargs):+ kwargs.update(apple_package_config())+ apple_package_rule(_ipa_package = make_apple_ipa_package_target(apple_ipa_package_rule, **kwargs), **kwargs)++def apple_universal_executable_macro_impl(apple_universal_executable_rule = None, **kwargs):+ apple_universal_executable_rule(**kwargs)
@@ -0,0 +1,194 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")+load("@prelude//cxx:cxx_context.bzl", "get_cxx_platform_info")+load("@prelude//cxx:target_sdk_version.bzl", "get_versioned_metal_target_triple")+load(+ "@prelude//ide_integrations/xcode:data.bzl",+ "XCODE_DATA_SUB_TARGET",+ "XcodeDataInfoKeys",+ "generate_xcode_data",+)+load(":apple_resource_types.bzl", "AppleResourceDestination", "AppleResourceSpec")+load(":apple_target_sdk_version.bzl", "get_min_deployment_version_for_node")+load(":resource_groups.bzl", "create_resource_graph")++def apple_metal_library_impl(ctx: AnalysisContext) -> list[Provider]:+ metallib_archive = _compile_apple_metal_library(ctx)+ resource_spec = AppleResourceSpec(+ files = [metallib_archive],+ destination = AppleResourceDestination("resources"),+ )+ resource_graph = create_resource_graph(+ ctx = ctx,+ labels = ctx.attrs.labels,+ deps = [],+ exported_deps = [],+ resource_spec = resource_spec,+ )++ xcode_data_default_info, xcode_data_info = generate_xcode_data(ctx, "apple_metal_library", None, _xcode_populate_attributes)++ return [+ DefaultInfo(+ sub_targets = {+ XCODE_DATA_SUB_TARGET: xcode_data_default_info,+ },+ default_output = metallib_archive,+ ),+ resource_graph,+ xcode_data_info,+ ]++# Versioning extracted from Metal spec https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf+_IOS_MIN_OS_TO_METAL_VERSION = {+ "10": "1.2",+ "11": "2.0",+ "12": "2.1",+ "13": "2.2",+ "14": "2.3",+ "15": "2.4",+ "16": "3.0",+ "17": "3.1",+ "18": "3.2",+ "26": "4.0",+ "8": "1.0",+ "9": "1.1",+}++_MACOS_MIN_OS_TO_METAL_VERSION = {+ "10.11": "1.1",+ "10.12": "1.2",+ "10.13": "2.0",+ "10.14": "2.1",+ "10.15": "2.2",+ "11": "2.3",+ "12": "2.4",+ "13": "3.0",+ "14": "3.1",+ "15": "3.2",+ "26": "4.0",+}++def _derive_metal_version_from_min_os_version(ctx: AnalysisContext, min_os_version: str) -> str | None:+ platform_info = get_cxx_platform_info(ctx)+ version_components = min_os_version.split(".")+ if "macosx" in platform_info.name:+ major = version_components[0]+ if major == "10":+ minor = version_components[1] if len(version_components) > 1 else "0"+ key = "{major}.{minor}".format(+ major = major,+ minor = minor,+ )+ else:+ key = major+ return _MACOS_MIN_OS_TO_METAL_VERSION.get(key)+ if "iphone" in platform_info.name or "maccatalyst" in platform_info.name:+ # Mac Catalyst uses iOS versioning numbers+ return _IOS_MIN_OS_TO_METAL_VERSION.get(version_components[0])+ return None++# Reference: `-std=` section in https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf+def _compute_metal_std_compiler_arg(ctx: AnalysisContext, min_os_version: str) -> list[str]:+ version = ctx.attrs.metal_version or _derive_metal_version_from_min_os_version(ctx, min_os_version)+ if version == None:+ return []++ if "." not in version:+ version = version + ".0"++ is_version_before_unification = version.startswith("1") or version.startswith("2")+ if is_version_before_unification:+ platform_info = get_cxx_platform_info(ctx)++ # Mac Catalyst, i.e., `maccatalyst`, is using iOS args+ is_mac = "macosx" in platform_info.name+ platform_name = "macos" if is_mac else "ios"+ return [+ "-std={platform}-metal{version}".format(+ platform = platform_name,+ version = version,+ )+ ]++ return ["-std=metal{version}".format(version = version)]++def _compile_apple_metal_library(ctx: AnalysisContext) -> Artifact:+ toolchain = ctx.attrs._apple_toolchain[AppleToolchainInfo]+ if toolchain.metal == None or toolchain.metallib == None:+ fail("apple_metal_library can only be built with the metal compiler available in the apple bundle toolchain")++ header_map = {}+ for header_artifact in ctx.attrs.headers:+ import_paths = [+ # Support including via both direct filename and relative-to-target path+ header_artifact.basename,+ header_artifact.short_path,+ ]+ for import_path in import_paths:+ if import_path in header_map:+ fail("Header file duplicate import path conflict: `{}`".format(import_path))+ header_map[import_path] = header_artifact++ header_symlink_tree = None+ if len(header_map):+ header_symlink_tree = ctx.actions.symlinked_dir(str(ctx.label.name) + "_header_symlink_tree", header_map, has_content_based_path = False)++ sysroot = ctx.attrs._apple_toolchain[AppleToolchainInfo].sdk_path+ air_files = []++ min_os_version = get_min_deployment_version_for_node(ctx)+ compile_std_arg = _compute_metal_std_compiler_arg(ctx, min_os_version)+ for metal_file in ctx.attrs.srcs:+ air_output = ctx.actions.declare_output(paths.replace_extension(ctx.attrs.name + "_" + metal_file.basename, ".air"), has_content_based_path = False)+ air_compile_cmd = cmd_args(toolchain.metal)+ air_compile_cmd.add("-target", get_versioned_metal_target_triple(ctx, min_os_version))+ air_compile_cmd.add(compile_std_arg)+ air_compile_cmd.add("-isysroot", sysroot)+ if header_symlink_tree:+ air_compile_cmd.add("-I", header_symlink_tree)+ air_compile_cmd.add("-c", metal_file)+ air_compile_cmd.add(ctx.attrs.metal_compiler_flags)+ air_compile_cmd.add("-o", air_output.as_output())+ ctx.actions.run(air_compile_cmd, category = "apple_metal_air_compile", identifier = "compile_" + ctx.attrs.name + "_" + metal_file.basename)+ air_files.append(air_output)++ if ctx.attrs.out != None:+ if not ctx.attrs.out.endswith(".metallib"):+ fail("Metal library output name must end in `.metallib`")+ output_name = ctx.attrs.out+ else:+ output_name = ctx.attrs.name + ".metallib"+ output = ctx.actions.declare_output(output_name, has_content_based_path = False)+ metallib_compile = cmd_args(toolchain.metallib)+ for air_file in air_files:+ metallib_compile.add(air_file)+ metallib_compile.add(ctx.attrs.metal_linker_flags)+ metallib_compile.add("-o", output.as_output())++ ctx.actions.run(+ metallib_compile,+ category = "apple_metallib_link",+ identifier = "link_metallib_" + ctx.attrs.name,+ # It's possible a local machine has the correct Xcode version selected+ # but does not have the Metal toolchain installed. Because this would+ # lead to a build failure, we have to send actions remotely where we+ # it's guaranteed the Metal toolchain will be installed alongside Xcode.+ prefer_remote = True,+ )++ return output++def _xcode_populate_attributes(ctx) -> dict[str, typing.Any]:+ return {+ XcodeDataInfoKeys.SRCS: ctx.attrs.srcs,+ XcodeDataInfoKeys.HEADERS: ctx.attrs.headers,+ }
@@ -0,0 +1,15 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# We use a fixed module cache location. This works around issues with+# multi-user setups with MobileOnDemand and allows us to share the+# module cache with Xcode, LLDB and arc focus.+#+# TODO(T123737676): This needs to be changed to use $TMPDIR in a+# wrapper for modular clang compilation.+MODULE_CACHE_PATH = "/tmp/buck-module-cache"
@@ -0,0 +1,100 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:prelude.bzl", "native")+load(+ "@prelude//platforms/apple:constants.bzl",+ "apple_sdks",+)+load("@prelude//platforms/apple:platforms.bzl", "config_backed_apple_target_platform", "get_default_target_platform_for_platform", "set_apple_platforms")+load("@prelude//platforms/apple:platforms_map.bzl", "APPLE_SDK_DEFAULT_PLATFORM_MAP")+load("@prelude//utils:buckconfig.bzl", "read")++def _apple_library(**kwargs):+ kwargs = _update_platforms(**kwargs)+ native.apple_library(**kwargs)++def _apple_asset_catalog(**kwargs):+ kwargs = _update_platforms(**kwargs)+ native.apple_asset_catalog(**kwargs)++def _apple_binary(**kwargs):+ kwargs = _update_platforms(**kwargs)+ native.apple_binary(**kwargs)++def _apple_bundle(**kwargs):+ kwargs = _update_platforms(**kwargs)+ native.apple_bundle(**kwargs)++def _apple_watchos_bundle(**kwargs):+ kwargs = _update_platforms(**kwargs)+ native.apple_watchos_bundle(**kwargs)++def _apple_package(**kwargs):+ kwargs = _update_platforms(**kwargs)+ native.apple_package(**kwargs)++def _apple_resource(**kwargs):+ kwargs = _update_platforms(**kwargs)+ native.apple_resource(**kwargs)++def _apple_test(**kwargs):+ kwargs = _update_platforms(**kwargs)+ native.apple_test(**kwargs)++def _apple_xcuitest(**kwargs):+ kwargs = _update_platforms(**kwargs)+ native.apple_xcuitest(**kwargs)++def _apple_xcframework(**kwargs):+ kwargs = _update_platforms(**kwargs)+ native.apple_xcframework(**kwargs)++def _update_platforms(**kwargs):+ sdk = kwargs.pop("sdk", apple_sdks.IOS)+ platform = _get_default_platform(sdk)++ default_target_platform = kwargs.pop("default_target_platform", None)+ base_config_backed_target_platform = kwargs.pop("config_backed_target_platform", None)++ if default_target_platform != None and base_config_backed_target_platform != None:+ name = kwargs.get("name", "UNKNOWN_TARGET")+ fail("{} has both a default_target_platform and a config_backed_target_platform, which is not allowed".format(name))++ supported_build_modes = kwargs.pop("supported_build_modes", None)++ if base_config_backed_target_platform != None:+ default_target_platform = config_backed_apple_target_platform(base_config_backed_target_platform, platform, supported_build_modes = supported_build_modes)+ elif default_target_platform == None:+ default_target_platform = get_default_target_platform_for_platform(platform)++ if default_target_platform != None:+ kwargs["default_target_platform"] = default_target_platform++ kwargs = set_apple_platforms(platform, base_config_backed_target_platform, kwargs, supported_build_modes)++ return kwargs++def _get_default_platform(sdk: str) -> str:+ config_platform = read("cxx", "default_platform")+ if config_platform != None:+ return config_platform+ return APPLE_SDK_DEFAULT_PLATFORM_MAP.get(sdk)++apple_native = struct(+ apple_asset_catalog = _apple_asset_catalog,+ apple_binary = _apple_binary,+ apple_bundle = _apple_bundle,+ apple_watchos_bundle = _apple_watchos_bundle,+ apple_library = _apple_library,+ apple_package = _apple_package,+ apple_resource = _apple_resource,+ apple_test = _apple_test,+ apple_xcuitest = _apple_xcuitest,+ apple_xcframework = _apple_xcframework,+)
@@ -0,0 +1,144 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")+load("@prelude//xplugins:types.bzl", "XPluginsFunctionMappingManifestInfo")+load(+ ":apple_bundle_types.bzl",+ "AppleBundleInfo",+ "AppleBundleLinkerMapInfo",+ "AppleInfoPlistInfo",+ "ApplePackageExtension",+)+load(":apple_package_config.bzl", "IpaCompressionLevel")+load(":apple_package_types.bzl", "ApplePackageInfo")+load(+ ":debug.bzl",+ "AppleDebuggableInfo",+)++def apple_package_impl(ctx: AnalysisContext) -> list[Provider]:+ package_name = ctx.attrs.package_name if ctx.attrs.package_name else ctx.attrs.bundle.label.name+ package = ctx.actions.declare_output("{}.{}".format(package_name, ctx.attrs.ext), has_content_based_path = False)++ contents = ctx.attrs.bundle[DefaultInfo].default_outputs[0] if ctx.attrs.packager else _get_ipa_contents(ctx)+ if ctx.attrs.packager:+ process_ipa_cmd = cmd_args([+ ctx.attrs.packager[RunInfo],+ "--app-bundle-path",+ contents,+ "--output-path",+ package.as_output(),+ ctx.attrs.packager_args,+ ])+ category = "apple_package_make_custom"+ else:+ process_ipa_cmd = _get_default_package_cmd(+ ctx,+ contents,+ package.as_output(),+ )+ category = "apple_package_make"++ sub_targets = {+ "bundle": ctx.attrs.bundle.providers,+ }++ prepackaged_validators_artifacts = _get_prepackaged_validators_outputs(ctx, contents)+ if prepackaged_validators_artifacts:+ # Add the artifacts to packaging cmd so that they are run.+ process_ipa_cmd.add(cmd_args(hidden = prepackaged_validators_artifacts))+ sub_targets["prepackaged_validators"] = [+ DefaultInfo(default_outputs = prepackaged_validators_artifacts),+ ]++ ctx.actions.run(process_ipa_cmd, category = category)++ providers = [+ DefaultInfo(+ default_output = package,+ sub_targets = sub_targets,+ ),+ ApplePackageInfo(+ name = package_name,+ bundle_info = ctx.attrs.bundle[AppleBundleInfo],+ extension = ApplePackageExtension(ctx.attrs.ext),+ package = package,+ dsyms = ctx.attrs.bundle[AppleDebuggableInfo].dsyms,+ info_plist = ctx.attrs.bundle[AppleInfoPlistInfo].info_plist,+ linker_maps = ctx.attrs.bundle[AppleBundleLinkerMapInfo].linker_maps,+ unstripped_binaries = ctx.attrs.bundle[AppleDebuggableInfo].binaries,+ ),+ ]+ xplugins_function_mapping_manifest_info = ctx.attrs.bundle.get(XPluginsFunctionMappingManifestInfo)+ if xplugins_function_mapping_manifest_info:+ providers.append(xplugins_function_mapping_manifest_info)+ return providers++def _get_ipa_contents(ctx: AnalysisContext) -> Artifact:+ ipa_package_dep = ctx.attrs._ipa_package+ default_outputs = ipa_package_dep[DefaultInfo].default_outputs+ if len(default_outputs) != 1:+ fail("Expect exactly one output for .ipa package")+ return default_outputs[0]++def _get_default_package_cmd(ctx: AnalysisContext, unprocessed_ipa_contents: Artifact, output: OutputArtifact) -> cmd_args:+ apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]+ process_ipa_cmd = cmd_args([+ apple_tools.ipa_package_maker,+ "--ipa-contents-dir",+ unprocessed_ipa_contents,+ "--ipa-output-path",+ output,+ "--compression-level",+ _compression_level_arg(IpaCompressionLevel(ctx.attrs._ipa_compression_level)),+ ])++ return process_ipa_cmd++def _compression_level_arg(compression_level: IpaCompressionLevel) -> str:+ if compression_level == IpaCompressionLevel("none"):+ return "0"+ elif compression_level == IpaCompressionLevel("default"):+ return "6"+ elif compression_level == IpaCompressionLevel("min"):+ return "1"+ elif compression_level == IpaCompressionLevel("max"):+ return "9"+ else:+ fail("Unknown .ipa compression level: " + str(compression_level))++def _get_prepackaged_validators_outputs(ctx: AnalysisContext, prepackaged_contents: Artifact) -> list[Artifact]:+ if not ctx.attrs.prepackaged_validators:+ return []++ outputs = []+ for idx, validator in enumerate(ctx.attrs.prepackaged_validators):+ if type(validator) == "tuple":+ validator, validator_args = validator+ else:+ validator = validator+ validator_args = []++ output = ctx.actions.declare_output(validator.label.name + "_{}".format(idx), has_content_based_path = False)+ outputs.append(output)++ ctx.actions.run(+ cmd_args([+ validator[RunInfo],+ "--contents-dir",+ prepackaged_contents,+ "--output-path",+ output.as_output(),+ validator_args,+ ]),+ category = "prepackaged_validator",+ identifier = str(idx),+ )++ return outputs
@@ -0,0 +1,19 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++IpaCompressionLevel = enum(+ "min",+ "max",+ "default",+ "none",+)++def apple_package_config() -> dict[str, typing.Any]:+ return {+ "_ipa_compression_level": read_root_config("apple", "ipa_compression_level", IpaCompressionLevel("default").value),+ }
@@ -0,0 +1,22 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(":apple_bundle_types.bzl", "AppleBundleInfo", "ApplePackageExtension")++ApplePackageInfo = provider(+ fields = {+ "bundle_info": provider_field(AppleBundleInfo),+ "dsyms": provider_field(list[Artifact]),+ "extension": provider_field(ApplePackageExtension),+ "info_plist": provider_field(Artifact),+ "linker_maps": provider_field(list[Artifact]),+ "name": provider_field(str),+ "package": provider_field(Artifact),+ "unstripped_binaries": provider_field(list[Artifact]),+ },+)
@@ -0,0 +1,9 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++APPLE_PLATFORMS_KEY = "_apple_platforms"
@@ -0,0 +1,53 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:artifacts.bzl", "ArtifactGroupInfo")++AppleProvisioningProfileSourceInfo = record(+ # Individual profile files, populated when the source is a filegroup+ # that provides ArtifactGroupInfo. None means this source uses a+ # directory instead. An empty list means the source has no profiles.+ profiles = field([list[Artifact], None], None),+ # A directory containing profiles, populated when the source is a+ # genrule that only provides DefaultInfo (e.g. compressed profiles+ # decompressed at build time).+ directory = field([Artifact, None], None),+)++AppleProvisioningProfileSourcesInfo = provider(+ fields = {+ "sources": provider_field(list[AppleProvisioningProfileSourceInfo]),+ },+)++def apple_provisioning_profile_sources_impl(ctx: AnalysisContext) -> list[Provider]:+ sources = []+ for dep in ctx.attrs.sources:+ artifact_group_info = dep.get(ArtifactGroupInfo)+ if artifact_group_info:+ # This handles the case where a filegroup defines the set of profiles+ sources.append(+ AppleProvisioningProfileSourceInfo(+ profiles = artifact_group_info.artifacts,+ )+ )+ else:+ # This handles the case where a genrule produces a directory of profiles+ default_info = dep[DefaultInfo]+ if default_info.default_outputs:+ sources.append(+ AppleProvisioningProfileSourceInfo(+ directory = default_info.default_outputs[0],+ )+ )+ return [+ DefaultInfo(default_outputs = []),+ AppleProvisioningProfileSourcesInfo(+ sources = sources,+ ),+ ]
@@ -0,0 +1,77 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//ide_integrations/xcode:data.bzl",+ "XCODE_DATA_SUB_TARGET",+ "XcodeDataInfoKeys",+ "generate_xcode_data",+)+load(":apple_resource_types.bzl", "AppleResourceDestination", "AppleResourceSpec")+load(":resource_groups.bzl", "create_resource_graph")++def _xcode_populate_attributes(ctx) -> dict[str, typing.Any]:+ extra_xcode_files = []++ # ctx.attrs.files can contain Dependency+ for file in ctx.attrs.files:+ if isinstance(file, Dependency):+ extra_xcode_files.extend(file[DefaultInfo].default_outputs)+ else:+ extra_xcode_files.append(file)++ extra_xcode_files += ctx.attrs.dirs + ctx.attrs.variants++ # Named varients map a str to a set, so we need to add the values from the set+ for val in ctx.attrs.named_variants.values():+ extra_xcode_files.extend(val)++ data = {}+ if extra_xcode_files:+ data[XcodeDataInfoKeys.EXTRA_XCODE_FILES] = extra_xcode_files++ return data++def apple_resource_impl(ctx: AnalysisContext) -> list[Provider]:+ destination = ctx.attrs.destination or "resources"+ resource_spec = AppleResourceSpec(+ files = ctx.attrs.files,+ dirs = ctx.attrs.dirs,+ content_dirs = ctx.attrs.content_dirs,+ destination = AppleResourceDestination(destination),+ variant_files = ctx.attrs.variants or [],+ named_variant_files = ctx.attrs.named_variants or {},+ codesign_files_on_copy = ctx.attrs.codesign_on_copy,+ codesign_entitlements = ctx.attrs.codesign_entitlements,+ codesign_flags_override = ctx.attrs.codesign_flags_override,+ )++ # `files` can contain `apple_library()` which in turn can have `apple_resource()` deps+ file_deps = [file_or_dep for file_or_dep in ctx.attrs.files if isinstance(file_or_dep, Dependency)]+ deps = file_deps + ctx.attrs.resources_from_deps+ graph = create_resource_graph(+ ctx = ctx,+ labels = ctx.attrs.labels,+ deps = deps,+ exported_deps = [],+ resource_spec = resource_spec,+ )+ xcode_data_default_info, xcode_data_info = generate_xcode_data(ctx, "apple_resource", None, _xcode_populate_attributes)++ return [+ DefaultInfo(+ sub_targets = {+ "headers": [+ DefaultInfo(default_outputs = []),+ ],+ XCODE_DATA_SUB_TARGET: xcode_data_default_info,+ },+ ),+ graph,+ xcode_data_info,+ ]
@@ -0,0 +1,97 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# Splitting the resource compilation into another rule means we can have+# different exec platforms for the resource compilation and for the rest+# of the bundling process. This allows us to send resource compilations+# directly to RE.+#+# +-------------------------------------------------++# | apple_bundle() |+# | Exec Platform: macOS/Linux |+# | +--------+ +--------+ +------------------+ |+# +---+ binary +--+ deps +-+ _resource_bundle +---++# +--------+ +--------+ +------------------++# | | |+# | | |+# | | +---------------++# | | |+# | | |+# | | v+# | | +---------------------------------++# | +-----+ | apple_resource_bundle() |+# | | | Exec Platform: macOS-only |+# | | | +--------+ +--------+ |+# | | +-----+ binary +--+ deps +------++# | | +--------+ +--------++# | | | |+# | | | |+# | v | |+# | +-------------------+ | |+# | | Dependencies |<--------+-----------++# | +-------------------+ |+# | +-------------------+ |+# +------>| Binary |<--------++# +-------------------+++load("@prelude//apple:apple_rules_impl_utility.bzl", "get_apple_info_plist_build_system_identification_attrs")++_RESOURCE_BUNDLE_FIELDS = [+ "asset_catalogs_compilation_options",+ "binary",+ "copy_public_framework_headers",+ "default_target_platform",+ "deps",+ "extension",+ "ibtool_flags",+ "info_plist",+ "info_plist_substitutions",+ "module_map",+ "product_name",+ "privacy_manifest",+ "resource_group",+ "resource_group_map",+ "within_view",+ "visibility",+] + get_apple_info_plist_build_system_identification_attrs().keys()++def _is_resources_toolchain_enabled() -> bool:+ is_xplat_query_mode = read_root_config("mode", "is_xplat_mode_query") in ("True", "true")+ if is_xplat_query_mode:+ # Avoid returning buck2-only targets+ return False++ return read_root_config("apple", "resources_toolchain_enabled", "true").lower() == "true"++def make_resource_bundle_rule(apple_resource_bundle_rule, **kwargs) -> [None, str]:+ # The `apple_resource_bundle()` target will _always_ be Xcode-based, so resources can always be used+ # from there. `resources_toolchain_enabled` exists only as a killswitch (or for testing/debugging purposes).+ # By default, we consistently get all resources from `apple_resource_bundle()` target across all OSes and+ # toolchains.+ resources_toolchain_enabled = _is_resources_toolchain_enabled()+ if not resources_toolchain_enabled:+ return None++ resource_bundle_name = kwargs["name"] + "__ResourceBundle_Private"+ resource_bundle_kwargs = {+ "compatible_with": kwargs.get("compatible_with"),+ "exec_compatible_with": kwargs.get("exec_compatible_with"),+ "labels": ["generated"],+ "product_name_from_module_name": kwargs.get("product_name_from_module_name"),+ "skip_private_swiftinterface": kwargs.get("skip_private_swiftinterface"),+ "target_compatible_with": kwargs.get("target_compatible_with"),+ "_bundle_target_name": kwargs["name"],+ "_compile_resources_locally_override": kwargs["_compile_resources_locally_override"],+ }+ for field_name in _RESOURCE_BUNDLE_FIELDS:+ resource_bundle_kwargs[field_name] = kwargs.get(field_name)++ # TODO(T125269558): Remove usage of apple_resource_bundle() once we have exec groups.+ apple_resource_bundle_rule(name = resource_bundle_name, **resource_bundle_kwargs)++ return ":{}".format(resource_bundle_name)
@@ -0,0 +1,10 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++def apple_resource_dedupe_alias_impl(ctx: AnalysisContext) -> list[Provider]:+ return ctx.attrs.actual.providers
@@ -0,0 +1,70 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:artifacts.bzl", "ArtifactOutputs")+load(":apple_asset_catalog_types.bzl", "AppleAssetCatalogSpec")+load(":apple_core_data_types.bzl", "AppleCoreDataSpec")+load(":scene_kit_assets_types.bzl", "SceneKitAssetsSpec")+load(":xcassets_asset_symbols.bzl", "MetaXcassetsAssetSymbolSpec")++# Represents the values for the `destination` field of `apple_resource`+#+# Not every destination is meaningful for every bundle kind: like `loginitems`, `launchagents`+# only has a path in macOS application bundles, and resolves to the bundle root elsewhere.+AppleResourceDestination = enum(+ "executables",+ "extensionkit_extensions",+ "frameworks",+ "launchagents",+ "loginitems",+ "plugins",+ "resources",+ "xpcservices",+)++# Defines _where_ resources need to be placed in an `apple_bundle`+AppleResourceSpec = record(+ files = field(list[[Artifact, Dependency]], []),+ dirs = field(list[Artifact], []),+ content_dirs = field(list[Artifact], []),+ destination = AppleResourceDestination,+ variant_files = field(list[Artifact], []),+ # Map from locale to list of files for that locale, e.g.+ # `{ "ru.lproj" : ["Localizable.strings"] }`+ named_variant_files = field(dict[str, list[Artifact]], {}),+ codesign_files_on_copy = field(bool, False),+ codesign_entitlements = field(Artifact | None, None),+ codesign_flags_override = field(list[str] | None, None),+)++# Used when invoking `ibtool`, `actool`, `mapc` and `momc`+AppleResourceProcessingOptions = record(+ prefer_local = field(bool, False),+ prefer_remote = field(bool, False),+ allow_cache_upload = field(bool, False),+)++CxxResourceSpec = record(+ resources = field(dict[str, ArtifactOutputs], {}),+)++# A selected asset catalog with the resource-graph target that provided it.+SelectedAppleAssetCatalogSpec = record(+ asset_catalog_spec = field(AppleAssetCatalogSpec),+ xcassets_symbol_spec = field([MetaXcassetsAssetSymbolSpec, None], None),+ target = field(Label),+)++AppleResourceSelectionOutput = record(+ resource_specs = field(list[AppleResourceSpec]),+ asset_catalog_specs = field(list[AppleAssetCatalogSpec]),+ selected_asset_catalog_specs = field(list[SelectedAppleAssetCatalogSpec], []),+ core_data_specs = field(list[AppleCoreDataSpec]),+ scene_kit_assets_spec = field(list[SceneKitAssetsSpec]),+ cxx_resource_specs = field(list[CxxResourceSpec]),+)
@@ -0,0 +1,16 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(":apple_bundle_destination.bzl", "AppleBundleDestination")+load(+ ":apple_resource_types.bzl",+ "AppleResourceDestination", # @unused Used as a type+)++def apple_bundle_destination_from_resource_destination(res_destination: AppleResourceDestination) -> AppleBundleDestination:+ return AppleBundleDestination(res_destination.value)
@@ -0,0 +1,121 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//cxx:cxx_context.bzl", "get_cxx_platform_info")+load("@prelude//cxx:target_sdk_version.bzl", "get_target_sdk_version", "version_is_greater")++def _rpath_flags_for_paths(paths: list[str]) -> list[str]:+ return ["-Wl,-rpath," + p for p in paths]++_MACOS_BINARY_RPATHS = _rpath_flags_for_paths([+ # @executable_path = MyApp.app/Contents/MacOS+ "@executable_path/../Frameworks",+])++_MACOS_EXTENSION_RPATHS = _MACOS_BINARY_RPATHS + _rpath_flags_for_paths([+ # @executable_path = MyApp.app/Contents/PlugIns/MyExtension.appex/Contents/MacOS+ "@executable_path/../../../../Frameworks",+])++_MACOS_LIBRARY_RPATHS = _rpath_flags_for_paths([+ # @executable_path = MyApp.app/Contents/MacOS+ "@executable_path/../Frameworks",+ # @loader_path = MyApp.app/Contents/Frameworks/MyFramework.framework+ "@loader_path/Frameworks",+])++_MACOS_TEST_RPATHS = _rpath_flags_for_paths([+ # loader_path = MyApp.app/Contents/PlugIns/TestBundle.xctest/Contents/MacOS+ "@loader_path/../Frameworks",+ # executable_path = MyApp.app/Contents/MacOS+ "@executable_path/../Frameworks",+])++_IOS_BINARY_RPATHS = _rpath_flags_for_paths([+ # @executable_path = MyApp.app+ "@executable_path/Frameworks",+])++_IOS_EXTENSION_RPATHS = _IOS_BINARY_RPATHS + _rpath_flags_for_paths([+ # @executable_path = MyApp.app/PlugIns/MyExtension.appex+ "@executable_path/../../Frameworks",+])++_IOS_LIBRARY_RPATHS = _rpath_flags_for_paths([+ # @executable_path = MyApp.app+ "@executable_path/Frameworks",+ # @loader_path = MyApp.app/Frameworks/MyFramework.framework+ "@loader_path/Frameworks",+])++_IOS_TEST_RPATHS = _rpath_flags_for_paths([+ # loader_path = MyApp.app/PlugIns/TestBundle.xctest+ "@loader_path/Frameworks",+ # executable_path = MyApp.app+ "@executable_path/Frameworks",+])++_SWIFT_LIB_RPATHS = _rpath_flags_for_paths([+ # Required for concurrency backport compatibility pre iOS 15.0+ "/usr/lib/swift",+])++_CONCURRENCY_INTRODUCED_VERSIONS = {+ # https://github.com/DougGregor/swift/blob/ebd7b4975558ae00e7f42ea0597ad91ab05ca4ca/stdlib/private/StdlibUnittest/CMakeLists.txt#L26+ "appletvos": "15.0",+ "appletvsimulator": "15.0",+ "iphoneos": "15.0",+ "iphonesimulator": "15.0",+ "maccatalyst": "15.0",+ "macosx": "12.0",+ "visionos": "1.0",+ "visionsimulator": "1.0",+ "watchos": "8.0",+ "watchsimulator": "8.0",+}++def _get_platform_name(ctx: AnalysisContext) -> str:+ return get_cxx_platform_info(ctx).name.split("-")[0]++def _is_mac_binary(platform: str) -> bool:+ return platform.startswith("mac")++def _swift_lib_rpaths(ctx: AnalysisContext, platform: str) -> list[str]:+ target_sdk_version = get_target_sdk_version(ctx)+ concurrency_introduced_version = _CONCURRENCY_INTRODUCED_VERSIONS[platform]++ if version_is_greater(concurrency_introduced_version, target_sdk_version):+ return _SWIFT_LIB_RPATHS+ else:+ return []++def get_rpath_flags_for_apple_binary(ctx: AnalysisContext) -> list[str]:+ platform = _get_platform_name(ctx)+ if _is_mac_binary(platform):+ if ctx.attrs.application_extension:+ return _swift_lib_rpaths(ctx, platform) + _MACOS_EXTENSION_RPATHS+ else:+ return _swift_lib_rpaths(ctx, platform) + _MACOS_BINARY_RPATHS+ elif ctx.attrs.application_extension:+ return _swift_lib_rpaths(ctx, platform) + _IOS_EXTENSION_RPATHS+ else:+ return _swift_lib_rpaths(ctx, platform) + _IOS_BINARY_RPATHS++def get_rpath_flags_for_library(ctx: AnalysisContext) -> list[str]:+ platform = _get_platform_name(ctx)+ if _is_mac_binary(platform):+ return _swift_lib_rpaths(ctx, platform) + _MACOS_LIBRARY_RPATHS+ else:+ return _swift_lib_rpaths(ctx, platform) + _IOS_LIBRARY_RPATHS++def get_rpath_flags_for_tests(ctx: AnalysisContext) -> list[str]:+ platform = _get_platform_name(ctx)+ if _is_mac_binary(platform):+ return _swift_lib_rpaths(ctx, platform) + _MACOS_TEST_RPATHS+ else:+ return _swift_lib_rpaths(ctx, platform) + _IOS_TEST_RPATHS
@@ -0,0 +1,1909 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,+# but should be manually edited going forward. There may be some errors in+# the generated docs, and so those should be verified to be accurate and+# well-formatted (and then delete this TODO)++load("@prelude//:attrs_validators.bzl", "validation_common")+load("@prelude//:validation_deps.bzl", "VALIDATION_DEPS_ATTR_NAME", "VALIDATION_DEPS_ATTR_TYPE")+load("@prelude//apple:apple_common.bzl", "apple_common")+load("@prelude//apple:apple_info_plist.bzl", "MergeOperations", "RestrictedMergeOperations", "UpdateOperations", "apple_info_plist_impl")+load("@prelude//apple:apple_metal_library.bzl", "apple_metal_library_impl")+load("@prelude//apple:apple_platforms.bzl", "APPLE_PLATFORMS_KEY")+load("@prelude//apple:apple_provisioning_profile_sources.bzl", "apple_provisioning_profile_sources_impl")+load("@prelude//apple:apple_resource_dedupe_alias.bzl", "apple_resource_dedupe_alias_impl")+load("@prelude//apple:apple_resource_types.bzl", "AppleResourceDestination")+load(+ "@prelude//apple:apple_rules_impl_utility.bzl",+ "AppleFrameworkBundleModuleMapType",+ "apple_bundle_extra_attrs",+ "apple_test_extra_attrs",+ "get_apple_info_plist_build_system_identification_attrs",+)+load("@prelude//apple:apple_simulators.bzl", "apple_simulators_impl")+load("@prelude//apple:apple_static_archive.bzl", "apple_static_archive_impl")+load("@prelude//apple:apple_test_host_app_transition.bzl", "apple_test_host_app_transition")+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")+load("@prelude//apple:apple_tools.bzl", "apple_tools_impl")+load("@prelude//apple:apple_universal_executable.bzl", "apple_universal_executable_impl")+load("@prelude//apple:cxx_universal_executable.bzl", "cxx_universal_executable_impl")+load("@prelude//apple:resource_groups.bzl", "RESOURCE_GROUP_MAP_ATTR")+load("@prelude//apple/mockingbird:mockingbird_mock.bzl", "mockingbird_mock_attrs", "mockingbird_mock_impl")+load("@prelude//apple/swift:swift_incremental_support.bzl", "SwiftCompilationMode")+load("@prelude//apple/swift:swift_toolchain.bzl", "swift_toolchain_impl")+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftObjectFormat")+load("@prelude//apple/swift:swift_types.bzl", "SwiftMacroPlugin", "SwiftVersion")+load("@prelude//apple/user:apple_ipa_package.bzl", "apple_ipa_package_attribs", "apple_ipa_package_impl")+load("@prelude//apple/user:apple_macos_bundle.bzl", "apple_macos_bundle_impl")+load("@prelude//apple/user:apple_resource_bundle.bzl", "apple_resource_bundle_impl")+load("@prelude//apple/user:apple_resource_transition.bzl", "apple_resource_transition")+load("@prelude//apple/user:apple_selective_debugging.bzl", "SelectiveDebuggingJsonTypes", "apple_selective_debugging_impl")+load("@prelude//apple/user:apple_spm_package.bzl", "apple_spm_package_impl")+load("@prelude//apple/user:apple_watchos_bundle.bzl", "apple_watchos_bundle_impl")+load("@prelude//apple/user:apple_xcframework.bzl", "apple_xcframework_impl", "framework_split_transition")+load("@prelude//apple/user:cpu_split_transition.bzl", "cpu_split_transition")+load("@prelude//apple/user:macos_transition.bzl", "macos_transition")+load("@prelude//apple/user:resource_group_map.bzl", "resource_group_map_impl")+load("@prelude//apple/user:target_sdk_version_transition.bzl", "apple_test_target_sdk_version_transition", "target_sdk_version_transition")+load("@prelude//apple/user:watch_transition.bzl", "watch_transition")+load("@prelude//apple/validation:required_reasons_tools.bzl", "RequiredReasonsToolsInfo", "required_reasons_tools_impl")+load("@prelude//cxx:groups_types.bzl", "GroupFilterInfo", "Traversal")+load("@prelude//cxx:headers.bzl", "CPrecompiledHeaderInfo", "HeaderMode")+load("@prelude//cxx:link_groups_types.bzl", "LINK_GROUP_MAP_ATTR")+load("@prelude//decls:common.bzl", "CxxRuntimeType", "CxxSourceType", "HeadersAsRawHeadersMode", "LinkableDepType", "buck", "prelude_rule")+load("@prelude//decls:cxx_common.bzl", "cxx_common")+load("@prelude//decls:native_common.bzl", "native_common")+load("@prelude//decls:test_common.bzl", "test_common")+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")+load("@prelude//linking:execution_preference.bzl", "link_execution_preference_attr")+load("@prelude//linking:link_info.bzl", "LinkOrdering")+load("@prelude//linking:types.bzl", "Linkage")+load("@prelude//transitions:constraint_overrides.bzl", "constraint_overrides")+load("@prelude//utils:buckconfig.bzl", "read_bool")+load("@prelude//xplugins:attrs.bzl", "xplugins_common")+load(":apple_app_intents.bzl", "apple_app_intents_impl")+load(":apple_asset_catalog.bzl", "apple_asset_catalog_impl")+load(":apple_binary.bzl", "apple_binary_impl")+load(":apple_bundle.bzl", "apple_bundle_impl")+load(":apple_bundle_types.bzl", "AppleBundleInfo", "ApplePackageExtension")+load(":apple_core_data.bzl", "apple_core_data_impl")+load(":apple_library.bzl", "AppleSharedLibraryMachOFileType", "apple_library_impl")+load(":apple_package.bzl", "apple_package_impl")+load(":apple_package_config.bzl", "IpaCompressionLevel")+load(":apple_resource.bzl", "apple_resource_impl")+load(+ ":apple_rules_impl_utility.bzl",+ "APPLE_ARCHIVE_OBJECTS_LOCALLY_OVERRIDE_ATTR_NAME",+ "apple_xcuitest_extra_attrs",+ "get_apple_resources_toolchain_attr",+ "get_apple_xctoolchain_attr",+ "get_apple_xctoolchain_bundle_id_attr",+ "get_enable_library_evolution",+ "get_incremental_split_actions_attrs",+ "get_incremental_swiftmodule_action_attrs",+ "get_skip_swift_incremental_outputs_attrs",+ "get_swift_incremental_file_hashing_attrs",+ "get_swift_incremental_logging_attrs",+ "get_swift_incremental_remote_outputs_attrs",+)+load(":apple_test.bzl", "apple_test_impl")+load(":apple_toolchain.bzl", "apple_toolchain_impl")+load(":apple_xcuitest.bzl", "apple_xcuitest_impl")+load(":prebuilt_apple_framework.bzl", "prebuilt_apple_framework_impl")+load(":scene_kit_assets.bzl", "scene_kit_assets_impl")++AdditionalActions = ["pre_scheme_actions", "post_scheme_actions"]++AppleBundleExtension = ["app", "framework", "appex", "plugin", "bundle", "xctest", "dsym", "xpc", "prefpane", "qlgenerator"]++LaunchStyle = ["auto", "wait"]++SchemeActionType = ["build", "launch", "test", "profile", "analyze", "archive"]++WatchInterface = ["main", "complication", "dynamic_notification", "static_notification"]++SWIFT_VERSION_FEATURE_MAP = {+ "5": [],+ "6": [],+}++def apple_bundle_base_attrs():+ return (+ apple_common.product_name_from_module_name_arg()+ | apple_common.asset_catalogs_compilation_options_arg()+ | apple_common.info_plist_substitutions_arg()+ | buck.contacts_arg()+ | apple_common.default_platform_arg()+ | buck.labels_arg()+ | buck.licenses_arg()+ | apple_common.codesign_flags_arg()+ | apple_common.codesign_identity_arg()+ | apple_common.deps_arg()+ | apple_common.ibtool_flags_arg()+ | apple_common.product_name_arg()+ | apple_common.resource_group_arg()+ | apple_common.xcode_product_type_arg()+ | apple_common.skip_private_swiftinterface_arg()+ | {+ "extension": attrs.one_of(attrs.enum(AppleBundleExtension), attrs.string()),+ "incremental_bundling_enabled": attrs.option(attrs.bool(), default = None),+ "info_plist": attrs.source(),+ "resource_group_map": attrs.option(RESOURCE_GROUP_MAP_ATTR, default = None),+ "skip_copying_swift_stdlib": attrs.option(attrs.bool(), default = None),+ }+ )++def apple_bundle_default_attrs():+ attributes = {}+ attributes.update(apple_bundle_base_attrs())+ attributes.update(apple_bundle_extra_attrs())+ attributes.update({+ APPLE_PLATFORMS_KEY: attrs.dict(key = attrs.string(), value = attrs.dep(), sorted = False, default = {}),+ })+ return attributes++def apple_macos_bundle_attrs():+ attributes = apple_bundle_default_attrs()+ attributes.update({+ "bundle_type": attrs.string(default = "default"),+ })+ return attributes++def apple_watchos_bundle_attrs():+ attributes = apple_bundle_default_attrs()+ attributes.update({+ "bundle_type": attrs.string(default = "watchapp"),+ })+ return attributes++apple_asset_catalog = prelude_rule(+ name = "apple_asset_catalog",+ docs = """+ An `apple_asset_catalog()` rule contains resources stored in Apple asset catalog+ directories. This rule does not have any output on its own and can be built only as a dependency+ (either direct or transitive) of an `apple_bundle()` rule, in which case all `apple_asset_catalog()` rules+ that the bundle rule depends on are merged and placed into the final output bundle together.+ """,+ examples = """+ ```++ apple_asset_catalog(+ name = 'MyAssetCatalog',+ dirs = [+ 'MyResources.xcassets',+ ],+ )++ # A asset catalog with a app icon and launch image+ apple_asset_catalog(+ name = 'AssetCatalog',+ dirs = [ 'AssetCatalog.xcassets' ],+ app_icon = 'Icon',+ launch_image = 'LaunchImage',+ )++ ```+ """,+ further = None,+ attrs = (+ # @unsorted-dict-items+ buck.contacts_arg()+ | buck.labels_arg()+ | buck.licenses_arg()+ | {+ "app_icon": attrs.option(+ attrs.string(),+ default = None,+ doc = """+ An optional reference to a `.appiconset` containing a image set representing an+ application icon. (The extension itself should not be included.) This parameter+ may be specified at most once in a given `apple_bundle`'s transitive dependencies.+ """,+ ),+ "dirs": attrs.list(+ attrs.source(allow_directory = True),+ default = [],+ doc = """+ Set of paths of Apple asset catalogs contained by this rule. All paths have to end with the `.xcassets` extension and be compatible with the asset catalog format used by Xcode.+ """,+ ),+ "launch_image": attrs.option(+ attrs.string(),+ default = None,+ doc = """+ An optional reference to a `.launchimage` containing a image set representing an+ application launch image. (The extension itself should not be included.) This parameter+ may be specified at most once in a given `apple_bundle`'s transitive dependencies.+ """,+ ),+ }+ | apple_common.skip_universal_resource_dedupe_arg()+ ),+ impl = apple_asset_catalog_impl,+ cfg = apple_resource_transition,+)++apple_app_intents = prelude_rule(+ name = "apple_app_intents",+ docs = "An `apple_app_intents()` rule represents App Intents definitions for Apple platforms.",+ examples = None,+ further = None,+ attrs = (buck.contacts_arg() | buck.labels_arg() | buck.licenses_arg()),+ impl = apple_app_intents_impl,+)++apple_binary = prelude_rule(+ name = "apple_binary",+ docs = """+ An `apple_binary()` rule builds a native executable - such as an iOS or OSX app - from+ the supplied set of Objective-C/C++ source files and dependencies. It is similar to+ a `cxx_binary()` rule with which it shares many attributes. In addition+ to those common attributes, `apple_binary()` has a some additional attributes+ that are specific to binaries intended to be built using the Apple toolchain.+ Note, however, that `apple_binary()` and `cxx_binary()` differ+ in the way that they import header files, in order to better accommodate existing conventions.+ See the sections for the `headers` and `exported_headers` attributes for more details.++ Buck enables you to override components of the Apple toolchain with+ alternate tools, either from the Xcode search paths or from directories+ that you specify.+ See `.buckconfig`+ and `.buckconfig`+ for more information.+ """,+ examples = """+ ```++ apple_binary(+ name = 'MyBinary',+ deps = [+ ':MyLibrary',+ '//Libraries:AnotherLibrary',+ ],+ preprocessor_flags = ['-fobjc-arc'],+ headers = [+ 'MyHeader.h',+ ],+ srcs = [+ 'MySource.m',+ ],+ frameworks = [+ '$SDKROOT/System/Library/Frameworks/UIKit.framework',+ '$SDKROOT/System/Library/Frameworks/Foundation.framework',+ ],+ )++ ```+ """,+ further = None,+ attrs = (+ # @unsorted-dict-items+ cxx_common.srcs_arg()+ | apple_common.headers_arg()+ | {+ "entitlements_file": attrs.option(+ attrs.source(),+ default = None,+ doc = """+ An optional name of a plist file to be embedded in the binary. Some platforms like+ `iphonesimulator` require this to run properly.+ """,+ ),+ }+ | apple_common.apple_tools_arg()+ | apple_common.apple_toolchain_arg()+ | apple_common.exported_headers_arg()+ | apple_common.header_path_prefix_arg()+ | apple_common.frameworks_arg()+ | cxx_common.preprocessor_flags_arg()+ | cxx_common.exported_preprocessor_flags_arg(exported_preprocessor_flags_type = attrs.list(attrs.arg(), default = []))+ | cxx_common.compiler_flags_arg()+ | cxx_common.linker_extra_outputs_arg()+ | cxx_common.linker_flags_arg()+ | cxx_common.exported_linker_flags_arg()+ | native_common.link_style()+ | native_common.link_group_public_deps_label()+ | apple_common.target_sdk_version()+ | apple_common.extra_xcode_sources()+ | apple_common.extra_xcode_files()+ | apple_common.serialize_debugging_options_arg()+ | apple_common.uses_explicit_modules_arg()+ | apple_common.apple_sanitizer_compatibility_arg()+ | apple_common.executable_name_arg()+ | apple_common.info_plist_substitutions_arg()+ | cxx_common.supported_platforms_regex_arg()+ | buck.contacts_arg()+ | apple_common.default_platform_arg()+ | buck.labels_arg()+ | buck.licenses_arg()+ | apple_common.defaults_arg()+ | apple_common.deps_arg()+ | apple_common.devirt_enabled_arg()+ | apple_common.diagnostics_arg()+ | apple_common.enable_cxx_interop_arg()+ | cxx_common.exported_header_style_arg()+ | apple_common.fat_lto_arg()+ | cxx_common.header_namespace_arg()+ | cxx_common.include_directories_arg()+ | apple_common.libraries_arg()+ | apple_common.link_group_arg()+ | apple_common.minimum_os_version_arg()+ | apple_common.modular_arg()+ | apple_common.module_name_arg()+ | apple_common.module_requires_cxx_arg()+ | cxx_common.public_include_directories_arg()+ | cxx_common.public_system_include_directories_arg()+ | apple_common.sdk_modules_arg()+ | native_common.soname()+ | apple_common.static_library_basename_arg()+ | apple_common.strip_level_arg()+ | apple_common.swift_module_skip_function_bodies_arg()+ | apple_common.disable_generated_umbrella_header_arg()+ | apple_common.swift_package_name_arg()+ | apple_common.thin_lto_arg()+ | apple_common.use_submodules_arg()+ | apple_common.uses_cxx_explicit_modules_arg()+ | apple_common.uses_modules_arg()+ | {+ "application_extension": attrs.bool(default = False),+ "binary_linker_flags": attrs.list(attrs.arg(), default = []),+ "bridging_header": attrs.option(attrs.source(), default = None),+ "can_be_asset": attrs.option(attrs.bool(), default = None),+ "cxx_runtime_type": attrs.option(attrs.enum(CxxRuntimeType), default = None),+ "dist_thin_lto_codegen_flags": attrs.list(attrs.arg(), default = []),+ "enable_distributed_thinlto": attrs.bool(+ default = select({+ "DEFAULT": False,+ "config//build_mode/constraints:distributed-thin-lto[enabled]": True,+ })+ ),+ "enable_library_evolution": attrs.option(attrs.bool(), default = None),+ "exported_lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),+ "focused_list_target": attrs.option(attrs.dep(), default = None),+ "force_static": attrs.option(attrs.bool(), default = None),+ "headers_as_raw_headers_mode": attrs.option(attrs.enum(HeadersAsRawHeadersMode), default = None),+ "info_plist": attrs.option(attrs.source(), default = None),+ "lang_compiler_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),+ "lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),+ "link_execution_preference": link_execution_preference_attr(),+ "link_group_map": LINK_GROUP_MAP_ATTR,+ "link_ordering": attrs.option(attrs.enum(LinkOrdering.values()), default = None),+ "link_whole": attrs.option(attrs.bool(), default = None),+ "post_linker_flags": attrs.list(attrs.arg(), default = []),+ "precompiled_header": attrs.option(attrs.dep(providers = [CPrecompiledHeaderInfo]), default = None),+ "prefer_stripped_objects": attrs.bool(default = False),+ "preferred_linkage": attrs.enum(Linkage.values(), default = "any"),+ "prefix_header": attrs.option(attrs.source(), default = None),+ "raw_headers": attrs.set(attrs.source(), sorted = True, default = []),+ "reexport_all_header_dependencies": attrs.option(attrs.bool(), default = None),+ "sanitizer_runtime_enabled": attrs.option(attrs.bool(), default = None),+ "supports_merged_linking": attrs.option(attrs.bool(), default = None),+ "swift_compilation_mode": attrs.enum(SwiftCompilationMode.values(), default = "wmo"),+ "swift_compiler_flags": attrs.list(attrs.arg(), default = []),+ "swift_interface_compilation_enabled": attrs.bool(default = False),+ "swift_version": attrs.enum(SwiftVersion, default = SwiftVersion[0]),+ "_apple_xctoolchain": get_apple_xctoolchain_attr(),+ "_apple_xctoolchain_bundle_id": get_apple_xctoolchain_bundle_id_attr(),+ "_enable_library_evolution": get_enable_library_evolution(),+ "_swift_enable_testing": attrs.default_only(attrs.bool(default = False)),+ VALIDATION_DEPS_ATTR_NAME: VALIDATION_DEPS_ATTR_TYPE,+ }+ | buck.allow_cache_upload_arg()+ | validation_common.attrs_validators_arg()+ | constraint_overrides.attributes+ | get_skip_swift_incremental_outputs_attrs()+ | xplugins_common.debug_artifacts_arg+ ),+ impl = apple_binary_impl,+ cfg = target_sdk_version_transition,+)++apple_bundle = prelude_rule(+ name = "apple_bundle",+ docs = """+ An `apple_bundle()` rule takes an Apple binary and all of the resources and asset+ catalogs in the rule's transitive dependencies and generates a bundle containing all of those files.+ Optionally the generated bundle can also be signed using specified provisioning profiles.++ Code signing will embed entitlements pointed to by the `entitlements_file` arg in+ the bundle's `apple_binary`. This is the preferred way to specify entitlements+ when building with Buck.++ If the entitlements file is not present, it falls back to the `CODE_SIGN_ENTITLEMENTS` entry in+ `info_plist_substitutions`.++ If after these checks, an entitlements file is still not specified, it will be derived based+ on the entitlements of the selected provisioning profile. Provisioning profiles will be selected+ from profiles pointed to by `apple.provisioning_profile_search_path`, based on a+ non-expired profile that matches the bundle id and entitlements.++ Code signing will embed entitlements pointed to by the `CODE_SIGN_ENTITLEMENTS` entry in+ `info_plist_substitutions`. If an entitlements file is omitted, it will be derived based+ on the entitlements of the selected provisioning profile. Provisioning profiles will be selected+ from profiles pointed to by `apple.provisioning_profile_search_path`, based on a+ non-expired profile that matches the bundle id and entitlements.+ """,+ examples = """+ ```++ apple_bundle(+ name = 'AppBundle',+ binary = ':MyBinary',+ extension = 'app',+ info_plist = 'Info.plist',+ )++ ```++ ```++ # iOS app with embedded WatchOS 2.0 app/extension+ apple_bundle(+ name = 'DemoWatchAppExtension',+ binary = ':DemoWatchAppExtensionBinary',+ extension = 'appex',+ info_plist = 'WatchExtension/Resources/Info.plist',+ )++ apple_bundle(+ name = 'DemoWatchApp',+ binary = ':DemoWatchAppBinary',+ deps = [':DemoWatchAppResources', ':DemoWatchAppExtension'],+ extension = 'app',+ info_plist = 'WatchApplication/Info.plist',+ )++ apple_bundle(+ name = 'DemoApp',+ binary = ':DemoAppBinary',+ deps = [':DemoWatchApp#watch'],+ extension = 'app',+ info_plist = 'Info.plist',+ )++ ```++ ```++ # iOS app using safeAreaInsets delivering to iOS 9.x+ apple_bundle(+ name = 'DemoIBApp',+ binary = ':DemoIBAppBinary',+ deps = [':DemoIBAppResources'],+ extension = 'app',+ ibtool_flags = ["--minimum-deployment-target", "9.0"],+ info_plist = 'Info.plist',+ )++ ```+ """,+ further = None,+ attrs = (+ # @unsorted-dict-items+ {+ "deps": attrs.list(+ attrs.dep(),+ default = [],+ doc = """+ A list of dependencies of this bundle as build targets. You can embed application+ extensions by specifying the extension's bundle target. To include a WatchKit app, append the+ flavor `#watch` to the target specification. Buck will automatically substitute the appropriate+ platform flavor (either `watchsimulator` or `watchos`) based on the parent.+ """,+ ),+ "product_name": attrs.option(+ attrs.string(),+ default = None,+ doc = """+ The name of the resulting bundle and binary. The setting behaves like PRODUCT\\_NAME Xcode build setting.+ For example, if your rule is named "MyApp" and extension is "app", by default buck will generate MyApp.app bundle.+ But if you will set product name to "SuperApp", bundle will get "SuperApp.app" name.+ """,+ ),+ "extension": attrs.one_of(+ attrs.enum(AppleBundleExtension),+ attrs.string(),+ doc = """+ The extension of the generated bundle. For example `'app'` for an application bundle+ or `'appex'` for an application extension bundle.+ """,+ ),+ "binary": attrs.option(+ attrs.dep(),+ default = None,+ doc = """+ A `build target` identifying+ an `apple_binary()` rule or+ an `apple_library()` or `apple_libary_for_distribution()` rule whose output will+ be used as the main executable binary of the generated bundle. The required rule type depends+ on the value in the `extension` attribute. For example, application bundles expect+ a binary (e.g. `'//Apps/MyApp:MyApp'`), application extension bundles expect a shared+ library (e.g. `'//Libraries/MyLibrary:MyLibrary#shared'`).+ """,+ ),+ }+ | apple_common.info_plist_arg()+ | apple_common.info_plist_substitutions_arg()+ | apple_common.privacy_manifest_arg()+ | apple_common.product_name_from_module_name_arg()+ | apple_common.asset_catalogs_compilation_options_arg()+ | buck.contacts_arg()+ | apple_common.default_platform_arg()+ | buck.labels_arg()+ | buck.licenses_arg()+ | apple_common.codesign_flags_arg()+ | apple_common.codesign_identity_arg()+ | apple_common.resource_group_arg()+ | apple_common.xcode_product_type_arg()+ | apple_common.skip_private_swiftinterface_arg()+ | {+ "ibtool_flags": attrs.option(+ attrs.list(attrs.string()),+ default = None,+ doc = """+ List of flags to be passed to ibtool during interface builder file compilation.+ """,+ ),+ "incremental_bundling_enabled": attrs.option(attrs.bool(), default = None),+ "platform_binary": attrs.option(attrs.list(attrs.tuple(attrs.regex(), attrs.dep())), default = None),+ "resource_group_map": attrs.option(RESOURCE_GROUP_MAP_ATTR, default = None),+ "skip_copying_swift_stdlib": attrs.option(attrs.bool(), default = None),+ }+ | apple_bundle_extra_attrs()+ ),+ impl = apple_bundle_impl,+ cfg = target_sdk_version_transition,+)++apple_library = prelude_rule(+ name = "apple_library",+ docs = """+ An `apple_library()` rule represents a set of Objective-C/C++/Swift+ source files and is similar to a `cxx_library()` rule with which it shares many+ attributes. In addition to those common attributes, `apple_library()` has a some additional attributes+ that are specific to binaries intended to be built using the Apple toolchain.+ Note, however, that `apple_library()` and `cxx_library()` differ+ in the way that they import header files, in order to better accommodate existing conventions.+ See the sections for the `headers` and `exported_headers` attributes for more details.++ Buck enables you to override components of the Apple toolchain with+ alternate tools, either from the Xcode search paths or from directories+ that you specify.+ See `.buckconfig`+ and `.buckconfig`+ for more information.+ """,+ examples = """+ ```++ apple_library(+ name = 'MyLibrary',+ deps = [+ ':OtherLibrary',+ '//Libraries:YetAnotherLibrary',+ ],+ preprocessor_flags = ['-fobjc-arc'],+ headers = [+ 'MyHeader.h',+ ],+ srcs = [+ 'MySource.m',+ 'MySource.swift',+ ],+ frameworks = [+ '$SDKROOT/System/Library/Frameworks/UIKit.framework',+ '$SDKROOT/System/Library/Frameworks/Foundation.framework',+ ],+ )++ ```+ """,+ further = None,+ attrs = (+ # @unsorted-dict-items+ cxx_common.srcs_arg()+ | apple_common.headers_arg()+ | apple_common.exported_headers_arg()+ | apple_common.header_path_prefix_arg()+ | cxx_common.header_namespace_arg()+ | apple_common.frameworks_arg()+ | cxx_common.preprocessor_flags_arg()+ | cxx_common.exported_preprocessor_flags_arg(exported_preprocessor_flags_type = attrs.list(attrs.arg(), default = []))+ | cxx_common.compiler_flags_arg()+ | cxx_common.linker_extra_outputs_arg()+ | cxx_common.linker_flags_arg()+ | cxx_common.exported_linker_flags_arg()+ | apple_common.target_sdk_version()+ | native_common.preferred_linkage(preferred_linkage_type = attrs.option(attrs.enum(Linkage.values()), default = None))+ | native_common.link_style()+ | native_common.link_whole(link_whole_type = attrs.option(attrs.bool(), default = None))+ | cxx_common.reexport_all_header_dependencies_arg()+ | cxx_common.exported_deps_arg()+ | cxx_common.raw_headers_arg()+ | cxx_common.include_directories_arg()+ | cxx_common.public_include_directories_arg()+ | cxx_common.public_system_include_directories_arg()+ | cxx_common.raw_headers_as_headers_mode_arg()+ | apple_common.extra_xcode_sources()+ | apple_common.extra_xcode_files()+ | apple_common.serialize_debugging_options_arg()+ | apple_common.uses_explicit_modules_arg()+ | apple_common.meta_apple_library_validation_enabled_arg()+ | apple_common.executable_name_arg()+ | apple_common.info_plist_substitutions_arg()+ | cxx_common.supported_platforms_regex_arg()+ | apple_common.apple_tools_arg()+ | apple_common.apple_toolchain_arg()+ | validation_common.attrs_validators_arg()+ | buck.contacts_arg()+ | apple_common.default_platform_arg()+ | buck.labels_arg()+ | buck.licenses_arg()+ | apple_common.defaults_arg()+ | apple_common.deps_arg()+ | apple_common.devirt_enabled_arg()+ | apple_common.diagnostics_arg()+ | apple_common.enable_cxx_interop_arg()+ | cxx_common.exported_header_style_arg()+ | apple_common.fat_lto_arg()+ | apple_common.libraries_arg()+ | apple_common.link_group_arg()+ | apple_common.minimum_os_version_arg()+ | apple_common.modular_arg()+ | apple_common.module_name_arg()+ | apple_common.module_requires_cxx_arg()+ | apple_common.sdk_modules_arg()+ | native_common.soname()+ | apple_common.static_library_basename_arg()+ | apple_common.strip_level_arg()+ | apple_common.swift_module_skip_function_bodies_arg()+ | apple_common.disable_generated_umbrella_header_arg()+ | apple_common.swift_package_name_arg()+ | apple_common.thin_lto_arg()+ | apple_common.use_submodules_arg()+ | apple_common.uses_cxx_explicit_modules_arg()+ | apple_common.uses_modules_arg()+ | {+ "bridging_header": attrs.option(attrs.source(), default = None),+ "can_be_asset": attrs.option(attrs.bool(), default = None),+ "cxx_runtime_type": attrs.option(attrs.enum(CxxRuntimeType), default = None),+ "dist_thin_lto_codegen_flags": attrs.list(attrs.arg(), default = []),+ "enable_distributed_thinlto": attrs.bool(+ default = select({+ "DEFAULT": False,+ "config//build_mode/constraints:distributed-thin-lto[enabled]": True,+ })+ ),+ "enable_library_evolution": attrs.option(attrs.bool(), default = None),+ "exported_lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),+ "exported_post_linker_flags": attrs.list(attrs.arg(), default = []),+ "focused_list_target": attrs.option(attrs.dep(), default = None),+ "force_static": attrs.option(attrs.bool(), default = None),+ "has_content_based_path": attrs.option(attrs.bool(), default = None),+ "header_mode": attrs.option(attrs.enum(HeaderMode.values()), default = None),+ "headers_as_raw_headers_mode": attrs.option(attrs.enum(HeadersAsRawHeadersMode), default = None),+ "info_plist": attrs.option(attrs.source(), default = None),+ "lang_compiler_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),+ "lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),+ "link_execution_preference": link_execution_preference_attr(),+ "link_group_map": LINK_GROUP_MAP_ATTR,+ "link_ordering": attrs.option(attrs.enum(LinkOrdering.values()), default = None),+ "post_linker_flags": attrs.list(attrs.arg(), default = []),+ "precompiled_header": attrs.option(attrs.dep(providers = [CPrecompiledHeaderInfo]), default = None),+ "preferred_linkage": attrs.enum(Linkage.values(), default = "any"),+ "prefix_header": attrs.option(attrs.source(), default = None),+ "public_framework_headers": attrs.named_set(attrs.source(), sorted = True, default = []),+ # Mach-O file type for binary when the target is built as a shared library.+ "shared_library_macho_file_type": attrs.enum(AppleSharedLibraryMachOFileType.values(), default = "dylib"),+ "supports_header_symlink_subtarget": attrs.bool(default = False),+ "supports_merged_linking": attrs.option(attrs.bool(), default = None),+ "supports_shlib_interfaces": attrs.bool(default = True),+ "swift_compilation_mode": attrs.enum(SwiftCompilationMode.values(), default = "wmo"),+ "swift_compiler_flags": attrs.list(attrs.arg(), default = []),+ "swift_dump_ast_subtarget_enabled": attrs.bool(default = read_bool("apple", "swift_dump_ast_subtarget_enabled", default = False, root_cell = True)),+ "swift_interface_compilation_enabled": attrs.bool(default = True),+ "swift_macro_deps": attrs.list(attrs.plugin_dep(kind = SwiftMacroPlugin), default = []),+ "swift_version": attrs.enum(SwiftVersion, default = SwiftVersion[0]),+ "swiftinterface_subtarget_enabled": attrs.bool(default = read_bool("apple", "swiftinterface_subtarget_enabled", default = False, root_cell = True)),+ "use_archive": attrs.option(attrs.bool(), default = None),+ "_apple_xctoolchain": get_apple_xctoolchain_attr(),+ "_apple_xctoolchain_bundle_id": get_apple_xctoolchain_bundle_id_attr(),+ "_enable_library_evolution": get_enable_library_evolution(),+ "_swift_enable_testing": attrs.bool(+ default = select({+ "DEFAULT": False,+ "config//features/apple:swift_enable_testing_enabled": True,+ })+ ),+ APPLE_ARCHIVE_OBJECTS_LOCALLY_OVERRIDE_ATTR_NAME: attrs.option(attrs.bool(), default = None),+ VALIDATION_DEPS_ATTR_NAME: VALIDATION_DEPS_ATTR_TYPE,+ }+ | buck.allow_cache_upload_arg()+ | get_swift_incremental_file_hashing_attrs()+ | get_swift_incremental_logging_attrs()+ | get_swift_incremental_remote_outputs_attrs()+ | get_skip_swift_incremental_outputs_attrs()+ | xplugins_common.debug_artifacts_arg+ | get_incremental_split_actions_attrs()+ | get_incremental_swiftmodule_action_attrs()+ ),+ uses_plugins = [SwiftMacroPlugin],+ impl = apple_library_impl,+ cfg = target_sdk_version_transition,+)++apple_library_for_distribution = prelude_rule(+ name = "apple_library_for_distribution",+ docs = """+ An `apple_library_for_distribution()` rule creates a library for distribution+ (for instance via a Framework or Xcframework) with link group support.+ """,+ examples = None,+ further = None,+ attrs = (+ apple_library.attrs+ | {+ "distribution_dep": attrs.dep(),+ }+ ),+ uses_plugins = [SwiftMacroPlugin],+ impl = apple_library_impl,+ cfg = target_sdk_version_transition,+)++apple_metal_library = prelude_rule(+ name = "apple_metal_library",+ impl = apple_metal_library_impl,+ docs = """+ An `apple_metal_library()` rule contains .metal and .h source files+ to be bundled together to create a .metallib+ """,+ examples = """+ ```++ apple_metal_library(+ name = 'MyShaderLibrary',+ srcs = [+ MyShaderFile.metal,+ SharedShaderHelpers.metal,+ ],+ headers = [ SharedShaderHelpers.h ],+ )++ ```+ """,+ further = None,+ attrs = (+ buck.labels_arg()+ | buck.contacts_arg()+ | {+ "headers": attrs.list(attrs.source(), default = []),+ "metal_compiler_flags": attrs.list(+ attrs.arg(),+ default = [],+ doc = """+ Flags to use when compiling Metal sources.+ """,+ ),+ "metal_linker_flags": attrs.list(+ attrs.arg(),+ default = [],+ doc = """+ Flags to use when linking Metal `.air` files using `metallib`.+ """,+ ),+ "metal_version": attrs.option(attrs.string(), default = None),+ "out": attrs.option(+ attrs.string(),+ default = None,+ doc = """+ The name of the compiled library (must end in `.metallib`). Defaults to the target's name.+ """,+ ),+ "srcs": attrs.list(attrs.source(), default = []),+ "_apple_toolchain": get_apple_resources_toolchain_attr(),+ }+ ),+)++apple_package = prelude_rule(+ name = "apple_package",+ docs = """+ An `apple_package()` rule takes the output of+ an `apple_bundle()` rule and compresses it in+ an IPA (iOS App Store Package) file.++ This rule can be customized using the config options `.buckconfig`+ and `.buckconfig`+ .+ """,+ examples = """+ ```++ apple_package(+ name = 'AppPackage',+ bundle = ':AppBundle',+ )++ ```+ """,+ further = None,+ attrs = (+ # @unsorted-dict-items+ buck.contacts_arg()+ | apple_common.default_platform_arg()+ | buck.labels_arg()+ | buck.licenses_arg()+ | {+ "bundle": attrs.dep(+ providers = [AppleBundleInfo],+ doc = """+ A build target identifying+ an `apple_bundle()` rule whose output will+ be stored in the IPA package generated by this rule.+ """,+ ),+ "ext": attrs.enum(ApplePackageExtension.values(), default = "ipa"),+ "include_app_symbols": attrs.bool(default = False),+ "package_name": attrs.option(attrs.string(), default = None),+ "packager": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "packager_args": attrs.list(attrs.arg(), default = []),+ "prepackaged_validators": attrs.list(+ attrs.one_of(+ attrs.exec_dep(providers = [RunInfo]),+ attrs.tuple(attrs.exec_dep(providers = [RunInfo]), attrs.list(attrs.arg())),+ ),+ default = [],+ ),+ "_ipa_compression_level": attrs.enum(IpaCompressionLevel.values()),+ "_ipa_package": attrs.dep(),+ }+ | apple_common.apple_tools_arg()+ ),+ impl = apple_package_impl,+)++apple_resource = prelude_rule(+ name = "apple_resource",+ docs = """+ An `apple_resource()` rule contains sets of resource directories, files and file variants+ that can be bundled in an application bundle. This rule does not have any output on its own and can+ be built only as a dependency (either direct or transitive) of+ an `apple_bundle()` rule.+ """,+ examples = """+ ```++ apple_resource(+ name = 'Images',+ files = glob([+ '*.png',+ ]),+ dirs = [+ 'PrettyImages',+ ],+ )++ ```+ """,+ further = None,+ attrs = (+ # @unsorted-dict-items+ {+ "dirs": attrs.list(+ attrs.source(allow_directory = True),+ default = [],+ doc = """+ Set of paths of resource directories that should be placed in an application bundle.+ """,+ ),+ "content_dirs": attrs.list(+ attrs.source(allow_directory = True),+ default = [],+ doc = """+ Set of paths of directories containing resource files that should be placed in an application bundle. Unlike `dirs`, the directories themselves are not placed in the bundle.+ """,+ ),+ "files": attrs.list(+ attrs.one_of(attrs.dep(), attrs.source()),+ default = [],+ doc = """+ Set of paths of resource files that should be placed in an application bundle.+ """,+ ),+ "variants": attrs.list(+ attrs.source(),+ default = [],+ doc = """+ Set of paths of resource file variants that should be placed in an application bundle. The files+ mentioned here should be placed in a directory named `$VARIANT_NAME.lproj`,+ where `$VARIANT_NAME` is the name of the variant+ (e.g. `Base`, `en`). This argument makes it possible to use different+ resource files based on the active locale.+ """,+ ),+ "named_variants": attrs.dict(+ key = attrs.string(),+ value = attrs.set(attrs.source(), sorted = False),+ sorted = False,+ default = {},+ doc = """+ Mapping from a variant name to the list of resource file paths which should be placed in an application bundle. Those files+ will be placed in a directory with name equal to the corresponding key in this mapping. Keys should end with `.lproj` suffix.+ (e.g. `Base.lproj`, `en.lproj`).+ """,+ ),+ "resources_from_deps": attrs.list(+ attrs.dep(),+ default = [],+ doc = """+ Set of build targets whose transitive `apple_resource`s should be considered as part of+ the current resource when collecting resources for bundles.++ Usually, an `apple_bundle` collects all `apple_resource` rules transitively+ reachable through apple\\_library rules. This field allows for resources which are not reachable+ using the above traversal strategy to be considered for inclusion in the bundle.+ """,+ ),+ "destination": attrs.option(+ attrs.enum(AppleResourceDestination.values()),+ default = None,+ doc = """+ Specifies the destination in the final application bundle where resource will be copied. Possible+ values: "resources", "frameworks", "executables", "plugins", "xpcservices", "loginitems",+ "launchagents" (macOS `Contents/Library/LaunchAgents`), "extensionkit_extensions".+ """,+ ),+ "codesign_on_copy": attrs.bool(+ default = False,+ doc = """+ Indicates whether the files specified in the files arg in this resource should be code signed with the identity used to sign the overall bundle. This is useful for e.g.+ dylibs or other additional binaries copied into the bundle. The caller is responsible to ensure that the file format is valid for codesigning.+ """,+ ),+ "codesign_entitlements": attrs.option(attrs.source(), default = None),+ "codesign_flags_override": attrs.option(attrs.list(attrs.string()), default = None),+ }+ | buck.contacts_arg()+ | buck.labels_arg()+ | buck.licenses_arg()+ | apple_common.skip_universal_resource_dedupe_arg()+ ),+ impl = apple_resource_impl,+ cfg = apple_resource_transition,+)++apple_test = prelude_rule(+ name = "apple_test",+ docs = """+ An `apple_test()` rule contains Objective-C/C++ code which can be built and used to test+ code contained in other rules. The tests can be executed by running `buck test`.+ """,+ examples = """+ ```++ apple_test(+ name = 'MyTest',+ info_plist = 'MyTest-Info.plist',+ preprocessor_flags = ['-fobjc-arc'],+ srcs = [+ 'MyTest.m',+ ],+ deps = [+ ':MyLibrary',+ ],+ frameworks = [+ '$SDKROOT/System/Library/Frameworks/Foundation.framework',+ '$SDKROOT/System/Library/Frameworks/UIKit.framework',+ '$PLATFORM_DIR/Developer/Library/Frameworks/XCTest.framework',+ ],+ )++ ```+ """,+ further = None,+ attrs = (+ # @unsorted-dict-items+ apple_common.info_plist_arg()+ | apple_common.info_plist_substitutions_arg()+ | {+ "embed_xctest_frameworks_in_test_host_app": attrs.option(+ attrs.bool(),+ default = None,+ doc = """+ Controls whether a marker constraint is added to the `test_host_app`.+ """,+ ),+ "test_host_app": attrs.option(+ attrs.transition_dep(cfg = apple_test_host_app_transition),+ default = None,+ doc = """+ A build target identifying+ an `apple_bundle()` rule that builds an+ application bundle. Output of the specified rule will be used as a test host of this test. This+ implies `run_test_separately`.+ Since symbols that are defined in the test host application and its dependencies will not be+ linked into the test binary, to make those symbols accessible to the test target they need+ to be specified as a dependency of this target and `['-undefined', 'dynamic_lookup']` needs to be added to this target's `linker_flags` (this will suppress undefined+ reference errors during compilation, but if the symbols do not exist, it might result in runtime+ crashes).+ """,+ ),+ }+ | cxx_common.srcs_arg()+ | apple_common.headers_arg()+ | apple_common.header_path_prefix_arg()+ | apple_common.frameworks_arg()+ | cxx_common.preprocessor_flags_arg()+ | cxx_common.compiler_flags_arg()+ | cxx_common.linker_flags_arg()+ | apple_common.target_sdk_version()+ | buck.run_test_separately_arg(run_test_separately_type = attrs.bool(default = False))+ | buck.test_label_arg()+ | apple_common.extra_xcode_sources()+ | apple_common.extra_xcode_files()+ | apple_common.serialize_debugging_options_arg()+ | apple_common.uses_explicit_modules_arg()+ | apple_common.apple_sanitizer_compatibility_arg()+ | apple_common.executable_name_arg()+ | apple_common.asset_catalogs_compilation_options_arg()+ | cxx_common.supported_platforms_regex_arg()+ | buck.contacts_arg()+ | apple_common.default_platform_arg()+ | buck.licenses_arg()+ | apple_common.codesign_flags_arg()+ | apple_common.codesign_identity_arg()+ | apple_common.defaults_arg()+ | apple_common.deps_arg()+ | cxx_common.exported_deps_arg()+ | apple_common.devirt_enabled_arg()+ | apple_common.diagnostics_arg()+ | apple_common.enable_cxx_interop_arg()+ | cxx_common.exported_header_style_arg()+ | apple_common.fat_lto_arg()+ | cxx_common.header_namespace_arg()+ | cxx_common.include_directories_arg()+ | apple_common.libraries_arg()+ | apple_common.link_group_arg()+ | apple_common.modular_arg()+ | apple_common.module_name_arg()+ | apple_common.module_requires_cxx_arg()+ | cxx_common.public_include_directories_arg()+ | cxx_common.public_system_include_directories_arg()+ | apple_common.sdk_modules_arg()+ | native_common.soname()+ | apple_common.static_library_basename_arg()+ | apple_common.swift_module_skip_function_bodies_arg()+ | apple_common.disable_generated_umbrella_header_arg()+ | apple_common.thin_lto_arg()+ | apple_common.use_submodules_arg()+ | apple_common.uses_cxx_explicit_modules_arg()+ | apple_common.uses_modules_arg()+ | apple_common.xcode_product_type_arg()+ | {+ "bridging_header": attrs.option(attrs.source(), default = None),+ "can_be_asset": attrs.option(attrs.bool(), default = None),+ "cxx_runtime_type": attrs.option(attrs.enum(CxxRuntimeType), default = None),+ "destination_specifier": attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False, default = {}),+ "entitlements_file": attrs.option(attrs.source(), default = None),+ "env": attrs.option(attrs.dict(key = attrs.string(), value = attrs.arg(), sorted = False), default = None),+ # Need to keep both `exported_headers` and `headers` for Swift mixed modules+ # to hide C++ code importing.+ "exported_headers": attrs.named_set(attrs.source(), sorted = True, default = []),+ "exported_lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),+ "exported_linker_flags": attrs.list(attrs.arg(), default = []),+ "exported_post_linker_flags": attrs.list(attrs.arg(), default = []),+ "exported_preprocessor_flags": attrs.list(attrs.arg(), default = []),+ "focused_list_target": attrs.option(attrs.dep(), default = None),+ "force_static": attrs.option(attrs.bool(), default = None),+ "headers_as_raw_headers_mode": attrs.option(attrs.enum(HeadersAsRawHeadersMode), default = None),+ "incremental_bundling_enabled": attrs.option(attrs.bool(), default = None),+ "is_ui_test": attrs.bool(default = False),+ "lang_compiler_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),+ "lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),+ "link_group_map": LINK_GROUP_MAP_ATTR,+ # Used to create the shared test library. Any library deps whose `preferred_linkage` isn't "shared" will+ # be treated as "static" deps and linked into the shared test library.+ "link_style": attrs.enum(LinkableDepType, default = "static"),+ "link_whole": attrs.option(attrs.bool(), default = None),+ "linker_extra_outputs": attrs.list(attrs.string(), default = []),+ "post_linker_flags": attrs.list(attrs.arg(), default = []),+ # The test source code and lib dependencies should be built into a shared library.+ "preferred_linkage": attrs.enum(Linkage.values(), default = "shared"),+ "prefix_header": attrs.option(attrs.source(), default = None),+ "raw_headers": attrs.set(attrs.source(), sorted = True, default = []),+ "reexport_all_header_dependencies": attrs.option(attrs.bool(), default = None),+ "runner": attrs.option(attrs.dep(), default = None),+ "skip_copying_swift_stdlib": attrs.option(attrs.bool(), default = None),+ "snapshot_reference_images_path": attrs.option(attrs.one_of(attrs.source(), attrs.string()), default = None),+ "specs": attrs.option(attrs.arg(json = True), default = None),+ "supports_merged_linking": attrs.option(attrs.bool(), default = None),+ "swift_compiler_flags": attrs.list(attrs.arg(), default = []),+ "swift_interface_compilation_enabled": attrs.bool(default = False),+ "swift_macro_deps": attrs.list(attrs.plugin_dep(kind = SwiftMacroPlugin), default = []),+ "swift_version": attrs.enum(SwiftVersion, default = SwiftVersion[0]),+ "test_rule_timeout_ms": attrs.option(attrs.int(), default = None),+ "ui_test_target_app": attrs.option(attrs.dep(), default = None),+ }+ | buck.allow_cache_upload_arg()+ | buck.inject_test_env_arg()+ | apple_test_extra_attrs()+ | test_common.attributes()+ | xplugins_common.debug_artifacts_arg+ | constraint_overrides.attributes+ ),+ uses_plugins = [SwiftMacroPlugin],+ impl = apple_test_impl,+ cfg = apple_test_target_sdk_version_transition,+)++apple_toolchain = prelude_rule(+ name = "apple_toolchain",+ docs = """+ An `apple_toolchain()` rule defines the set of tools and settings used to build Apple targets.+ It specifies paths to compilers, linkers, code signing utilities, resource compilers, and other+ tools from the Apple SDK and Xcode. Rules such as `apple_binary()`, `apple_library()`, and+ `apple_bundle()` reference an `apple_toolchain()` to determine which tools and SDK to use+ during compilation, linking, and bundling.+ """,+ examples = None,+ further = None,+ attrs = (+ buck.contacts_arg()+ | buck.labels_arg()+ | buck.licenses_arg()+ | {+ "actool": attrs.exec_dep(providers = [RunInfo]),+ "app_intents_metadata_processor": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "app_intents_nl_training_processor": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "architecture": attrs.string(default = ""),+ "build_version": attrs.option(attrs.string(), default = None),+ "codesign": attrs.exec_dep(providers = [RunInfo]),+ "codesign_allocate": attrs.exec_dep(providers = [RunInfo]),+ "codesign_identities_command": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ # Controls invocations of `ibtool`, `actool` `mapc` and `momc`+ "compile_resources_locally": attrs.bool(default = False),+ "copy_scene_kit_assets": attrs.exec_dep(providers = [RunInfo]),+ "cxx_toolchain": attrs.toolchain_dep(),+ "developer_path": attrs.option(attrs.source(), default = None),+ "dsymutil": attrs.exec_dep(providers = [RunInfo]),+ "dsymutil_flags": attrs.list(attrs.string(), default = []),+ "dwarfdump": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "extra_linker_outputs": attrs.set(attrs.string(), default = []),+ "ibtool": attrs.exec_dep(providers = [RunInfo]),+ "libtool": attrs.exec_dep(providers = [RunInfo]),+ "lipo": attrs.exec_dep(providers = [RunInfo]),+ "mapc": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "merge_index_store": attrs.default_only(attrs.dep(providers = [RunInfo], default = "prelude//apple/tools/index:merge_index_store")),+ "metal": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "metallib": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "min_version": attrs.string(default = ""),+ "momc": attrs.exec_dep(providers = [RunInfo]),+ "objdump": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ # A placeholder tool that can be used to set up toolchain constraints.+ # Useful when fat and thin toolchains share the same underlying tools via `command_alias()`,+ # which requires setting up separate platform-specific aliases with the correct constraints.+ "placeholder_tool": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "platform_path": attrs.option(attrs.source(), default = None), # Mark as optional until we remove `_internal_platform_path`+ "required_reasons_tools": attrs.exec_dep(providers = [RequiredReasonsToolsInfo]),+ # Defines whether the Xcode project generator needs to check+ # that the selected Xcode version matches the one defined+ # by the `xcode_build_version` fields.+ "requires_xcode_version_match": attrs.bool(default = False),+ "sdk_environment": attrs.option(attrs.string(), default = None),+ "sdk_name": attrs.string(default = ""),+ "sdk_path": attrs.option(attrs.source(), default = None), # Mark as optional until we remove `_internal_sdk_path`+ "swift_toolchain": attrs.option(attrs.toolchain_dep(), default = None),+ "version": attrs.option(attrs.string(), default = None),+ "watch_kit_stub_binary": attrs.option(attrs.source(), default = None),+ "work_around_dsymutil_lto_stack_overflow_bug": attrs.option(attrs.bool(), default = None),+ "xcode_build_version": attrs.option(attrs.string(), default = None),+ "xcode_version": attrs.string(),+ "xctest": attrs.exec_dep(providers = [RunInfo]),+ # TODO(T111858757): Mirror of `platform_path` but treated as a string. It allows us to+ # pass abs paths during development and using the currently selected Xcode.+ "_internal_platform_path": attrs.option(attrs.string(), default = None),+ # TODO(T111858757): Mirror of `sdk_path` but treated as a string. It allows us to+ # pass abs paths during development and using the currently selected Xcode.+ "_internal_sdk_path": attrs.option(attrs.string(), default = None),+ }+ | apple_common.apple_installer_arg()+ ),+ impl = apple_toolchain_impl,+)++required_reasons_tools = prelude_rule(+ name = "required_reasons_tools",+ docs = """+ A `required_reasons_tools()` rule bundles the tools used to validate Apple+ Required Reasons API (RRAPI) usage against a bundle's `.xcprivacy` privacy manifest.+ It is referenced by `apple_toolchain()` and provides the per-target `analyzer`, the+ bundle-level `validator`.+ """,+ examples = None,+ further = None,+ attrs = (+ buck.contacts_arg()+ | buck.labels_arg()+ | {+ "analyzer": attrs.exec_dep(providers = [RunInfo]),+ "validator": attrs.exec_dep(providers = [RunInfo]),+ }+ ),+ impl = required_reasons_tools_impl,+)++core_data_model = prelude_rule(+ name = "core_data_model",+ docs = """+ An `core_data_model()` rule contains models for Apple's Core Data framework. This rule does not have any output on its own and can be built only as a dependency+ (either direct or transitive) of an `apple_bundle()` rule in which case all `core_data_model()` rules+ that the bundle rule depends on are merged and placed into the final output bundle together.+ """,+ examples = """+ ```++ core_data_model(+ name = 'MyCoreDataModel',+ path = 'MyCoreDataModel.xcdatamodeld',+ )++ ```+ """,+ further = None,+ attrs = (+ # @unsorted-dict-items+ buck.contacts_arg()+ | buck.labels_arg()+ | buck.licenses_arg()+ | {+ "module": attrs.option(attrs.string(), default = None),+ "path": attrs.source(+ allow_directory = True,+ doc = """+ Relative path of the .xcdatamodeld package directory.+ """,+ ),+ }+ ),+ impl = apple_core_data_impl,+)++prebuilt_apple_framework = prelude_rule(+ name = "prebuilt_apple_framework",+ docs = """+ A `prebuilt_apple_framework()` rule represents a set of+ Objective-C/C++ source files and is very similar to a `prebuilt_cxx_library()` rule.+ """,+ examples = """+ ```++ prebuilt_apple_framework(+ name = 'MyPrebuiltFramework',+ framework = 'myPrebuiltFramework.framework',+ preferred_linkage = 'static',+ visibility = [+ 'PUBLIC'+ ]+ )++ ```+ """,+ further = None,+ attrs = (+ # @unsorted-dict-items+ buck.contacts_arg()+ | buck.labels_arg()+ | buck.licenses_arg()+ | apple_common.deps_arg()+ | apple_common.libraries_arg()+ | apple_common.sdk_modules_arg()+ | apple_common.strip_level_arg()+ | {+ "binary": attrs.option(+ attrs.string(),+ default = None,+ doc = """+ Optional name for the binary contained in the framework. Otherwise the framework name is used.+ Therefore, if your framework binary is named something like `libFrameworkName-iPhone.a` instead+ of `FrameworkName`, you can declare this here.+ """,+ ),+ "contains_swift": attrs.bool(default = False),+ "dsyms": attrs.list(attrs.source(allow_directory = True), default = []),+ "exported_linker_flags": attrs.list(attrs.string(), default = []),+ "extra_codesign_paths": attrs.list(+ attrs.string(),+ default = [],+ doc = """+ A list of extra paths, relative to the framework root, that will be codesigned.+ """,+ ),+ "framework": attrs.option(attrs.source(allow_directory = True), default = None),+ "frameworks": attrs.list(attrs.string(), default = []),+ "modular": attrs.bool(default = True),+ "preferred_linkage": attrs.enum(+ Linkage.values(),+ default = "any",+ doc = """+ How to link to a binary: use `dynamic` for a dynamic+ framework, and `static` for old universal static+ frameworks manually lipo-ed together. `dynamic` will+ copy the frameworks into the `Frameworks` directory+ of an Apple bundle, and configure framework search paths and linker flags.+ `static` will copy the resources of the framework into+ an Apple bundle.+ """,+ ),+ }+ | apple_common.apple_tools_arg()+ | apple_common.apple_toolchain_arg()+ | cxx_common.supported_platforms_regex_arg()+ ),+ impl = prebuilt_apple_framework_impl,+)++scene_kit_assets = prelude_rule(+ name = "scene_kit_assets",+ docs = """+ A `scene_kit_assets()` rule specifies a SceneKit asset catalog (`.scnassets` directory)+ to be included in an `apple_bundle()`. The assets are compiled using the+ `copy_scene_kit_assets` tool from the Apple toolchain during bundling.+ """,+ examples = None,+ further = None,+ attrs = (+ # @unsorted-dict-items+ buck.contacts_arg()+ | buck.labels_arg()+ | buck.licenses_arg()+ | {+ "path": attrs.source(allow_directory = True),+ }+ ),+ impl = scene_kit_assets_impl,+)++swift_toolchain = prelude_rule(+ name = "swift_toolchain",+ docs = """+ A `swift_toolchain()` rule defines the Swift compiler and associated tools used to build+ Swift code in Apple targets. It specifies the `swiftc` compiler, standard library tools,+ module paths, SDK paths, and compiler flags. An `apple_toolchain()` references a+ `swift_toolchain()` via its `swift_toolchain` attribute to enable Swift compilation.+ """,+ examples = None,+ further = None,+ attrs = (+ buck.contacts_arg()+ | buck.labels_arg()+ | buck.licenses_arg()+ | {+ "architecture": attrs.string(),+ "enforce_dedupe_eligibility": attrs.bool(default = False),+ "make_swift_comp_db": attrs.default_only(attrs.exec_dep(providers = [RunInfo], default = "prelude//apple/tools:make_swift_comp_db")),+ "make_swift_interface": attrs.default_only(attrs.exec_dep(providers = [RunInfo], default = "prelude//apple/tools:make_swift_interface")),+ "object_format": attrs.enum(SwiftObjectFormat.values(), default = "object"),+ # A placeholder tool that can be used to set up toolchain constraints.+ # Useful when fat and thin toolchahins share the same underlying tools via `command_alias()`,+ # which requires setting up separate platform-specific aliases with the correct constraints.+ "placeholder_tool": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "platform_path": attrs.option(attrs.source(), default = None),+ # Prioritizes the Swift critical path by preferring swiftmodule emits+ # locally, disabling low-pass gating for swiftmodule and PCM actions,+ # and increasing bulk Swift object-compile weight.+ "prioritize_swift_critical_path": attrs.bool(default = False),+ "provide_swift_debug_info": attrs.bool(default = True),+ "resource_dir": attrs.option(attrs.source(), default = None),+ "runtime_paths_for_bundling": attrs.list(attrs.string(), default = []),+ "runtime_paths_for_linking": attrs.list(attrs.string(), default = []),+ "sdk_module_path_prefixes": attrs.dict(key = attrs.string(), value = attrs.source(), default = {}),+ "sdk_modules": attrs.list(attrs.exec_dep(), default = []), # A list or a root target that represent a graph of sdk modules (e.g Frameworks)+ "sdk_path": attrs.option(attrs.source(), default = None), # Mark as optional until we remove `_internal_sdk_path`+ "serialized_diags_to_json": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "supports_explicit_module_debug_serialization": attrs.bool(default = False),+ "supports_incremental_file_hashing": attrs.bool(default = False),+ # Only the Pika toolchain's swiftc understands+ # -emit-modularization-dependency-dot-graph.+ "supports_modularization_dependency_graph": attrs.bool(default = False),+ "supports_modulemaps_with_hmaps": attrs.bool(default = False),+ "supports_relative_resource_dir": attrs.bool(default = False),+ "swift_experimental_features": attrs.dict(+ key = attrs.enum(SwiftVersion), value = attrs.list(attrs.string()), sorted = False, default = SWIFT_VERSION_FEATURE_MAP+ ),+ "swift_ide_test_tool": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "swift_stdlib_tool": attrs.exec_dep(providers = [RunInfo]),+ "swift_stdlib_tool_flags": attrs.list(attrs.arg(), default = []),+ "swift_upcoming_features": attrs.dict(+ key = attrs.enum(SwiftVersion), value = attrs.list(attrs.string()), sorted = False, default = SWIFT_VERSION_FEATURE_MAP+ ),+ "swiftc": attrs.exec_dep(providers = [RunInfo]),+ "swiftc_flags": attrs.list(attrs.arg(), default = []),+ "use_depsfiles": attrs.bool(default = False),+ "uses_content_based_paths": attrs.bool(default = False),+ # TODO(T111858757): Mirror of `sdk_path` but treated as a string. It allows us to+ # pass abs paths during development and using the currently selected Xcode.+ "_internal_sdk_path": attrs.option(attrs.string(), default = None),+ "_swiftc_wrapper": attrs.exec_dep(providers = [RunInfo], default = "prelude//apple/tools:swift_exec"),+ }+ ),+ impl = swift_toolchain_impl,+)++apple_universal_executable = prelude_rule(+ name = "apple_universal_executable",+ impl = apple_universal_executable_impl,+ docs = """+ An `apple_universal_executable()` rule takes a target via its+ `binary` attribute, builds it for multiple architectures and+ combines the result into a single binary using `lipo`.++ The output of the rule is a universal binary:+ - If `config//cpu/constraints:universal-enabled` is present in the target platform.+ - If the `universal` attribute is set to `True`.++ If none of the conditions are met, then the rule acts as a nop `alias()`.++ The `universal` attribute, if present, takes precedence over constraint.+ For example, if `universal = False`, then the presence of the constraint+ would not affect the output.++ `apple_bundle()` supports building of universal binaries,+ `apple_universal_executable()` is only needed if you have a standalone+ binary target which is not embedded in an `apple_bundle()` (usually a+ CLI tool).+ """,+ examples = None,+ further = None,+ attrs = (+ buck.labels_arg()+ | buck.contacts_arg()+ | {+ "executable": attrs.split_transition_dep(+ cfg = cpu_split_transition,+ doc = """+ A build target identifying the binary which will be built for multiple architectures.+ The target will be transitioned into different configurations, with distinct architectures.++ The target can be one of:+ - `apple_binary()` and `cxx_binary()`+ - `[shared]` subtarget of `apple_library()` and `cxx_library()`+ - `apple_library()` and `cxx_library()` which have `preferred_linkage = shared` attribute+ """,+ ),+ "split_arch_dsym": attrs.bool(+ default = False,+ doc = """+ If enabled, each architecture gets its own dSYM binary. Use this if the combined+ universal dSYM binary exceeds 4GiB.+ """,+ ),+ "universal": attrs.option(+ attrs.bool(),+ default = None,+ doc = """+ Controls whether the output is universal binary. Any value overrides the presence+ of the `config//cpu/constraints:universal-enabled` constraint. Read the rule docs+ for more information on resolution.+ """,+ ),+ }+ | apple_common.executable_name_for_universal_arg()+ | apple_common.apple_toolchain_arg()+ | apple_common.apple_tools_arg()+ ),+)++apple_provisioning_profile_sources = prelude_rule(+ name = "apple_provisioning_profile_sources",+ docs = """+ An `apple_provisioning_profile_sources()` rule specifies a set of provisioning profile+ targets that are available for code signing Apple bundles. These profiles are used during+ the signing step of `apple_bundle()` to match a valid, non-expired profile to the bundle+ identifier and entitlements.+ """,+ impl = apple_provisioning_profile_sources_impl,+ examples = None,+ further = None,+ attrs = {+ "sources": attrs.list(attrs.dep(), default = []),+ },+)++apple_simulators = prelude_rule(+ name = "apple_simulators",+ docs = """+ An `apple_simulators()` rule configures the Apple simulator environment used for+ running tests. It specifies the simulator broker, device type, OS version, and+ setup parameters needed to launch and manage iOS/watchOS/tvOS simulators during+ test execution.+ """,+ impl = apple_simulators_impl,+ examples = None,+ further = None,+ attrs = {+ "args": attrs.list(attrs.string(), default = []),+ "broker": attrs.exec_dep(providers = [RunInfo]),+ "idb_targets": attrs.exec_dep(providers = [RunInfo]),+ "setup_timeout_seconds": attrs.option(attrs.int(), default = None),+ "_simulator_device": attrs.default_only(attrs.string(default = read_root_config("apple", "simulator_device", ""))),+ "_simulator_os_version": attrs.default_only(attrs.string(default = read_root_config("apple", "simulator_os_version", ""))),+ },+)++apple_tools = prelude_rule(+ name = "apple_tools",+ impl = apple_tools_impl,+ docs = """+ The `apple_tools` rule exposes a set of supplementary tools+ required by the Apple rules _internally_. Such tools are not+ toolchain/SDK specific, they're just internal helper tools.+ """,+ examples = None,+ further = None,+ attrs = {+ "adhoc_codesign_tool": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "assemble_bundle": attrs.exec_dep(providers = [RunInfo]),+ "bundle_telemetry_logger": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "codesign_manifest_tree_postprocessor": attrs.exec_dep(providers = [RunInfo]),+ "dedupe_swift_module_map": attrs.exec_dep(providers = [RunInfo]),+ "dry_codesign_tool": attrs.exec_dep(providers = [RunInfo]),+ "framework_sanitizer": attrs.exec_dep(providers = [RunInfo]),+ "info_plist_processor": attrs.exec_dep(providers = [RunInfo]),+ "ipa_package_maker": attrs.exec_dep(providers = [RunInfo]),+ "make_modulemap": attrs.exec_dep(providers = [RunInfo]),+ "make_vfsoverlay": attrs.exec_dep(providers = [RunInfo]),+ "provisioning_manifest": attrs.exec_dep(providers = [RunInfo]),+ "resolve_signing_context": attrs.exec_dep(providers = [RunInfo]),+ "selective_debugging_scrubber": attrs.exec_dep(providers = [RunInfo]),+ "signing_context_tree_postprocessor": attrs.exec_dep(providers = [RunInfo]),+ "signing_info": attrs.exec_dep(providers = [RunInfo]),+ "split_arch_combine_dsym_bundles_tool": attrs.exec_dep(providers = [RunInfo]),+ "spm_packager": attrs.exec_dep(providers = [RunInfo]),+ "static_archive_linker": attrs.exec_dep(providers = [RunInfo]),+ "swiftmodule_change_analysis": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "xcframework_maker": attrs.exec_dep(providers = [RunInfo]),+ },+)++cxx_universal_executable = prelude_rule(+ name = "cxx_universal_executable",+ impl = cxx_universal_executable_impl,+ docs = """+ A `cxx_universal_executable()` rule takes a target via its+ `binary` attribute, builds it for multiple architectures and+ combines the result into a single binary using `lipo`.++ The output of the rule is a universal binary:+ - If `config//cpu/constraints:universal-enabled` is present in the target platform.+ - If the `universal` attribute is set to `True`.++ If none of the conditions are met, then the rule acts as a nop `alias()`.++ The `universal` attribute, if present, takes precedence over constraint.+ For example, if `universal = False`, then the presence of the constraint+ would not affect the output.+ """,+ examples = None,+ further = None,+ attrs = (+ buck.labels_arg()+ | buck.contacts_arg()+ | {+ "executable": attrs.split_transition_dep(+ cfg = cpu_split_transition,+ doc = """+ A build target identifying the binary which will be built for multiple architectures.+ The target will be transitioned into different configurations, with distinct architectures.++ The target can be one of:+ - `cxx_binary()`+ - `[shared]` subtarget `cxx_library()`+ - `cxx_library()` which have `preferred_linkage = shared` attribute+ """,+ ),+ "universal": attrs.option(+ attrs.bool(),+ default = None,+ doc = """+ Controls whether the output is universal binary. Any value overrides the presence+ of the `config//cpu/constraints:universal-enabled` constraint. Read the rule docs+ for more information on resolution.+ """,+ ),+ "_cxx_toolchain": toolchains_common.cxx(),+ }+ | apple_common.executable_name_for_universal_arg()+ ),+)++apple_ipa_package = prelude_rule(+ name = "apple_ipa_package",+ docs = """+ An `apple_ipa_package()` rule packages an `apple_bundle()` into an IPA file+ for distribution. The IPA is a compressed archive containing the application+ bundle in the standard format expected by App Store Connect and ad-hoc+ distribution workflows.+ """,+ impl = apple_ipa_package_impl,+ attrs = apple_ipa_package_attribs(),+)++apple_xcframework = prelude_rule(+ name = "apple_xcframework",+ docs = """+ An `apple_xcframework()` rule packages a framework target built for multiple platforms+ (e.g., iOS device, iOS simulator, macOS) into a single `.xcframework` bundle that can+ be distributed and consumed by Xcode projects or other build systems. The framework is+ built per-platform via a split transition and then combined.+ """,+ impl = apple_xcframework_impl,+ attrs = buck.labels_arg()+ | buck.contacts_arg()+ | {+ "framework": attrs.split_transition_dep(cfg = framework_split_transition),+ "framework_name": attrs.option(attrs.string(), default = None),+ "framework_name_from_product_name": attrs.bool(default = False),+ "include_dsym": attrs.option(attrs.bool(), default = None),+ "platforms": attrs.list(attrs.string(), default = []),+ }+ | apple_common.apple_tools_arg(),+)++apple_spm_package = prelude_rule(+ name = "apple_spm_package",+ docs = """+ An `apple_spm_package()` rule packages a set of dependencies into a Swift Package+ Manager (SPM) compatible package. This enables distributing buck2-built libraries+ in a format that can be consumed by SPM-based projects.+ """,+ impl = apple_spm_package_impl,+ attrs = (+ apple_common.deps_arg()+ | {+ "package_name": attrs.string(),+ "_apple_tools": attrs.exec_dep(default = "prelude//apple/tools:apple-tools", providers = [AppleToolsInfo]),+ }+ ),+)++apple_static_archive = prelude_rule(+ name = "apple_static_archive",+ docs = """+ An `apple_static_archive()` rule combines one or more Apple libraries into a single+ static archive (`.a` file). This is useful for distributing prebuilt libraries+ where multiple object files need to be bundled together.+ """,+ impl = apple_static_archive_impl,+ attrs = (+ buck.labels_arg()+ | buck.contacts_arg()+ | apple_common.deps_arg()+ | {+ "archive_name": attrs.option(attrs.string(), default = None),+ "distribution_flat_dep": attrs.option(attrs.dep(), default = None),+ "flat_deps": attrs.list(attrs.dep(), default = []),+ VALIDATION_DEPS_ATTR_NAME: VALIDATION_DEPS_ATTR_TYPE,+ }+ | apple_common.apple_tools_arg()+ | apple_common.apple_toolchain_arg()+ ),+)++apple_selective_debugging = prelude_rule(+ name = "apple_selective_debugging",+ docs = """+ An `apple_selective_debugging()` rule configures which targets have debug information+ included in the final binary. By specifying include/exclude patterns for build targets+ or regular expressions, you can reduce binary size by stripping debug info from+ dependencies you don't need to debug.+ """,+ impl = apple_selective_debugging_impl,+ attrs = {+ "exclude_build_target_patterns": attrs.list(attrs.string(), default = []),+ "exclude_regular_expressions": attrs.list(attrs.string(), default = []),+ "include_build_target_patterns": attrs.list(attrs.string(), default = []),+ "include_regular_expressions": attrs.list(attrs.string(), default = []),+ "json_type": attrs.enum(SelectiveDebuggingJsonTypes),+ "targets_json_file": attrs.option(attrs.source(), default = None),+ }+ | apple_common.apple_tools_arg(),+)++apple_macos_bundle = prelude_rule(+ name = "apple_macos_bundle",+ docs = """+ An `apple_macos_bundle()` rule generates a macOS application bundle. It applies+ the macOS platform transition automatically, so the binary and its dependencies+ are built for macOS regardless of the default target platform. Use case is Mac+ Catalyst apps which want to include an AppKit framework.+ """,+ impl = apple_macos_bundle_impl,+ attrs = apple_macos_bundle_attrs(),+ cfg = macos_transition,+)++apple_watchos_bundle = prelude_rule(+ name = "apple_watchos_bundle",+ docs = """+ An `apple_watchos_bundle()` rule generates a watchOS application bundle. It applies+ the watchOS platform transition automatically, so the binary and its dependencies+ are built for watchOS regardless of the default target platform.+ """,+ impl = apple_watchos_bundle_impl,+ attrs = apple_watchos_bundle_attrs(),+ cfg = watch_transition,+)++apple_resource_bundle = prelude_rule(+ name = "apple_resource_bundle",+ docs = """+ An `apple_resource_bundle()` is a rule that exists for internal implementation reasons to compile resources for the Apple platform. It's used by the Apple rules and not for public consumption.+ """,+ impl = apple_resource_bundle_impl,+ attrs = (+ buck.labels_arg()+ | buck.contacts_arg()+ | apple_common.deps_arg()+ | apple_common.ibtool_flags_arg()+ | apple_common.product_name_arg()+ | apple_common.resource_group_arg()+ | {+ "binary": attrs.option(attrs.split_transition_dep(cfg = cpu_split_transition), default = None),+ "copy_public_framework_headers": attrs.option(attrs.bool(), default = None),+ "extension": attrs.one_of(attrs.enum(AppleBundleExtension), attrs.string()),+ "info_plist": attrs.source(),+ "module_map": attrs.option(attrs.one_of(attrs.enum(AppleFrameworkBundleModuleMapType), attrs.source()), default = None),+ "privacy_manifest": attrs.option(attrs.source(), default = None),+ "product_name_from_module_name": attrs.bool(default = False),+ "resource_group_map": RESOURCE_GROUP_MAP_ATTR,+ "universal": attrs.option(attrs.bool(), default = None),+ # Only include macOS hosted toolchains, so we compile resources directly on Mac RE+ "_apple_toolchain": get_apple_resources_toolchain_attr(),+ # Because `apple_resource_bundle` is a proxy for `apple_bundle`, we need to get `name`+ # field of the `apple_bundle`, as it's used as a fallback value in Info.plist.+ "_bundle_target_name": attrs.string(),+ "_compile_resources_locally_override": attrs.option(attrs.bool(), default = None),+ }+ | get_apple_info_plist_build_system_identification_attrs()+ | apple_common.apple_tools_arg()+ | apple_common.asset_catalogs_compilation_options_arg()+ | apple_common.info_plist_substitutions_arg()+ | apple_common.enforce_minimum_os_plist_key()+ | apple_common.skip_private_swiftinterface_arg()+ ),+)++apple_resource_dedupe_alias = prelude_rule(+ name = "apple_resource_dedupe_alias",+ docs = """+ An `apple_resource_dedupe_alias()` rule creates an alias for a resource target+ with a resource configuration transition applied. This enables the resource+ deduplication pipeline to dedupe the same resources across arch-transitions (i.e., universal binaries - x86 + arm64).+ """,+ impl = apple_resource_dedupe_alias_impl,+ attrs = {+ "actual": attrs.transition_dep(cfg = apple_resource_transition),+ }+ | apple_common.skip_universal_resource_dedupe_arg(),+)++mockingbird_mock = prelude_rule(+ name = "mockingbird_mock",+ docs = """+ A `mockingbird_mock()` rule generates mock implementations using the Mockingbird+ mocking framework. The generated mocks can be used in `apple_test()` targets for+ unit testing Swift and Objective-C code.+ """,+ impl = mockingbird_mock_impl,+ attrs = mockingbird_mock_attrs(),+)++resource_group_map = prelude_rule(+ name = "resource_group_map",+ docs = """+ A `resource_group_map()` rule defines a mapping of resource groups for an+ `apple_bundle()`. Each group specifies which dependencies' resources should be+ placed together, enabling fine-grained control over how resources are partitioned+ across bundles in a multi-bundle application (e.g., app extensions, plugins).+ """,+ impl = resource_group_map_impl,+ attrs = {+ "map": attrs.list(+ attrs.tuple(+ attrs.string(),+ attrs.list(+ attrs.tuple(+ attrs.one_of(attrs.dep(), attrs.list(attrs.dep())),+ attrs.enum(Traversal.values()),+ attrs.option(attrs.one_of(attrs.dep(providers = [GroupFilterInfo]), attrs.string())),+ ),+ ),+ ),+ ),+ },+)++apple_xcuitest = prelude_rule(+ name = "apple_xcuitest",+ docs = """+ An `apple_xcuitest()` rule defines an XCUITest UI test target. It builds a test+ runner bundle that launches the application under test and executes UI automation+ tests using Apple's XCTest UI testing framework.+ """,+ impl = apple_xcuitest_impl,+ attrs = apple_xcuitest_extra_attrs(),+)++apple_info_plist = prelude_rule(+ name = "apple_info_plist",+ docs = """+ An `apple_info_plist()` rule defines mutations to apply to an `Info.plist` file.+ It supports update, merge, and restricted merge operations, allowing you to+ programmatically set, override, or combine plist entries during the build.+ """,+ impl = apple_info_plist_impl,+ attrs = {+ "mutations": attrs.list(+ attrs.one_of(+ attrs.tuple(+ attrs.enum(UpdateOperations.values()),+ attrs.dict(key = attrs.string(), value = attrs.one_of(attrs.string(), attrs.bool(), attrs.int())),+ ),+ attrs.tuple(attrs.enum(MergeOperations.values()), attrs.source()),+ attrs.tuple(+ attrs.enum(RestrictedMergeOperations.values()),+ attrs.source(),+ attrs.dict(key = attrs.string(), value = attrs.one_of(attrs.string(), attrs.bool())),+ ),+ )+ ),+ "src": attrs.source(),+ "xml": attrs.bool(default = False),+ "_apple_tools": attrs.exec_dep(default = "prelude//apple/tools:apple-tools", providers = [AppleToolsInfo]),+ },+)++apple_rules = struct(+ apple_app_intents = apple_app_intents,+ apple_asset_catalog = apple_asset_catalog,+ apple_binary = apple_binary,+ apple_bundle = apple_bundle,+ apple_info_plist = apple_info_plist,+ apple_library = apple_library,+ apple_library_for_distribution = apple_library_for_distribution,+ apple_macos_bundle = apple_macos_bundle,+ apple_metal_library = apple_metal_library,+ apple_package = apple_package,+ apple_ipa_package = apple_ipa_package,+ apple_provisioning_profile_sources = apple_provisioning_profile_sources,+ apple_resource = apple_resource,+ apple_test = apple_test,+ apple_toolchain = apple_toolchain,+ apple_tools = apple_tools,+ apple_resource_bundle = apple_resource_bundle,+ apple_resource_dedupe_alias = apple_resource_dedupe_alias,+ apple_selective_debugging = apple_selective_debugging,+ apple_simulators = apple_simulators,+ apple_spm_package = apple_spm_package,+ apple_static_archive = apple_static_archive,+ apple_universal_executable = apple_universal_executable,+ apple_watchos_bundle = apple_watchos_bundle,+ apple_xcframework = apple_xcframework,+ apple_xcuitest = apple_xcuitest,+ core_data_model = core_data_model,+ cxx_universal_executable = cxx_universal_executable,+ mockingbird_mock = mockingbird_mock,+ prebuilt_apple_framework = prebuilt_apple_framework,+ required_reasons_tools = required_reasons_tools,+ resource_group_map = resource_group_map,+ scene_kit_assets = scene_kit_assets,+ swift_toolchain = swift_toolchain,+)
@@ -0,0 +1,15 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# @oss-disable[end= ]: load("@prelude//apple/meta_only:meta_only_rules.bzl", "meta_only_apple_rule_attributes", "meta_only_apple_rule_implementations")++# @oss-disable[end= ]: implemented_rules = {} | meta_only_apple_rule_implementations()+implemented_rules = {} # @oss-enable++# @oss-disable[end= ]: extra_attributes = {} | meta_only_apple_rule_attributes()+extra_attributes = {} # @oss-enable
@@ -0,0 +1,306 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:attrs_validators.bzl", "validation_common")+load("@prelude//apple:apple_bundle_types.bzl", "AppleBundleResourceInfo", "AppleBundleTypeAttributeType")+load("@prelude//apple:apple_code_signing_types.bzl", "CodeSignConfiguration", "CodeSignType")+load("@prelude//apple:apple_common.bzl", "apple_common")+load("@prelude//apple:apple_test_device_types.bzl", "AppleTestDeviceType")+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")+load("@prelude//apple:resource_groups.bzl", "RESOURCE_GROUP_MAP_ATTR")+load("@prelude//apple/swift:swift_incremental_support.bzl", "SwiftCompilationMode")+load("@prelude//apple/user:apple_selective_debugging.bzl", "AppleSelectiveDebuggingInfo")+load("@prelude//apple/user:cpu_split_transition.bzl", "cpu_split_transition")+load("@prelude//cxx:headers.bzl", "CPrecompiledHeaderInfo")+load("@prelude//ide_integrations/xcode:scheme_settings.bzl", "XCODE_SCHEME_SETTINGS_ATTR_NAME", "XCODE_SCHEME_SETTINGS_ATTR_TYPE")+load("@prelude//linking:execution_preference.bzl", "link_execution_preference_attr")+load("@prelude//linking:link_info.bzl", "LinkOrdering")+load("@prelude//utils:buckconfig.bzl", "read_bool")+load("@prelude//utils:clear_platform.bzl", "clear_platform_transition")++AppleFrameworkBundleModuleMapType = ["auto"]++def get_apple_bundle_toolchain_attr():+ return attrs.toolchain_dep(default = "toolchains//:apple-bundle", providers = [AppleToolchainInfo])++def get_apple_resources_toolchain_attr():+ return attrs.toolchain_dep(default = "toolchains//:apple-resources", providers = [AppleToolchainInfo])++def get_apple_xctoolchain_attr():+ return attrs.toolchain_dep(default = "toolchains//:apple-xctoolchain")++def get_apple_xctoolchain_bundle_id_attr():+ return attrs.toolchain_dep(default = "toolchains//:apple-xctoolchain-bundle-id")++def get_enable_library_evolution():+ return attrs.bool(+ default = select({+ "DEFAULT": False,+ "config//features/apple:swift_library_evolution_enabled": True,+ })+ )++def _strict_provisioning_profile_search_default_attr():+ default_value = read_root_config("apple", "strict_provisioning_profile_search", "true").lower() == "true"+ return attrs.bool(+ default = select({+ "DEFAULT": default_value,+ "config//features/apple:strict_provisioning_profile_search_enabled": True,+ })+ )++def _fast_adhoc_signing_enabled_default_attr():+ return attrs.bool(+ default = select({+ "DEFAULT": True,+ "config//features/apple:fast_adhoc_signing_disabled": False,+ "config//features/apple:fast_adhoc_signing_enabled": True,+ })+ )++def _skip_adhoc_resigning_scrubbed_frameworks_default_attr():+ default_value = read_root_config("apple", "skip_adhoc_resigning_scrubbed_frameworks", "").lower() == "true"+ return attrs.bool(+ default = select({+ "DEFAULT": default_value,+ "config//features/apple/constraints:skip_adhoc_resigning_scrubbed_frameworks_disabled": False,+ "config//features/apple/constraints:skip_adhoc_resigning_scrubbed_frameworks_enabled": True,+ })+ )++def _versioned_macos_bundle_default_value():+ return select({+ "DEFAULT": False,+ "config//features/apple/constraints:versioned_macos_bundle_false": False,+ "config//features/apple/constraints:versioned_macos_bundle_true": True,+ })++def _include_build_info_file_default_value():+ return select({+ "DEFAULT": select({+ "DEFAULT": read_root_config("apple", "include_build_info_file", "false").lower() == "true",+ # Unless explicitly requested, production builds (aka App Store/Developer ID) do not include internal build info file+ "config//build_mode/apple/constraints:build_mode[production]": False,+ }),+ "config//features/apple/constraints:include_build_info_file[disabled]": False,+ "config//features/apple/constraints:include_build_info_file[enabled]": True,+ })++APPLE_ARCHIVE_OBJECTS_LOCALLY_OVERRIDE_ATTR_NAME = "_archive_objects_locally_override"+APPLE_USE_ENTITLEMENTS_WHEN_ADHOC_CODE_SIGNING_CONFIG_OVERRIDE_ATTR_NAME = "_use_entitlements_when_adhoc_code_signing"+APPLE_USE_ENTITLEMENTS_WHEN_ADHOC_CODE_SIGNING_ATTR_NAME = "use_entitlements_when_adhoc_code_signing"+APPLE_EMBED_PROVISIONING_PROFILE_WHEN_ADHOC_CODE_SIGNING_CONFIG_OVERRIDE_ATTR_NAME = "_embed_provisioning_profile_when_adhoc_code_signing"+APPLE_EMBED_PROVISIONING_PROFILE_WHEN_ADHOC_CODE_SIGNING_ATTR_NAME = "embed_provisioning_profile_when_adhoc_code_signing"++APPLE_VALIDATION_DEPS_ATTR_NAME = "validation_deps"+APPLE_VALIDATION_DEPS_ATTR_TYPE = attrs.set(attrs.dep(), sorted = True, default = [])++def get_apple_info_plist_build_system_identification_attrs():+ return {+ "info_plist_identify_build_system": attrs.option(attrs.bool(), default = None),+ "_info_plist_identify_build_system_default": attrs.bool(default = False),+ }++def get_skip_swift_incremental_outputs_attrs():+ return {+ "_skip_swift_incremental_outputs": attrs.bool(default = read_bool("apple", "skip_swift_incremental_outputs", False, False, True)),+ }++def get_swift_incremental_file_hashing_attrs():+ return {+ "swift_incremental_file_hashing": attrs.bool(default = read_bool("apple", "swift_incremental_file_hashing", False, False, True)),+ }++def get_swift_incremental_remote_outputs_attrs():+ return {+ "incremental_remote_outputs": attrs.bool(default = read_bool("apple", "incremental_remote_outputs", False, False, True)),+ }++def get_swift_incremental_logging_attrs():+ return {+ "swift_incremental_logging": attrs.bool(default = read_bool("apple", "swift_incremental_logging_enabled", False, False, True)),+ }++def get_incremental_split_actions_attrs():+ return {+ "_swift_incremental_split_actions": attrs.bool(default = read_bool("apple", "swift_incremental_split_actions", False, False, True)),+ }++def get_incremental_swiftmodule_action_attrs():+ return {+ "_swift_incremental_swiftmodule_action": attrs.bool(default = read_bool("apple", "swift_incremental_swiftmodule_action", False, False, True)),+ }++def _apple_bundle_like_common_attrs():+ # `apple_bundle()` and `apple_test()` share a common set of extra attrs+ attribs = {+ # Target-level attribute always takes precedence over buckconfigs.+ "code_signing_configuration": attrs.option(attrs.enum(CodeSignConfiguration.values()), default = None),+ "codesign_type": attrs.option(attrs.enum(CodeSignType.values()), default = None),+ "entitlements_verification_check_enabled": attrs.bool(+ default = select({+ "DEFAULT": read_bool("apple", "entitlements_verification_check_enabled", default = True, root_cell = True),+ "config//features/apple:entitlements_verification_check_disabled": False,+ "config//features/apple:entitlements_verification_check_enabled": True,+ })+ ),+ "fast_adhoc_signing_enabled": attrs.option(attrs.bool(), default = None),+ "include_build_info_file": attrs.bool(default = _include_build_info_file_default_value()),+ "include_build_info_file_in_bundles_with_extensions": attrs.list(attrs.string(), default = ["app"]),+ "provisioning_profile_filter": attrs.option(attrs.string(), default = None),+ "skip_adhoc_resigning_scrubbed_frameworks": attrs.option(attrs.bool(), default = None),+ "strict_provisioning_profile_search": attrs.option(attrs.bool(), default = None),+ "versioned_macos_bundle": attrs.bool(default = _versioned_macos_bundle_default_value()),+ "_apple_xctoolchain": get_apple_xctoolchain_attr(),+ "_apple_xctoolchain_bundle_id": get_apple_xctoolchain_bundle_id_attr(),+ "_bundling_cache_buster": attrs.option(attrs.string(), default = None),+ "_bundling_log_file_enabled": attrs.bool(default = False),+ "_bundling_log_file_level": attrs.option(attrs.string(), default = None),+ "_code_signing_configuration": attrs.option(attrs.enum(CodeSignConfiguration.values()), default = None),+ "_codesign_command_override": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "_codesign_identities_command_override": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),+ "_codesign_type": attrs.option(attrs.enum(CodeSignType.values()), default = None),+ "_compile_resources_locally_override": attrs.option(attrs.bool(), default = None),+ "_fast_adhoc_signing_enabled_default": _fast_adhoc_signing_enabled_default_attr(),+ "_fast_adhoc_signing_probe_enabled": attrs.bool(default = False),+ "_fast_provisioning_profile_parsing_enabled": attrs.bool(default = False),+ "_incremental_bundling_enabled": attrs.bool(default = False),+ "_no_check_certificates": attrs.bool(default = False),+ "_profile_bundling_enabled": attrs.bool(default = False),+ "_provisioning_profile_sources": attrs.dep(default = "fbsource//xplat/buck2/platform/apple:provisioning_profile_sources"),+ "_resource_bundle": attrs.option(attrs.dep(providers = [AppleBundleResourceInfo]), default = None),+ "_skip_adhoc_resigning_scrubbed_frameworks_default": _skip_adhoc_resigning_scrubbed_frameworks_default_attr(),+ "_skip_adhoc_resigning_scrubbed_frameworks_override": attrs.option(attrs.bool(), default = None),+ "_strict_provisioning_profile_search_default": _strict_provisioning_profile_search_default_attr(),+ APPLE_USE_ENTITLEMENTS_WHEN_ADHOC_CODE_SIGNING_CONFIG_OVERRIDE_ATTR_NAME: attrs.option(attrs.bool(), default = None),+ APPLE_USE_ENTITLEMENTS_WHEN_ADHOC_CODE_SIGNING_ATTR_NAME: attrs.bool(default = False),+ APPLE_EMBED_PROVISIONING_PROFILE_WHEN_ADHOC_CODE_SIGNING_CONFIG_OVERRIDE_ATTR_NAME: attrs.option(attrs.bool(), default = None),+ APPLE_EMBED_PROVISIONING_PROFILE_WHEN_ADHOC_CODE_SIGNING_ATTR_NAME: attrs.bool(default = False),+ APPLE_VALIDATION_DEPS_ATTR_NAME: APPLE_VALIDATION_DEPS_ATTR_TYPE,+ XCODE_SCHEME_SETTINGS_ATTR_NAME: XCODE_SCHEME_SETTINGS_ATTR_TYPE,+ }+ attribs.update(get_apple_info_plist_build_system_identification_attrs())+ attribs.update(apple_common.apple_tools_arg())+ attribs.update(apple_common.enforce_minimum_os_plist_key())+ return attribs++def apple_test_extra_attrs():+ # To build an `apple_test`, one needs to first build a shared `apple_library` then+ # wrap this test library into an `apple_bundle`. Because of this, `apple_test` has attributes+ # from both `apple_library` and `apple_bundle`.+ attribs = {+ # Expected by `apple_bundle`, for `apple_test` this field is always None.+ "binary": attrs.option(attrs.dep(), default = None),+ "enable_library_evolution": attrs.option(attrs.bool(), default = None),+ # The resulting test bundle should have .xctest extension.+ "extension": attrs.string(),+ "link_execution_preference": link_execution_preference_attr(),+ "link_ordering": attrs.option(attrs.enum(LinkOrdering.values()), default = None),+ "precompiled_header": attrs.option(attrs.dep(providers = [CPrecompiledHeaderInfo]), default = None),+ # Expected by `apple_bundle`, for `apple_test` this field is always None.+ "resource_group": attrs.option(attrs.string(), default = None),+ # Expected by `apple_bundle`, for `apple_test` this field is always None.+ "resource_group_map": attrs.option(attrs.string(), default = None),+ "sanitizer_runtime_enabled": attrs.option(attrs.bool(), default = None),+ # Tests default to unstripped so they can be debugged.+ "strip_level": attrs.default_only(attrs.string(default = "unstripped")),+ "swift_compilation_mode": attrs.enum(SwiftCompilationMode.values(), default = "wmo"),+ "swift_package_name": attrs.option(attrs.string(), default = None),+ "swift_testing": attrs.bool(default = False),+ "test_device_type": attrs.enum(AppleTestDeviceType.values(), default = "default"),+ "test_re_capabilities": attrs.option(+ attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False),+ default = None,+ doc = """+ An optional dictionary with the RE capabilities for the test execution.+ Overrides a default selection mechanism.+ """,+ ),+ "test_re_use_case": attrs.option(+ attrs.string(),+ default = None,+ doc = """+ An optional name of the RE use case for the test execution.+ Overrides a default selection mechanism.+ """,+ ),+ "_enable_library_evolution": get_enable_library_evolution(),+ "_ipad_simulator": attrs.transition_dep(+ cfg = clear_platform_transition, default = "fbsource//xplat/buck2/platform/apple:ipad_simulator", providers = [LocalResourceInfo]+ ),+ "_iphone_booted_simulator": attrs.transition_dep(+ cfg = clear_platform_transition, default = "fbsource//xplat/buck2/platform/apple:iphone_booted_simulator", providers = [LocalResourceInfo]+ ),+ "_iphone_unbooted_simulator": attrs.transition_dep(+ cfg = clear_platform_transition, default = "fbsource//xplat/buck2/platform/apple:iphone_unbooted_simulator", providers = [LocalResourceInfo]+ ),+ "_swift_enable_testing": attrs.default_only(attrs.bool(default = True)),+ "_watch_simulator": attrs.transition_dep(+ cfg = clear_platform_transition, default = "fbsource//xplat/buck2/platform/apple:watch_simulator", providers = [LocalResourceInfo]+ ),+ } | validation_common.attrs_validators_arg()+ attribs.update(apple_common.apple_toolchain_arg())+ attribs.update(apple_common.minimum_os_version_arg())+ attribs.update(_apple_bundle_like_common_attrs())+ attribs.update(get_swift_incremental_file_hashing_attrs())+ attribs.update(get_swift_incremental_logging_attrs())+ attribs.update(get_skip_swift_incremental_outputs_attrs())+ attribs.update(get_incremental_split_actions_attrs())+ attribs.update(get_incremental_swiftmodule_action_attrs())+ return attribs++def apple_xcuitest_extra_attrs():+ attribs = {+ # This is ignored, but required for info plist processing.+ "binary": attrs.option(attrs.source(), default = None),+ "codesign_identity": attrs.option(attrs.string(), default = None),+ "enable_library_evolution": attrs.option(attrs.bool(), default = None),+ "entitlements_file": attrs.option(attrs.source(), default = None),+ "extension": attrs.default_only(attrs.string(default = "app")),+ "incremental_bundling_enabled": attrs.bool(default = False),+ "info_plist": attrs.source(),+ "info_plist_substitutions": attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False, default = {}),+ # The test bundle to package in the UI test runner app.+ "test_bundle": attrs.dep(),+ "_enable_library_evolution": get_enable_library_evolution(),+ }+ attribs.update(apple_common.target_sdk_version())+ attribs.update(apple_common.apple_toolchain_arg())+ attribs.update(_apple_bundle_like_common_attrs())++ return attribs++def _embed_xctest_frameworks_default_value():+ return select({+ "DEFAULT": False,+ # Xcode copies XCTest frameworks to test host apps, required when the+ # selected Xcode version != Xcode version used to build an app under test+ "config//marker/apple/constraints:embed_xctest_frameworks[enabled]": True,+ })++def apple_bundle_extra_attrs():+ attribs = {+ "binary": attrs.option(attrs.split_transition_dep(cfg = cpu_split_transition), default = None),+ "bundle_type": attrs.option(attrs.enum(AppleBundleTypeAttributeType.values()), default = None),+ "copy_public_framework_headers": attrs.option(attrs.bool(), default = None),+ "embed_xctest_frameworks": attrs.bool(default = _embed_xctest_frameworks_default_value()),+ "module_map": attrs.option(attrs.one_of(attrs.enum(AppleFrameworkBundleModuleMapType), attrs.source()), default = None),+ "resource_group_map": RESOURCE_GROUP_MAP_ATTR,+ "selective_debugging": attrs.option(attrs.dep(providers = [AppleSelectiveDebuggingInfo]), default = None),+ "split_arch_dsym": attrs.bool(default = False),+ "universal": attrs.option(attrs.bool(), default = None),+ "validate_rrapi_usage": attrs.bool(default = False),+ "_apple_toolchain": get_apple_bundle_toolchain_attr(),+ "_codesign_entitlements": attrs.option(attrs.source(), default = None),+ }+ attribs.update(_apple_bundle_like_common_attrs())+ attribs.update(apple_common.entitlements_suffixed_key_map_arg())+ attribs.update(apple_common.entitlements_removed_keys_arg())+ attribs.update(apple_common.entitlements_removed_values_map_arg())+ attribs.update(apple_common.minimum_os_version_arg())+ return attribs
@@ -0,0 +1,16 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")++def get_apple_sdk_name(ctx: AnalysisContext) -> str:+ """+ Get the SDK defined on the toolchain.+ Will throw if the `_apple_toolchain` is not present.+ """+ return ctx.attrs._apple_toolchain[AppleToolchainInfo].sdk_name
@@ -0,0 +1,105 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++AppleSdkMetadata = record(+ name = field(str),+ target_device_flags = field(list[str], []),+ is_ad_hoc_code_sign_sufficient = field(bool),+ info_plist_supported_platforms_values = field(list[str]),+ min_version_plist_info_key = field(str),+ actool_platform_override = field([str, None], None),+)++IPhoneOSSdkMetadata = AppleSdkMetadata(+ name = "iphoneos",+ target_device_flags = ["--target-device", "iphone", "--target-device", "ipad"],+ is_ad_hoc_code_sign_sufficient = False,+ info_plist_supported_platforms_values = ["iPhoneOS"],+ min_version_plist_info_key = "MinimumOSVersion",+)++IPhoneSimulatorSdkMetadata = AppleSdkMetadata(+ name = "iphonesimulator",+ target_device_flags = ["--target-device", "iphone", "--target-device", "ipad"],+ is_ad_hoc_code_sign_sufficient = True,+ info_plist_supported_platforms_values = ["iPhoneSimulator"],+ min_version_plist_info_key = "MinimumOSVersion",+)++TVOSSdkMetadata = AppleSdkMetadata(+ name = "appletvos",+ target_device_flags = ["--target-device", "tv"],+ is_ad_hoc_code_sign_sufficient = False,+ info_plist_supported_platforms_values = ["AppleTVOS"],+ min_version_plist_info_key = "MinimumOSVersion",+)++TVSimulatorSdkMetadata = AppleSdkMetadata(+ name = "appletvsimulator",+ target_device_flags = ["--target-device", "tv"],+ is_ad_hoc_code_sign_sufficient = True,+ info_plist_supported_platforms_values = ["AppleTVSimulator"],+ min_version_plist_info_key = "MinimumOSVersion",+)++WatchOSSdkMetadata = AppleSdkMetadata(+ name = "watchos",+ target_device_flags = ["--target-device", "watch"],+ is_ad_hoc_code_sign_sufficient = False,+ info_plist_supported_platforms_values = ["WatchOS"],+ min_version_plist_info_key = "MinimumOSVersion",+)++WatchSimulatorSdkMetadata = AppleSdkMetadata(+ name = "watchsimulator",+ target_device_flags = ["--target-device", "watch"],+ is_ad_hoc_code_sign_sufficient = True,+ info_plist_supported_platforms_values = ["WatchSimulator"],+ min_version_plist_info_key = "MinimumOSVersion",+)++MacOSXSdkMetadata = AppleSdkMetadata(+ name = "macosx",+ target_device_flags = ["--target-device", "mac"],+ is_ad_hoc_code_sign_sufficient = True,+ info_plist_supported_platforms_values = ["MacOSX"],+ min_version_plist_info_key = "LSMinimumSystemVersion",+)++MacOSXCatalystSdkMetadata = AppleSdkMetadata(+ name = "maccatalyst",+ target_device_flags = [+ "--target-device",+ # TODO(T112097815): Support for macOS idiom+ "ipad",+ # Needed so that `actool` works generates app icons correctly+ "--ui-framework-family",+ "uikit",+ ],+ is_ad_hoc_code_sign_sufficient = True,+ info_plist_supported_platforms_values = ["MacOSX"],+ min_version_plist_info_key = "LSMinimumSystemVersion",+ actool_platform_override = "macosx",+)++_SDK_MAP = {+ IPhoneOSSdkMetadata.name: IPhoneOSSdkMetadata,+ IPhoneSimulatorSdkMetadata.name: IPhoneSimulatorSdkMetadata,+ TVOSSdkMetadata.name: TVOSSdkMetadata,+ TVSimulatorSdkMetadata.name: TVSimulatorSdkMetadata,+ WatchOSSdkMetadata.name: WatchOSSdkMetadata,+ WatchSimulatorSdkMetadata.name: WatchSimulatorSdkMetadata,+ MacOSXSdkMetadata.name: MacOSXSdkMetadata,+ MacOSXCatalystSdkMetadata.name: MacOSXCatalystSdkMetadata,+}++def get_apple_sdk_metadata_for_sdk_name(name: str) -> AppleSdkMetadata:+ sdk = _SDK_MAP.get(name)+ if sdk == None:+ fail("unrecognized sdk name: `{}`".format(name))+ return sdk
@@ -0,0 +1,27 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++def apple_simulators_impl(ctx: AnalysisContext) -> list[Provider]:+ cmd_args_list = [ctx.attrs.broker[RunInfo], "--simulator-manager", ctx.attrs.idb_targets[RunInfo]] + ctx.attrs.args+ simulator_os_version = ctx.attrs._simulator_os_version+ simulator_device = ctx.attrs._simulator_device+ if simulator_os_version:+ cmd_args_list += ["--os_version", simulator_os_version]+ if simulator_device:+ cmd_args_list += ["--device", simulator_device]+ return [+ DefaultInfo(),+ LocalResourceInfo(+ setup = cmd_args(cmd_args_list),+ resource_env_vars = {+ "DEVICE_SET_PATH": "device_set_path",+ "DEVICE_UDID": "udid",+ },+ setup_timeout_seconds = ctx.attrs.setup_timeout_seconds,+ ),+ ]
@@ -0,0 +1,110 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:artifact_tset.bzl", "make_artifact_tset")+load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")+load("@prelude//apple:apple_library.bzl", "AppleLibraryForDistributionInfo")+load("@prelude//apple:apple_library_types.bzl", "AppleLibraryInfo")+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo", "AppleToolsInfo")+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")+load("@prelude//linking:link_info.bzl", "LinkStrategy", "get_link_args_for_strategy", "unpack_link_args_object_files_and_lazy_archives_only")+load("@prelude//linking:linkables.bzl", "linkables")+load("@prelude//utils:arglike.bzl", "ArgLike")++def apple_static_archive_impl(ctx: AnalysisContext) -> list[Provider]:+ libtool = ctx.attrs._apple_toolchain[AppleToolchainInfo].libtool+ static_archive_linker = ctx.attrs._apple_tools[AppleToolsInfo].static_archive_linker+ archive_name = ctx.attrs.name if ctx.attrs.archive_name == None else ctx.attrs.archive_name+ output = ctx.actions.declare_output(archive_name, has_content_based_path = False)++ link_args = _get_static_link_args(ctx)+ validation_deps_outputs = get_validation_deps_outputs(ctx)++ # TODO(T193127271): Support thin archives+ cmd = cmd_args([static_archive_linker, "--libtool", libtool, "--output", output.as_output(), link_args], hidden = validation_deps_outputs or [])+ ctx.actions.run(cmd, category = "static_archive_linker", identifier = output.short_path)++ providers = [DefaultInfo(default_output = output), _get_apple_library_info(ctx)] + _get_apple_library_for_distribution_info(ctx)++ return providers++def _get_apple_library_for_distribution_info(ctx: AnalysisContext) -> list[AppleLibraryForDistributionInfo]:+ if ctx.attrs.distribution_flat_dep != None:+ apple_library_for_distribution = ctx.attrs.distribution_flat_dep.get(AppleLibraryForDistributionInfo)+ if apple_library_for_distribution != None:+ return [apple_library_for_distribution]+ return []++def _get_apple_library_info(ctx: AnalysisContext) -> AppleLibraryInfo:+ all_flat_deps = filter(None, ctx.attrs.flat_deps + [ctx.attrs.distribution_flat_dep])+ flat_apple_library_infos = filter(None, [dep.get(AppleLibraryInfo) for dep in all_flat_deps])+ flat_public_framework_headers = []+ for apple_library_info in flat_apple_library_infos:+ tset = apple_library_info.public_framework_headers._tset+ if tset != None and tset.value:+ for headers in tset.value:+ flat_public_framework_headers += headers.artifacts++ flat_header_tset = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ artifacts = flat_public_framework_headers,+ )++ apple_library_infos = filter(None, [dep.get(AppleLibraryInfo) for dep in ctx.attrs.deps])+ public_framework_header_tset = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ children = [apple_library.public_framework_headers for apple_library in apple_library_infos] + [flat_header_tset],+ )++ swift_header = None+ if ctx.attrs.distribution_flat_dep != None:+ distribution_flat_dep_apple_library_info = ctx.attrs.distribution_flat_dep.get(AppleLibraryInfo)+ if distribution_flat_dep_apple_library_info:+ swift_header = distribution_flat_dep_apple_library_info.swift_header++ return AppleLibraryInfo(+ public_framework_headers = public_framework_header_tset,+ swift_header = swift_header,+ target = ctx.label,+ labels = ctx.attrs.labels,+ )++def _get_static_link_args(ctx: AnalysisContext) -> list[ArgLike]:+ args = []++ for dep in ctx.attrs.flat_deps:+ default_info = dep.get(DefaultInfo)+ if default_info == None:+ continue+ default_outputs = default_info.default_outputs+ if len(default_outputs) > 0:+ args.append(default_outputs[0])++ if ctx.attrs.distribution_flat_dep:+ default_info = ctx.attrs.distribution_flat_dep.get(DefaultInfo)+ if default_info != None:+ default_outputs = default_info.default_outputs+ if len(default_outputs) > 0:+ args.append(default_outputs[0])++ args = dedupe(args)++ transitive_link_args = get_link_args_for_strategy(+ ctx.actions,+ ctx.label,+ get_cxx_toolchain_info(ctx).linker_info,+ [x.merged_link_info for x in linkables(ctx.attrs.deps)],+ LinkStrategy("static"),+ prefer_stripped = False,+ transformation_spec_context = None,+ )+ args.append(unpack_link_args_object_files_and_lazy_archives_only(transitive_link_args))++ return args
@@ -0,0 +1,24 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")+load("@prelude//utils:expect.bzl", "expect")++def apple_strip_args(ctx: AnalysisContext) -> cmd_args:+ strip_flags_info = get_cxx_toolchain_info(ctx).strip_flags_info+ if ctx.attrs.strip_level == "non_global":+ flags = strip_flags_info.strip_non_global_flags+ elif ctx.attrs.strip_level == "all":+ flags = strip_flags_info.strip_all_flags+ elif ctx.attrs.strip_level == "debug":+ flags = strip_flags_info.strip_debug_flags+ else:+ fail("Unexpected strip level: " + ctx.attrs.strip_level)++ expect(flags != None, "Strip flags are missing on toolchain")+ return cmd_args(flags)
@@ -0,0 +1,15 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++_SKIP_COPYING_SWIFT_STDLIB_EXTENSIONS = [+ ".framework",+ ".appex",+]++def should_copy_swift_stdlib(bundle_extension: str) -> bool:+ return bundle_extension not in _SKIP_COPYING_SWIFT_STDLIB_EXTENSIONS
@@ -0,0 +1,96 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:versions.bzl", "TARGET_SDK_VERSIONS")+load("@prelude//cxx:target_sdk_version.bzl", "get_target_sdk_version")++# Taken from SDKSettings.json[VersionMap][iOSMac_macOS]+_MACCATALYST_IOS_TO_MACOS_VERSION_MAP = {+ "13.0": "10.15", # Catalina+ "13.1": "10.15",+ "13.2": "10.15.1",+ "13.3": "10.15.2",+ "13.3.1": "10.15.3",+ "13.4": "10.15.4",+ "13.5": "10.15.5",+ "13.6": "10.15.5", # Xcode reported 10.15+ "14.0": "11.0", # Big Sur+ "14.1": "11.0",+ "14.2": "11.0",+ "14.3": "11.1",+ "14.4": "11.2",+ "14.5": "11.3",+ "14.6": "11.4",+ "14.7": "11.5",+ "15.0": "12.0", # Monterey+ "15.1": "12.1", # Xcode reported 10.15+ "15.2": "12.1",+ "15.3": "12.2",+ "15.4": "12.3",+ "15.5": "12.4",+ "15.6": "12.5",+ "16.0": "13.0", # Ventura+ "16.1": "13.0",+ "16.2": "13.1",+ "16.3": "13.2",+ "16.4": "13.3",+ "16.5": "13.4",+ "16.6": "13.5",+ "17.0": "14.0", # Sonoma+ "17.1": "14.1",+ "17.2": "14.2",+ "17.3": "14.3",+ "17.4": "14.4",+ "17.5": "14.5",+ "18.0": "15.0", # Sequoia+ "18.1": "15.1",+ "18.2": "15.2",+ "18.3": "15.3",+ "18.4": "15.4",+ "18.5": "15.5",+ "18.6": "15.6",+ "19.0": "16.0", # Tahoe+}++_SDK_NAME_TO_PLATFORM_NAME_OVERRIDE_MAP = {+ "maccatalyst": "macosx",+}++def get_target_sdk_version_map() -> dict[str, str]:+ return {+ maccatalyst_version: "config//version:constraint-value-target-sdk-version-{}".format(macos_version)+ for maccatalyst_version, macos_version in _MACCATALYST_IOS_TO_MACOS_VERSION_MAP.items()+ if macos_version in TARGET_SDK_VERSIONS+ }++def get_platform_version_for_sdk_version(sdk_name: str, sdk_version: str) -> str:+ if sdk_name == "maccatalyst":+ sdk_major, _ = sdk_version.split(".", 2)++ # Version numbers are aligned from 26 and up+ if int(sdk_major) >= 26:+ return sdk_version++ macos_version = _MACCATALYST_IOS_TO_MACOS_VERSION_MAP.get(sdk_version, None)+ if macos_version == None:+ fail("No macos version for maccatalyst version {}".format(sdk_version))+ return macos_version++ return sdk_version++def get_platform_name_for_sdk(sdk_name: str) -> str:+ return _SDK_NAME_TO_PLATFORM_NAME_OVERRIDE_MAP.get(sdk_name, sdk_name)++# Returns the target_sdk_version specified for this build, falling+# back to the toolchain version when unset.+def get_min_deployment_version_for_node(ctx: AnalysisContext) -> str:+ version = get_target_sdk_version(ctx)+ if version == None:+ fail("No target_sdk_version set on target or toolchain")++ return version
@@ -0,0 +1,421 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "project_artifacts",+)+load("@prelude//apple:apple_library.bzl", "AppleLibraryAdditionalParams", "apple_library_rule_constructor_params_and_swift_providers")+load("@prelude//apple:apple_test_device_types.bzl", "AppleTestDeviceType", "get_default_test_device", "tpx_label_for_test_device_type")+load("@prelude//apple:apple_test_frameworks_utility.bzl", "get_test_frameworks_bundle_parts")+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")+# @oss-disable[end= ]: load("@prelude//apple/meta_only:apple_test_local_execution.bzl", "local_test_execution_is_available")+# @oss-disable[end= ]: load("@prelude//apple/meta_only:apple_test_re_capabilities.bzl", "apple_test_re_capabilities")+# @oss-disable[end= ]: load("@prelude//apple/meta_only:apple_test_re_use_case.bzl", "apple_test_re_use_case")+load("@prelude//apple/swift:swift_compilation.bzl", "get_swift_anonymous_targets")+load("@prelude//apple/swift:swift_helpers.bzl", "uses_explicit_modules")+load(+ "@prelude//cxx:argsfiles.bzl",+ "CompileArgsfile", # @unused Used as a type+)+load("@prelude//cxx:cxx_library.bzl", "cxx_library_parameterized")+load(+ "@prelude//cxx:cxx_sources.bzl",+ "CxxSrcWithFlags", # @unused Used as a type+)+load("@prelude//cxx:cxx_types.bzl", "CxxRuleProviderParams", "CxxRuleSubTargetParams", "xcode_data_enabled")+load(+ "@prelude//cxx:linker.bzl",+ "SharedLibraryFlagOverrides",+)+load("@prelude//ide_integrations/xcode:data.bzl", "XcodeDataInfoKeys")+load("@prelude//target_stats:target_stats_types.bzl", "TargetStatsInfo")+load(+ "@prelude//utils:dicts.bzl",+ "flatten_x",+)+load("@prelude//utils:expect.bzl", "expect")+load(":apple_bundle.bzl", "AppleBundlePartListConstructorParams", "get_apple_bundle_part_list")+load(":apple_bundle_destination.bzl", "AppleBundleDestination", "bundle_relative_path_for_destination")+load(":apple_bundle_part.bzl", "AppleBundlePart", "assemble_bundle", "bundle_output", "get_bundle_dir_name")+load(":apple_bundle_types.bzl", "AppleBundleInfo")+load(":apple_bundle_utility.bzl", "get_product_name")+load(+ ":apple_dsym.bzl",+ "DSYM_SUBTARGET",+ "DWARF_AND_DSYM_SUBTARGET",+ "EXTENDED_DSYM_INFO_SUBTARGET",+ "get_apple_dsym",+ "get_apple_dsym_info_json",+ "get_deps_debuggable_infos",+)+load(":apple_entitlements.bzl", "entitlements_link_flags")+load(":apple_rpaths.bzl", "get_rpath_flags_for_tests")+load(":apple_sdk.bzl", "get_apple_sdk_name")+load(":apple_sdk_metadata.bzl", "WatchSimulatorSdkMetadata")+load(":debug.bzl", "AppleDebuggableInfo")+load(":xcode.bzl", "apple_populate_xcode_attributes")+load(":xctest_swift_support.bzl", "XCTestSwiftSupportInfo")++_XCTOOLCHAIN_SUB_TARGET = "xctoolchain"++def apple_test_impl(ctx: AnalysisContext) -> [list[Provider], Promise]:+ def get_apple_test_providers(deps_providers) -> list[Provider]:+ xctest_bundle = bundle_output(ctx)++ test_host_app_bundle = _get_test_host_app_bundle(ctx)+ test_host_app_binary = _get_test_host_app_binary(ctx, test_host_app_bundle)+ ui_test_target_app_bundle = _get_ui_test_target_app_bundle(ctx)++ objc_bridging_header_flags = (+ [+ # Disable bridging header -> PCH compilation to mitigate an issue in Xcode 13 beta.+ "-disable-bridging-pch",+ "-import-objc-header",+ cmd_args(ctx.attrs.bridging_header),+ ]+ if ctx.attrs.bridging_header+ else []+ )++ shared_library_flags = ["-bundle"]++ # Embedding entitlements (if present) means that we can skip adhoc codesigning+ # any xctests altogether, provided the test dylib is adhoc signed+ shared_library_flags += entitlements_link_flags(ctx) + get_rpath_flags_for_tests(ctx)++ # The linker will include adhoc signature for ARM64 by default, lets+ # ensure we always have an adhoc signature regardless of arch/linker logic.+ shared_library_flags += ["-Wl,-adhoc_codesign"]++ constructor_params = apple_library_rule_constructor_params_and_swift_providers(+ ctx,+ AppleLibraryAdditionalParams(+ rule_type = "apple_test",+ extra_exported_link_flags = get_test_framework_linker_flags(ctx) + _get_bundle_loader_flags(test_host_app_binary),+ extra_swift_compiler_flags = _get_test_framework_search_paths_flags(ctx) + objc_bridging_header_flags,+ shared_library_flags = SharedLibraryFlagOverrides(+ # When `-bundle` is used we can't use the `-install_name` args, thus we keep this field empty.+ shared_library_name_linker_flags_format = [],+ # When building Apple tests, we want to link with `-bundle` instead of `-shared` to allow+ # linking against the bundle loader.+ shared_library_flags = shared_library_flags,+ ),+ generate_sub_targets = CxxRuleSubTargetParams(+ compilation_database = True,+ headers = False,+ link_group_map = False,+ xcode_data = xcode_data_enabled(),+ ),+ generate_providers = CxxRuleProviderParams(+ compilation_database = True,+ default = False,+ linkable_graph = False,+ link_style_outputs = True,+ merged_native_link_info = False,+ omnibus_root = False,+ preprocessors = False,+ resources = False,+ shared_libraries = False,+ template_placeholders = False,+ ),+ populate_xcode_attributes_func = lambda local_ctx, **kwargs: _xcode_populate_attributes(+ ctx = local_ctx, xctest_bundle = xctest_bundle, test_host_app_binary = test_host_app_binary, test_host_app_bundle = test_host_app_bundle, **kwargs+ ),+ # We want to statically link the transitive dep graph of the apple_test()+ # which we can achieve by forcing link group linking with+ # an empty mapping (i.e., default mapping).+ force_link_group_linking = True,+ ),+ deps_providers,+ is_test_target = True,+ )++ cxx_library_output = cxx_library_parameterized(ctx, constructor_params)++ # Locate the temporary binary that is bundled into the xctest in a binaries directory. When Xcode loads the test out of the target's output dir,+ # it will utilize a binary with the test name from the output dir instead of the xctest bundle. Which then results in paths to test resources+ # being incorrect. Locating the temporary binary elsewhere works around this issue.+ test_binary_output = ctx.actions.declare_output("__binaries__", get_product_name(ctx), has_content_based_path = False)++ # Rename in order to generate dSYM with correct binary name (dsymutil doesn't provide a way to control binary name in output dSYM bundle).+ test_binary = ctx.actions.copy_file(test_binary_output, cxx_library_output.default_output.default)++ binary_part = AppleBundlePart(source = test_binary, destination = AppleBundleDestination("executables"), new_name = ctx.attrs.name)+ part_list_output = get_apple_bundle_part_list(ctx, AppleBundlePartListConstructorParams(binaries = [binary_part]))++ xctest_swift_support_needed = None+ debug_info = None+ cxx_providers = []+ for p in cxx_library_output.providers:+ if isinstance(p, XCTestSwiftSupportInfo):+ xctest_swift_support_needed = p.support_needed+ elif isinstance(p, AppleDebuggableInfo):+ debug_info = project_artifacts(ctx.actions, p.debug_info_tset)+ elif isinstance(p, TargetStatsInfo):+ cxx_providers.append(p)+ elif isinstance(p, ValidationInfo):+ cxx_providers.append(p)+ expect(xctest_swift_support_needed != None, "Expected `XCTestSwiftSupportInfo` provider to be present")+ expect(debug_info != None, "Expected `AppleDebuggableInfo` provider to be present")++ bundle_parts = part_list_output.parts+ if not ctx.attrs.embed_xctest_frameworks_in_test_host_app and get_apple_sdk_name(ctx) != WatchSimulatorSdkMetadata.name:+ # The XCTest frameworks should only be embedded in a single place,+ # either the test host (as per Xcode) or in the test itself+ if test_host_app_bundle != None or read_root_config("apple", "exclude_xctest_libraries", "false").lower() != "true":+ bundle_parts += get_test_frameworks_bundle_parts(ctx, xctest_swift_support_needed)++ for sanitizer_runtime_dylib in cxx_library_output.sanitizer_runtime_files:+ frameworks_destination = AppleBundleDestination("frameworks")+ bundle_parts.append(+ AppleBundlePart(+ source = sanitizer_runtime_dylib,+ destination = frameworks_destination,+ codesign_on_copy = True,+ ),+ )++ bundle_result = assemble_bundle(+ ctx,+ xctest_bundle,+ bundle_parts,+ part_list_output.codesign_manifest_parts,+ part_list_output.signing_context_parts,+ part_list_output.info_plist_part,+ None, # swift_stdlib_args+ # Adhoc signing can be skipped because the test executable is adhoc signed+ # + includes any entitlements if present.+ skip_adhoc_signing = True,+ incremental_bundling_override = False,+ )+ sub_targets = bundle_result.sub_targets+ sub_targets.update(cxx_library_output.sub_targets)++ dsym_artifact = get_apple_dsym(+ ctx = ctx,+ executable = test_binary,+ debug_info = debug_info,+ action_identifier = "generate_apple_test_dsym",+ output_path_override = get_bundle_dir_name(ctx) + ".dSYM",+ )+ sub_targets[DSYM_SUBTARGET] = [DefaultInfo(default_output = dsym_artifact)]++ deps_debuggable_infos = get_deps_debuggable_infos(ctx)+ dep_dsym_artifacts = []+ for debuggable_info in deps_debuggable_infos:+ dep_dsym_artifacts.extend(debuggable_info.dsyms)++ dsym_json_info = get_apple_dsym_info_json([dsym_artifact], dep_dsym_artifacts)+ dsym_info = ctx.actions.write_json("extended-dsym-info.json", dsym_json_info.json_object, pretty = True, has_content_based_path = False)+ sub_targets[EXTENDED_DSYM_INFO_SUBTARGET] = [+ DefaultInfo(default_output = dsym_info, other_outputs = dsym_json_info.outputs),+ ]++ # If the test has a test host and a ui test target, add the subtargets to build the app bundles.+ sub_targets["test-host"] = [DefaultInfo(default_output = test_host_app_bundle)] if test_host_app_bundle else [DefaultInfo()]+ sub_targets["ui-test-target"] = [DefaultInfo(default_output = ui_test_target_app_bundle)] if ui_test_target_app_bundle else [DefaultInfo()]++ sub_targets[DWARF_AND_DSYM_SUBTARGET] = [+ DefaultInfo(+ default_output = xctest_bundle, other_outputs = [dsym_artifact], sub_targets = {_XCTOOLCHAIN_SUB_TARGET: ctx.attrs._apple_xctoolchain.providers}+ ),+ _get_test_info(ctx, xctest_bundle, test_host_app_bundle, dsym_artifact, ui_test_target_app_bundle),+ ]++ sub_targets[_XCTOOLCHAIN_SUB_TARGET] = ctx.attrs._apple_xctoolchain.providers++ return (+ filter(+ None,+ [+ DefaultInfo(default_output = xctest_bundle, sub_targets = sub_targets),+ _get_test_info(ctx, xctest_bundle, test_host_app_bundle, ui_test_target_app_bundle = ui_test_target_app_bundle),+ cxx_library_output.index_store_info,+ cxx_library_output.xcode_data_info,+ cxx_library_output.cxx_compilationdb_info,+ ],+ )+ + bundle_result.providers+ + cxx_providers+ )++ if uses_explicit_modules(ctx):+ return get_swift_anonymous_targets(ctx, get_apple_test_providers)+ else:+ return get_apple_test_providers([])++def _get_test_info(+ ctx: AnalysisContext,+ xctest_bundle: Artifact,+ test_host_app_bundle: Artifact | None,+ dsym_artifact: Artifact | None = None,+ ui_test_target_app_bundle: Artifact | None = None,+) -> Provider:+ # When interacting with Tpx, we just pass our various inputs via env vars,+ # since Tpx basically wants structured output for this.++ xctest_bundle = cmd_args(xctest_bundle, hidden = dsym_artifact) if dsym_artifact else xctest_bundle+ env = {"XCTEST_BUNDLE": xctest_bundle}++ if test_host_app_bundle == None:+ tpx_label = "tpx:apple_test:buck2:logicTest"+ else:+ env["HOST_APP_BUNDLE"] = test_host_app_bundle+ tpx_label = "tpx:apple_test:buck2:appTest"++ if ui_test_target_app_bundle != None:+ env["TARGET_APP_BUNDLE"] = ui_test_target_app_bundle+ tpx_label = "tpx:apple_test:buck2:uiTest"++ labels = ctx.attrs.labels+ labels.append(tpx_label)++ test_device_type = AppleTestDeviceType(ctx.attrs.test_device_type)+ if test_device_type == AppleTestDeviceType("default"):+ # determine the device type from the sdk and platform+ sdk_name = get_apple_sdk_name(ctx)+ test_device_type = get_default_test_device(sdk = sdk_name, platform = ctx.attrs.default_target_platform)+ labels.append(tpx_label_for_test_device_type(test_device_type))++ remote_execution_properties = None # @oss-enable+ remote_execution_use_case = None # @oss-enable++ # @oss-disable[end= ]: if ctx.attrs.test_re_capabilities:+ # @oss-disable[end= ]: remote_execution_properties = ctx.attrs.test_re_capabilities+ # @oss-disable[end= ]: else:+ # @oss-disable[end= ]: uses_test_host = test_host_app_bundle != None or ui_test_target_app_bundle != None+ # @oss-disable[end= ]: remote_execution_properties = apple_test_re_capabilities(test_device_type = test_device_type, uses_test_host = uses_test_host)+ # @oss-disable[end= ]: remote_execution_use_case = ctx.attrs.test_re_use_case or apple_test_re_use_case(test_device_type = test_device_type)++ # @oss-disable[end= ]: if local_test_execution_is_available():+ # @oss-disable[end= ]: labels.append("tpx:apple_test:local_execution_available")++ return ExternalRunnerTestInfo(+ type = "apple_test",+ command = ["false"], # Tpx makes up its own args, we just pass params via the env.+ env = flatten_x([ctx.attrs.env or {}, env]),+ labels = labels,+ use_project_relative_paths = True,+ run_from_project_root = True,+ contacts = ctx.attrs.contacts,+ executor_overrides = {+ "ios-simulator-local": CommandExecutorConfig(+ local_enabled = True,+ remote_enabled = False,+ remote_execution_properties = None,+ remote_execution_use_case = None,+ ),+ "ios-simulator-remote": CommandExecutorConfig(+ local_enabled = False,+ remote_enabled = True,+ remote_execution_properties = remote_execution_properties,+ remote_execution_use_case = remote_execution_use_case,+ ),+ "static-listing": CommandExecutorConfig(local_enabled = True, remote_enabled = False),+ },+ local_resources = {+ "ipad_simulator": ctx.attrs._ipad_simulator.label,+ "iphone_booted_simulator": ctx.attrs._iphone_booted_simulator.label,+ "iphone_unbooted_simulator": ctx.attrs._iphone_unbooted_simulator.label,+ "watch_simulator": ctx.attrs._watch_simulator.label,+ },+ )++def _get_test_host_app_bundle(ctx: AnalysisContext) -> Artifact | None:+ """Get the bundle for the test host app, if one exists for this test."""+ if ctx.attrs.test_host_app:+ # Copy the test host app bundle into test's output directory+ original_bundle = ctx.attrs.test_host_app[AppleBundleInfo].bundle+ test_host_app_bundle = ctx.actions.declare_output(original_bundle.basename, has_content_based_path = False)+ ctx.actions.copy_file(test_host_app_bundle, original_bundle)+ return test_host_app_bundle++ return None++def _get_test_host_app_binary(ctx: AnalysisContext, test_host_app_bundle: Artifact | None) -> [cmd_args, None]:+ """Reference to the binary with the test host app bundle, if one exists for this test. Captures the bundle as an artifact in the cmd_args."""+ if ctx.attrs.test_host_app == None:+ return None++ parts = [test_host_app_bundle]+ rel_path = bundle_relative_path_for_destination(AppleBundleDestination("executables"), get_apple_sdk_name(ctx), ctx.attrs.extension, False)+ if len(rel_path) > 0:+ parts.append(rel_path)+ parts.append(ctx.attrs.test_host_app[AppleBundleInfo].binary_name)+ return cmd_args(parts, delimiter = "/")++def _get_ui_test_target_app_bundle(ctx: AnalysisContext) -> Artifact | None:+ """Get the bundle for the ui test target app, if one exists for this test."""+ if ctx.attrs.ui_test_target_app:+ # Copy the ui test target app bundle into test's output directory+ original_bundle = ctx.attrs.ui_test_target_app[AppleBundleInfo].bundle+ ui_test_target_app_bundle = ctx.actions.declare_output(original_bundle.basename, has_content_based_path = False)+ ctx.actions.copy_file(ui_test_target_app_bundle, original_bundle)+ return ui_test_target_app_bundle++ return None++def _get_bundle_loader_flags(binary: [cmd_args, None]) -> list[typing.Any]:+ if binary:+ # During linking we need to link the test shared lib against the test host binary. The+ # test host binary doesn't need to be embedded in an `apple_bundle`.+ return ["-bundle_loader", binary]++ return []++def _xcode_populate_attributes(+ ctx: AnalysisContext,+ srcs: list[CxxSrcWithFlags],+ argsfiles: dict[str, CompileArgsfile],+ xctest_bundle: Artifact,+ test_host_app_binary: [cmd_args, None],+ test_host_app_bundle: Artifact | None,+ **_kwargs,+) -> dict[str, typing.Any]:+ data = apple_populate_xcode_attributes(ctx = ctx, srcs = srcs, argsfiles = argsfiles, product_name = ctx.attrs.name)+ data[XcodeDataInfoKeys.OUTPUT] = xctest_bundle++ # TODO: We should be able to extract this information in BXL. XcodeData is primarily necessary for derived data from the rules.+ if ctx.attrs.ui_test_target_app:+ data[XcodeDataInfoKeys.TEST_TYPE] = "ui-test"+ data[XcodeDataInfoKeys.TEST_TARGET] = ctx.attrs.ui_test_target_app.label.raw_target()+ else:+ data[XcodeDataInfoKeys.TEST_TYPE] = "unit-test"+ if test_host_app_binary:+ data[XcodeDataInfoKeys.TEST_HOST_APP_BINARY] = test_host_app_binary+ data[XcodeDataInfoKeys.TEST_HOST_APP_BUNDLE] = test_host_app_bundle+ data[XcodeDataInfoKeys.TEST_HOST_APP_TARGET] = ctx.attrs.test_host_app.label.raw_target()+ return data++def _get_test_framework_search_paths(ctx: AnalysisContext) -> (cmd_args, cmd_args):+ toolchain = ctx.attrs._apple_toolchain[AppleToolchainInfo]+ test_swiftmodule_search_path = cmd_args([toolchain.platform_path, "Developer/usr/lib"], delimiter = "/")+ test_framework_search_path = cmd_args([toolchain.platform_path, "Developer/Library/Frameworks"], delimiter = "/")+ return (test_swiftmodule_search_path, test_framework_search_path)++def _get_test_framework_search_paths_flags(ctx: AnalysisContext) -> list[[cmd_args, str]]:+ test_swiftmodule_search_path, test_framework_search_path = _get_test_framework_search_paths(ctx)+ return [+ "-I",+ test_swiftmodule_search_path,+ "-F",+ test_framework_search_path,+ ]++def get_test_framework_linker_flags(ctx: AnalysisContext) -> list[[cmd_args, str]]:+ test_swiftmodule_search_path, test_framework_search_path = _get_test_framework_search_paths(ctx)+ linker_flags = [+ "-L",+ test_swiftmodule_search_path,+ "-F",+ test_framework_search_path,+ ]+ if ctx.attrs.swift_testing:+ linker_flags += ["-lXCTestSwiftSupport"]+ return linker_flags
@@ -0,0 +1,46 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(":apple_sdk_metadata.bzl", "MacOSXSdkMetadata", "WatchSimulatorSdkMetadata")++apple_test_device_types = struct(+ DEFAULT = "default",+ CATALYST = "catalyst",+ IPAD = "ipad",+ IPHONE = "iphone",+ MAC = "mac",+ WATCH = "watch",+)++AppleTestDeviceType = enum(+ apple_test_device_types.DEFAULT,+ apple_test_device_types.CATALYST,+ apple_test_device_types.IPAD,+ apple_test_device_types.IPHONE,+ apple_test_device_types.MAC,+ apple_test_device_types.WATCH,+)++def get_default_test_device(sdk: str, platform: str) -> AppleTestDeviceType:+ if sdk == MacOSXSdkMetadata.name:+ return AppleTestDeviceType("mac")+ elif sdk == WatchSimulatorSdkMetadata.name:+ return AppleTestDeviceType("watch")+ elif "catalyst" in platform:+ return AppleTestDeviceType("catalyst")+ else:+ return AppleTestDeviceType("iphone")++def tpx_label_for_test_device_type(test_device_type: AppleTestDeviceType) -> str:+ if test_device_type in (AppleTestDeviceType("catalyst"), AppleTestDeviceType("mac")):+ return "tpx:apple_test:device_type:mac"+ elif test_device_type == AppleTestDeviceType("ipad"):+ return "tpx:apple_test:device_type:ipad"+ elif test_device_type == AppleTestDeviceType("watch"):+ return "tpx:apple_test:device_type:watch"+ return "tpx:apple_test:device_type:iphone"
@@ -0,0 +1,60 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load("@prelude//apple:apple_bundle_destination.bzl", "AppleBundleDestination")+load("@prelude//apple:apple_bundle_part.bzl", "AppleBundlePart")+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")++def get_test_frameworks_bundle_parts(ctx: AnalysisContext, swift_support_needed: bool) -> list[AppleBundlePart]:+ xcode_version = int(ctx.attrs._apple_toolchain[AppleToolchainInfo].xcode_version)+ paths = [+ _get_object_from_platform_path(ctx, "Developer/Library/Frameworks/XCTest.framework"),+ _get_object_from_platform_path(ctx, "Developer/Library/PrivateFrameworks/XCTAutomationSupport.framework"),+ _get_object_from_platform_path(ctx, "Developer/Library/PrivateFrameworks/XCTestCore.framework"),+ _get_object_from_platform_path(ctx, "Developer/Library/PrivateFrameworks/XCTestSupport.framework"),+ _get_object_from_platform_path(ctx, "Developer/Library/PrivateFrameworks/XCUnit.framework"),+ _get_object_from_platform_path(ctx, "Developer/usr/lib/libXCTestBundleInject.dylib"),+ ]++ # From Xcode 16.3 XCUIAutomation is in Frameworks, not PrivateFrameworks+ if xcode_version >= 1630:+ paths.append(_get_object_from_platform_path(ctx, "Developer/Library/Frameworks/XCUIAutomation.framework"))+ else:+ paths.append(_get_object_from_platform_path(ctx, "Developer/Library/PrivateFrameworks/XCUIAutomation.framework"))++ if swift_support_needed or ctx.attrs.swift_testing:+ paths.append(_get_object_from_platform_path(ctx, "Developer/usr/lib/libXCTestSwiftSupport.dylib"))++ # T201426509: Xcode 16 introduces the Swift Testing framework+ # that is a load dependency of libXCTestSwiftSupport.dylib+ if xcode_version >= 1600:+ paths.append(_get_object_from_platform_path(ctx, "Developer/Library/Frameworks/Testing.framework"))+ if xcode_version >= 2600:+ paths.append(_get_object_from_platform_path(ctx, "Developer/Library/Frameworks/_Testing_Foundation.framework"))++ # Xcode 26.4 makes Testing.framework load lib_TestingInterop.dylib at runtime.+ if xcode_version >= 2640:+ paths.append(_get_object_from_platform_path(ctx, "Developer/usr/lib/lib_TestingInterop.dylib"))++ return paths++def _get_object_from_platform_path(ctx: AnalysisContext, platform_relative_path: str) -> AppleBundlePart:+ toolchain = ctx.attrs._apple_toolchain[AppleToolchainInfo]+ copied_framework = ctx.actions.declare_output(paths.basename(platform_relative_path), has_content_based_path = False)++ # We have to copy because:+ # 1) Platform path might be a string (e.g. for Xcode toolchains)+ # 2) It's not possible to project artifact which is not produced by different target (and platform path is a separate target for distributed toolchains).+ ctx.actions.run(+ ["cp", "-PR", cmd_args(toolchain.platform_path, platform_relative_path, delimiter = "/"), copied_framework.as_output()],+ category = "extract_framework",+ identifier = platform_relative_path,+ )++ return AppleBundlePart(source = copied_framework, destination = AppleBundleDestination("frameworks"), codesign_on_copy = True)
@@ -0,0 +1,39 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++def _apple_test_host_app_transition_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> PlatformInfo:+ if not attrs.embed_xctest_frameworks_in_test_host_app:+ return platform++ updated_constraints = dict(platform.configuration.constraints)++ test_host_marker_setting_label = refs.embed_xctest_frameworks_constraint_setting[ConstraintSettingInfo].label+ if test_host_marker_setting_label in updated_constraints:+ return platform++ test_host_marker_value_info = refs.embed_xctest_frameworks_marker_constraint_value[ConstraintValueInfo]+ updated_constraints[test_host_marker_setting_label] = test_host_marker_value_info++ return PlatformInfo(+ label = platform.label + "-test-host-app",+ configuration = ConfigurationInfo(+ constraints = updated_constraints,+ values = platform.configuration.values,+ ),+ )++apple_test_host_app_transition = transition(+ impl = _apple_test_host_app_transition_impl,+ refs = {+ "embed_xctest_frameworks_constraint_setting": "config//marker/apple/constraints:embed_xctest_frameworks",+ "embed_xctest_frameworks_marker_constraint_value": "config//marker/apple/constraints:embed_xctest_frameworks[enabled]",+ },+ attrs = [+ "embed_xctest_frameworks_in_test_host_app",+ ],+)
@@ -0,0 +1,62 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftToolchainInfo")+load("@prelude//apple/validation:required_reasons_tools.bzl", "RequiredReasonsToolsInfo")+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxPlatformInfo", "CxxToolchainInfo")++def apple_toolchain_impl(ctx: AnalysisContext) -> list[Provider]:+ sdk_path = ctx.attrs._internal_sdk_path or ctx.attrs.sdk_path+ platform_path = ctx.attrs._internal_platform_path or ctx.attrs.platform_path+ dsymutil_cmd = cmd_args(ctx.attrs.dsymutil[RunInfo].args)+ dsymutil_cmd.add(ctx.attrs.dsymutil_flags)++ providers = [+ DefaultInfo(),+ AppleToolchainInfo(+ actool = ctx.attrs.actool[RunInfo],+ app_intents_metadata_processor = ctx.attrs.app_intents_metadata_processor[RunInfo] if ctx.attrs.app_intents_metadata_processor else None,+ app_intents_nl_training_processor = ctx.attrs.app_intents_nl_training_processor[RunInfo] if ctx.attrs.app_intents_nl_training_processor else None,+ architecture = ctx.attrs.architecture,+ codesign = ctx.attrs.codesign[RunInfo],+ codesign_allocate = ctx.attrs.codesign_allocate[RunInfo],+ codesign_identities_command = ctx.attrs.codesign_identities_command[RunInfo] if ctx.attrs.codesign_identities_command else None,+ compile_resources_locally = ctx.attrs.compile_resources_locally,+ copy_scene_kit_assets = ctx.attrs.copy_scene_kit_assets[RunInfo],+ cxx_platform_info = ctx.attrs.cxx_toolchain[CxxPlatformInfo],+ cxx_toolchain_info = ctx.attrs.cxx_toolchain[CxxToolchainInfo],+ dsymutil = RunInfo(args = dsymutil_cmd),+ dwarfdump = ctx.attrs.dwarfdump[RunInfo] if ctx.attrs.dwarfdump else None,+ extra_linker_outputs = ctx.attrs.extra_linker_outputs,+ ibtool = ctx.attrs.ibtool[RunInfo],+ installer = ctx.attrs.installer.label,+ installer_tool = ctx.attrs.installer[RunInfo],+ libtool = ctx.attrs.libtool[RunInfo],+ lipo = ctx.attrs.lipo[RunInfo],+ mapc = ctx.attrs.mapc[RunInfo] if ctx.attrs.mapc else None,+ merge_index_store = ctx.attrs.merge_index_store[RunInfo],+ metal = ctx.attrs.metal[RunInfo] if ctx.attrs.metal else None,+ metallib = ctx.attrs.metallib[RunInfo] if ctx.attrs.metallib else None,+ momc = ctx.attrs.momc[RunInfo],+ objdump = ctx.attrs.objdump[RunInfo] if ctx.attrs.objdump else None,+ platform_path = platform_path,+ required_reasons_tools = ctx.attrs.required_reasons_tools[RequiredReasonsToolsInfo],+ sdk_build_version = ctx.attrs.build_version,+ sdk_name = ctx.attrs.sdk_name,+ sdk_path = sdk_path,+ sdk_version = ctx.attrs.version,+ xcode_build_version = ctx.attrs.xcode_build_version,+ xcode_version = ctx.attrs.xcode_version,+ xctest = ctx.attrs.xctest[RunInfo],+ ),+ ]+ if ctx.attrs.swift_toolchain:+ providers.append(ctx.attrs.swift_toolchain[SwiftToolchainInfo])++ return providers
@@ -0,0 +1,79 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple/validation:required_reasons_tools.bzl", "RequiredReasonsToolsInfo")+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxPlatformInfo", "CxxToolchainInfo")++AppleToolchainInfo = provider(+ # @unsorted-dict-items+ fields = {+ "actool": provider_field(RunInfo),+ "app_intents_metadata_processor": provider_field(RunInfo | None, default = None),+ "app_intents_nl_training_processor": provider_field(RunInfo | None, default = None),+ "architecture": provider_field(str),+ "codesign_allocate": provider_field(RunInfo),+ "codesign_identities_command": provider_field(RunInfo | None, default = None),+ "codesign": provider_field(RunInfo),+ "compile_resources_locally": provider_field(bool),+ "copy_scene_kit_assets": provider_field(RunInfo),+ "cxx_platform_info": provider_field(CxxPlatformInfo),+ "cxx_toolchain_info": provider_field(CxxToolchainInfo),+ "dsymutil": provider_field(RunInfo),+ "dwarfdump": provider_field(RunInfo | None, default = None),+ "extra_linker_outputs": provider_field(list[str]),+ "ibtool": provider_field(RunInfo),+ "installer": provider_field(Label),+ "installer_tool": provider_field(RunInfo),+ "libtool": provider_field(RunInfo),+ "lipo": provider_field(RunInfo),+ "mapc": provider_field(RunInfo | None, default = None),+ "merge_index_store": provider_field(RunInfo),+ "metal": provider_field(RunInfo | None, default = None),+ "metallib": provider_field(RunInfo | None, default = None),+ "momc": provider_field(RunInfo),+ "objdump": provider_field(RunInfo | None, default = None),+ "platform_path": provider_field(str | Artifact),+ "required_reasons_tools": provider_field(RequiredReasonsToolsInfo),+ "sdk_build_version": provider_field(str | None, default = None),+ # SDK name to be passed to tools (e.g. actool), equivalent to ApplePlatform::getExternalName() in v1.+ "sdk_name": provider_field(str),+ "sdk_path": provider_field(str | Artifact),+ # TODO(T124581557) Make it non-optional once there is no "selected xcode" toolchain+ "sdk_version": provider_field(str | None, default = None),+ "xcode_build_version": provider_field(str | None, default = None),+ "xcode_version": provider_field(str),+ "xctest": provider_field(RunInfo),+ },+)++AppleToolsInfo = provider(+ # @unsorted-dict-items+ fields = {+ "assemble_bundle": provider_field(RunInfo),+ "provisioning_manifest": provider_field(RunInfo),+ "resolve_signing_context": provider_field(RunInfo),+ "signing_info": provider_field(RunInfo),+ "split_arch_combine_dsym_bundles_tool": provider_field(RunInfo),+ "dry_codesign_tool": provider_field(RunInfo),+ "adhoc_codesign_tool": provider_field(RunInfo),+ "codesign_manifest_tree_postprocessor": provider_field(RunInfo),+ "dedupe_swift_module_map": provider_field(RunInfo),+ "signing_context_tree_postprocessor": provider_field(RunInfo),+ "selective_debugging_scrubber": provider_field(RunInfo),+ "info_plist_processor": provider_field(RunInfo),+ "ipa_package_maker": provider_field(RunInfo),+ "make_modulemap": provider_field(RunInfo),+ "make_vfsoverlay": provider_field(RunInfo),+ "framework_sanitizer": provider_field(RunInfo),+ "xcframework_maker": provider_field(RunInfo),+ "static_archive_linker": provider_field(RunInfo),+ "spm_packager": provider_field(RunInfo),+ "bundle_telemetry_logger": provider_field(RunInfo | None, default = None),+ "swiftmodule_change_analysis": provider_field(RunInfo | None, default = None),+ },+)
@@ -0,0 +1,37 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")++def apple_tools_impl(ctx: AnalysisContext) -> list[Provider]:+ return [+ DefaultInfo(),+ AppleToolsInfo(+ assemble_bundle = ctx.attrs.assemble_bundle[RunInfo],+ provisioning_manifest = ctx.attrs.provisioning_manifest[RunInfo],+ resolve_signing_context = ctx.attrs.resolve_signing_context[RunInfo],+ signing_info = ctx.attrs.signing_info[RunInfo],+ split_arch_combine_dsym_bundles_tool = ctx.attrs.split_arch_combine_dsym_bundles_tool[RunInfo],+ dry_codesign_tool = ctx.attrs.dry_codesign_tool[RunInfo],+ adhoc_codesign_tool = ctx.attrs.adhoc_codesign_tool[RunInfo],+ codesign_manifest_tree_postprocessor = ctx.attrs.codesign_manifest_tree_postprocessor[RunInfo],+ dedupe_swift_module_map = ctx.attrs.dedupe_swift_module_map[RunInfo],+ signing_context_tree_postprocessor = ctx.attrs.signing_context_tree_postprocessor[RunInfo],+ info_plist_processor = ctx.attrs.info_plist_processor[RunInfo],+ ipa_package_maker = ctx.attrs.ipa_package_maker[RunInfo],+ make_modulemap = ctx.attrs.make_modulemap[RunInfo],+ make_vfsoverlay = ctx.attrs.make_vfsoverlay[RunInfo],+ selective_debugging_scrubber = ctx.attrs.selective_debugging_scrubber[RunInfo],+ xcframework_maker = ctx.attrs.xcframework_maker[RunInfo],+ framework_sanitizer = ctx.attrs.framework_sanitizer[RunInfo],+ static_archive_linker = ctx.attrs.static_archive_linker[RunInfo],+ spm_packager = ctx.attrs.spm_packager[RunInfo],+ bundle_telemetry_logger = ctx.attrs.bundle_telemetry_logger[RunInfo] if ctx.attrs.bundle_telemetry_logger else None,+ swiftmodule_change_analysis = ctx.attrs.swiftmodule_change_analysis[RunInfo] if ctx.attrs.swiftmodule_change_analysis else None,+ ),+ ]
@@ -0,0 +1,108 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:artifact_tset.bzl", "make_artifact_tset")+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")+load("@prelude//linking:link_info.bzl", "UnstrippedLinkOutputInfo")+load(":apple_bundle_types.bzl", "AppleBundleBinaryOutput")+load(":apple_toolchain_types.bzl", "AppleToolsInfo")+load(":debug.bzl", "AppleDebuggableInfo")++def get_universal_binary_name(ctx: AnalysisContext) -> str:+ if ctx.attrs.executable_name:+ return ctx.attrs.executable_name+ binary_deps = ctx.attrs.executable++ # Because `binary_deps` is a split transition of the same target,+ # the filenames would be identical, so we just pick the first one.+ first_binary_dep = binary_deps.values()[0]+ first_binary_artifact = first_binary_dep[DefaultInfo].default_outputs[0]++ # The universal executable should have the same name as the base/thin ones+ return first_binary_artifact.short_path++def lipo_binary_artifacts(ctx: AnalysisContext, binaries: list[Artifact], binary_name: [str, None], lipo: RunInfo, identifier: str) -> Artifact:+ binary_output = ctx.actions.declare_output("UniversalBinary" if binary_name == None else binary_name, dir = False, has_content_based_path = False)+ lipo_cmd = [lipo] + binaries++ lipo_cmd.extend(["-create", "-output", binary_output.as_output()])+ ctx.actions.run(cmd_args(lipo_cmd), category = "lipo", identifier = identifier)++ return binary_output++def lipo_binaries(ctx: AnalysisContext, binary_deps: dict[str, Dependency], binary_name: [str, None], lipo: RunInfo) -> Artifact:+ binaries = [binary[DefaultInfo].default_outputs[0] for binary in binary_deps.values()]+ return lipo_binary_artifacts(ctx, binaries, binary_name, lipo, "default")++def _get_unstripped_binaries(binary_deps: dict[str, Dependency]) -> list[Artifact]:+ unstripped_binaries = []+ for binary_dep in binary_deps.values():+ default_binary = binary_dep[DefaultInfo].default_outputs[0]+ unstripped_binary = binary_dep.get(UnstrippedLinkOutputInfo).artifact if binary_dep.get(UnstrippedLinkOutputInfo) != None else None+ if unstripped_binary != None and unstripped_binary != default_binary:+ unstripped_binaries.append(unstripped_binary)++ if len(unstripped_binaries) > 0 and len(unstripped_binaries) != len(binary_deps):+ fail("Inconsistent unstripped binaries, only certain archs provided unstripped binary versions")++ return unstripped_binaries++def create_universal_binary(+ ctx: AnalysisContext, binary_deps: dict[str, Dependency], binary_name: [str, None], dsym_bundle_name: [str, None], split_arch_dsym: bool+) -> AppleBundleBinaryOutput:+ binary_output = lipo_binaries(ctx, binary_deps, binary_name, ctx.attrs._apple_toolchain[AppleToolchainInfo].lipo)++ unstripped_binaries = _get_unstripped_binaries(binary_deps)+ unstripped_binary_output = None+ if unstripped_binaries:+ unstripped_binary_name = "unstripped/{}".format(binary_name) if binary_name else "UniversalBinary-Unstripped"+ unstripped_binary_output = lipo_binary_artifacts(+ ctx, unstripped_binaries, unstripped_binary_name, ctx.attrs._apple_toolchain[AppleToolchainInfo].lipo, "unstripped"+ )++ # Universal binaries can be created out of plain `cxx_binary()` / `cxx_library()`+ # which lack the `AppleDebuggableInfo` provider.+ # TODO(T174234334): Uniformly support debuggable info for apple_*/cxx_*+ contains_full_debuggable_info = _all_binaries_have_apple_debuggable_info(binary_deps)++ dsym_output = None+ if split_arch_dsym and contains_full_debuggable_info:+ dsym_output = ctx.actions.declare_output(+ "UniversalBinary.dSYM" if dsym_bundle_name == None else dsym_bundle_name, dir = True, has_content_based_path = False+ )+ dsym_combine_cmd = [ctx.attrs._apple_tools[AppleToolsInfo].split_arch_combine_dsym_bundles_tool]++ for arch, binary in binary_deps.items():+ dsym_combine_cmd.extend(["--dsym-bundle", cmd_args(binary.get(AppleDebuggableInfo).dsyms[0]), "--arch", arch])+ dsym_combine_cmd.extend(["--output", dsym_output.as_output()])+ ctx.actions.run(cmd_args(dsym_combine_cmd), category = "universal_binaries_dsym")++ all_debug_info_tsets = []+ if contains_full_debuggable_info:+ all_debug_info_tsets = [binary.get(AppleDebuggableInfo).debug_info_tset for binary in binary_deps.values()]++ return AppleBundleBinaryOutput(+ binary = binary_output,+ unstripped_binary = unstripped_binary_output,+ debuggable_info = AppleDebuggableInfo(+ dsyms = [dsym_output] if dsym_output != None else [],+ binaries = [unstripped_binary_output] if unstripped_binary_output else [binary_output],+ debug_info_tset = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ children = filter(None, all_debug_info_tsets),+ ),+ ),+ )++def _all_binaries_have_apple_debuggable_info(binary_deps: dict[str, Dependency]) -> bool:+ for binary in binary_deps.values():+ info = binary.get(AppleDebuggableInfo)+ if info == None:+ return False+ return True
@@ -0,0 +1,104 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "project_artifacts",+)+load(":apple_bundle_types.bzl", "AppleBundleLinkerMapInfo", "AppleMinDeploymentVersionInfo")+load(":apple_bundle_utility.bzl", "get_default_binary_dep", "get_flattened_binary_deps", "merge_bundle_linker_maps_info")+load(":apple_code_signing_types.bzl", "AppleEntitlementsInfo")+load(":apple_dsym.bzl", "DSYM_SUBTARGET", "get_apple_dsym_ext")+load(":apple_universal_binaries.bzl", "create_universal_binary", "get_universal_binary_name")+load(":debug.bzl", "AppleDebuggableInfo", "DEBUGINFO_SUBTARGET")+load(":resource_groups.bzl", "ResourceGraphInfo")++_FORWARDED_PROVIDER_TYPES = [+ AppleMinDeploymentVersionInfo,+ AppleEntitlementsInfo,+ ResourceGraphInfo,+]++_MERGED_PROVIDER_TYPES = [+ AppleDebuggableInfo,+ AppleBundleLinkerMapInfo,+]++def apple_universal_executable_impl(ctx: AnalysisContext) -> list[Provider]:+ dsym_name = ctx.attrs.name + ".dSYM"+ binary_outputs = create_universal_binary(+ ctx = ctx,+ binary_deps = ctx.attrs.executable,+ binary_name = get_universal_binary_name(ctx),+ dsym_bundle_name = dsym_name,+ split_arch_dsym = ctx.attrs.split_arch_dsym,+ )++ debug_info = project_artifacts(+ actions = ctx.actions,+ tsets = binary_outputs.debuggable_info.debug_info_tset,+ )++ sub_targets = {}+ if ctx.attrs.split_arch_dsym:+ dsyms = binary_outputs.debuggable_info.dsyms+ else:+ dsyms = [+ get_apple_dsym_ext(+ ctx = ctx,+ executable = binary_outputs.binary,+ debug_info = debug_info,+ action_identifier = ctx.attrs.name + "_dsym",+ output_path = dsym_name,+ )+ ]+ sub_targets[DSYM_SUBTARGET] = [DefaultInfo(default_outputs = dsyms)]++ debug_info_artifacts_manifest = ctx.actions.write(+ "debuginfo.artifacts",+ debug_info,+ with_inputs = True,+ has_content_based_path = False,+ )+ sub_targets[DEBUGINFO_SUBTARGET] = [DefaultInfo(default_output = debug_info_artifacts_manifest)]++ default_binary = get_default_binary_dep(ctx.attrs.executable)+ forwarded_providers = []+ for forward_provider_type in _FORWARDED_PROVIDER_TYPES:+ provider = default_binary.get(forward_provider_type)+ if provider != None:+ forwarded_providers += [provider]++ merged_providers = []+ all_binarys = get_flattened_binary_deps(ctx.attrs.executable)+ for merged_provider_type in _MERGED_PROVIDER_TYPES:+ if default_binary.get(merged_provider_type) == None:+ continue+ if merged_provider_type == AppleDebuggableInfo:+ merged_providers += [+ AppleDebuggableInfo(+ dsyms = dsyms,+ binaries = binary_outputs.debuggable_info.binaries,+ debug_info_tset = binary_outputs.debuggable_info.debug_info_tset,+ ),+ ]+ elif merged_provider_type == AppleBundleLinkerMapInfo:+ merged_providers += [+ merge_bundle_linker_maps_info([binary[AppleBundleLinkerMapInfo] for binary in all_binarys]),+ ]+ else:+ fail("Unhandled provider type: {}".format(merged_provider_type))++ return (+ [+ DefaultInfo(default_output = binary_outputs.binary, sub_targets = sub_targets),+ RunInfo(args = cmd_args(binary_outputs.binary)),+ ]+ + forwarded_providers+ + merged_providers+ )
@@ -0,0 +1,82 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftToolchainInfo")+load("@prelude//cxx:headers.bzl", "CHeader", "CxxHeadersLayout", "CxxHeadersNaming")+load("@prelude//utils:utils.bzl", "value_or")++def target_stats_header_name(header: CHeader) -> str:+ """The path a target refers to a header by.++ A header given as a dict is named by its key, which is the only thing+ separating two files that share a basename. A plain list keeps its+ package-relative path: Apple's naming would flatten it to the basename,+ which loses the sub-directory for no benefit here.+ """+ return header.name if header.named else header.artifact.short_path++def get_apple_cxx_headers_layout(ctx: AnalysisContext) -> CxxHeadersLayout:+ namespace = value_or(ctx.attrs.header_path_prefix, ctx.attrs.name)+ return CxxHeadersLayout(namespace = namespace, naming = CxxHeadersNaming("apple"))++def get_module_name(ctx: AnalysisContext) -> str:+ return ctx.attrs.module_name or ctx.attrs.header_path_prefix or ctx.attrs.name++def has_apple_toolchain(ctx: AnalysisContext) -> bool:+ return hasattr(ctx.attrs, "_apple_toolchain")++def get_apple_architecture(ctx: AnalysisContext) -> str:+ return ctx.attrs._apple_toolchain[AppleToolchainInfo].architecture++def get_apple_stripped_attr_value_with_default_fallback(ctx: AnalysisContext) -> bool:+ return ctx.attrs.strip_level != "unstripped"++def expand_relative_prefixed_sdk_path(swift_toolchain_info: SwiftToolchainInfo, path_to_expand: str) -> cmd_args:+ if not path_to_expand.startswith("$"):+ fail("Expanding path {} that does not start with a variable".format(path_to_expand))++ path_expansion_map = swift_toolchain_info.sdk_module_path_prefixes+ path_variable = path_to_expand[: path_to_expand.find("/")]+ if path_variable not in path_expansion_map:+ fail("Missing sdk_module_path_prefixes entry for {}".format(path_variable))++ path_val = path_expansion_map[path_variable]+ return cmd_args([path_val, path_to_expand[len(path_variable) :]], delimiter = "")++def get_disable_pch_validation_flags() -> list[str]:+ """+ We need to disable PCH validation for some actions like Swift compilation and Swift PCM generation.+ Currently, we don't have a mechanism to compile with enabled pch validation and Swift explicit modules,+ which we need to be able to do while we are waiting for Anonymous targets which will allow us to solve this problem properly.+ """+ return [+ "-Xcc",+ "-Xclang",+ "-Xcc",+ "-fno-validate-pch",+ ]++def get_base_swiftinterface_compilation_flags(module_name: str) -> cmd_args:+ cmd = cmd_args([+ "-frontend",+ "-compile-module-from-interface",+ "-disable-implicit-swift-modules",+ "-serialize-parseable-module-interface-dependency-hashes",+ "-disable-modules-validate-system-headers",+ "-suppress-warnings",+ "-module-name",+ module_name,+ "-Xcc",+ "-fno-implicit-modules",+ "-Xcc",+ "-fno-implicit-module-maps",+ ])+ cmd.add(get_disable_pch_validation_flags())++ return cmd
@@ -0,0 +1,104 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")+load(":apple_bundle_destination.bzl", "AppleBundleDestination")+load(":apple_bundle_part.bzl", "AppleBundlePart", "assemble_bundle")+load(":apple_bundle_types.bzl", "AppleBundleInfo", "AppleBundleType")+load(":apple_info_plist.bzl", "process_info_plist")+load(":apple_utility.bzl", "get_apple_architecture")++def apple_xcuitest_impl(ctx: AnalysisContext) -> [list[Provider], Promise]:+ # The XCUITest runner app bundle copies the application from the platform+ # directory, and includes the UI test bundle in the PlugIns folder.+ output_bundle = ctx.actions.declare_output(ctx.attrs.name + "." + ctx.attrs.extension, has_content_based_path = False)+ bundle_parts = [+ _get_xctrunner_binary(ctx),+ _get_uitest_bundle(ctx),+ ] + _get_xctrunner_frameworks(ctx)+ bundle_result = assemble_bundle(+ ctx = ctx,+ bundle = output_bundle,+ info_plist_part = process_info_plist(ctx, override_input = None),+ parts = bundle_parts,+ codesign_manifest_parts = [],+ signing_context_parts = [],+ swift_stdlib_args = None,+ )++ return [+ DefaultInfo(default_output = output_bundle),+ AppleBundleInfo(+ bundle = output_bundle,+ bundle_type = AppleBundleType("default"),+ binary_name = ctx.attrs.name,+ contains_watchapp = False,+ # The test runner binary does not contain Swift+ skip_copying_swift_stdlib = True,+ ),+ ] + bundle_result.providers++def _get_uitest_bundle(ctx: AnalysisContext) -> AppleBundlePart:+ return AppleBundlePart(+ source = ctx.attrs.test_bundle[DefaultInfo].default_outputs[0],+ destination = AppleBundleDestination("plugins"),+ )++def _get_xctrunner_binary(ctx: AnalysisContext) -> AppleBundlePart:+ arch = get_apple_architecture(ctx)+ lipo = ctx.attrs._apple_toolchain[AppleToolchainInfo].lipo+ platform_path = ctx.attrs._apple_toolchain[AppleToolchainInfo].platform_path+ thin_binary = ctx.actions.declare_output(ctx.attrs.name, has_content_based_path = False)+ xctrunner_path = cmd_args(platform_path, "Developer/Library/Xcode/Agents/XCTRunner.app/XCTRunner", delimiter = "/")+ ctx.actions.run(+ [+ lipo,+ xctrunner_path,+ "-extract",+ arch,+ "-output",+ thin_binary.as_output(),+ ],+ category = "copy_xctrunner",+ )++ return AppleBundlePart(+ source = thin_binary,+ destination = AppleBundleDestination("executables"),+ )++def _get_xctrunner_frameworks(ctx: AnalysisContext) -> list[AppleBundlePart]:+ # We need to copy the framework as AppleBundlePart requires an artifact.+ # It would be nicer to make this an arglike and avoid the copies.+ # It would also be nicer to exclude the headers.+ def copy_platform_framework(platform_relative_path: str) -> AppleBundlePart:+ copied_framework = ctx.actions.declare_output(paths.basename(platform_relative_path), has_content_based_path = False)+ path = cmd_args(ctx.attrs._apple_toolchain[AppleToolchainInfo].platform_path, platform_relative_path, delimiter = "/")+ ctx.actions.run(["cp", "-PR", path, copied_framework.as_output()], category = "copy_framework", identifier = platform_relative_path)+ return AppleBundlePart(+ source = copied_framework,+ destination = AppleBundleDestination("frameworks"),+ codesign_on_copy = True,+ )++ runner_frameworks = [+ "Developer/Library/Frameworks/XCTest.framework",+ "Developer/Library/PrivateFrameworks/XCTAutomationSupport.framework",+ "Developer/Library/PrivateFrameworks/XCTestCore.framework",+ "Developer/Library/PrivateFrameworks/XCTestSupport.framework",+ "Developer/Library/PrivateFrameworks/XCUnit.framework",+ ]++ # From Xcode 16.3 XCUIAutomation is in Frameworks, not PrivateFrameworks+ xcode_version = int(ctx.attrs._apple_toolchain[AppleToolchainInfo].xcode_version)+ if xcode_version >= 1630:+ runner_frameworks.append("Developer/Library/Frameworks/XCUIAutomation.framework")+ else:+ runner_frameworks.append("Developer/Library/PrivateFrameworks/XCUIAutomation.framework")+ return [copy_platform_framework(p) for p in runner_frameworks]
@@ -0,0 +1,16 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++_APPLE_ARCHES = [+ "arm64",+ "arm64e",+ "arm64_32",+ "x86_64",+]++AppleArch = enum(*_APPLE_ARCHES)
@@ -0,0 +1,32 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_universal_binaries.bzl", "get_universal_binary_name", "lipo_binaries")+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")++def cxx_universal_executable_impl(ctx: AnalysisContext) -> list[Provider]:+ lipo = ctx.attrs._cxx_toolchain[CxxToolchainInfo].lipo+ if not lipo:+ fail("`cxx_toolchain()` target does not have a valid `lipo` tool: {}".format(ctx.attrs._cxx_toolchain.label))++ universal_binary = lipo_binaries(+ ctx = ctx,+ binary_deps = ctx.attrs.executable,+ binary_name = get_universal_binary_name(ctx),+ lipo = lipo,+ )++ sub_targets = {arch: [DefaultInfo(default_output = binary[DefaultInfo].default_outputs[0])] for arch, binary in ctx.attrs.executable.items()}++ return [+ DefaultInfo(+ default_output = universal_binary,+ sub_targets = sub_targets,+ ),+ RunInfo(args = cmd_args(universal_binary)),+ ]
@@ -0,0 +1,113 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactTSet",+ "make_artifact_tset",+ "project_artifacts",+)++DEBUGINFO_SUBTARGET = "debuginfo"+DEBUGINFO_DB_SUBTARGET = "debuginfo-db"++AppleDebugInfo = TransitiveSetArgsProjection++AppleSelectiveDebuggableMetadata = record(+ # dSYM which the metadata applies for.+ dsym = field(Artifact),+ # JSON file containing metadata about the dSYM.+ #+ # This must be an artifact because there's no access to the focused targets+ # JSON file at analysis time.+ metadata = field(Artifact),+)++# Represents Apple debug info from both executables and bundles.+AppleDebuggableInfo = provider(+ fields = {+ "binaries": provider_field(list[Artifact], default = []),+ # Tset containing ArtifactInfos with either+ # a. the owning library target to artifacts, or+ # b. the owning bundle target to filtered artifacts+ "debug_info_tset": provider_field(ArtifactTSet),+ "dsyms": provider_field(list[Artifact]),+ # In the case of b above, contains the map of library target to artifacts, else None+ "filtered_map": provider_field([dict[Label, list[Artifact]], None], default = None),+ "selective_metadata": provider_field(list[AppleSelectiveDebuggableMetadata], default = []),+ },+)++_AppleDebugInfo = record(+ debug_info_tset = ArtifactTSet,+ filtered_map = field([dict[Label, list[Artifact]], None]),+)++AggregatedAppleDebugInfo = record(+ debug_info = field(_AppleDebugInfo),+ # debug_info_tset = field(ArtifactTSet),+ sub_targets = field(dict[str, list[DefaultInfo]]),+)++def get_aggregated_debug_info(ctx: AnalysisContext, debug_infos: list[AppleDebuggableInfo]) -> AggregatedAppleDebugInfo:+ all_debug_info_tsets = []+ full_debug_info_tsets = []+ debug_info_map = {}++ # If the AppleDebuggableInfo has a filtered map, the tset contains filtered info with a label equivalent to the bundle that propagated the+ # artifacts. Thus, we need to track whether any of the infos have a filtered map, and if so propagate the filtered map.+ any_info_has_filtered_map = False+ for info in debug_infos:+ all_debug_info_tsets.append(info.debug_info_tset)++ if info.filtered_map:+ debug_info_map.update(info.filtered_map)+ any_info_has_filtered_map = True+ else:+ full_debug_info_tsets.append(info.debug_info_tset)++ debug_info_tset = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ children = all_debug_info_tsets,+ )+ sub_targets = {}+ sub_targets[DEBUGINFO_SUBTARGET] = [+ DefaultInfo(+ default_output = ctx.actions.write(+ "debuginfo.artifacts",+ project_artifacts(+ actions = ctx.actions,+ tsets = debug_info_tset,+ ),+ with_inputs = True,+ has_content_based_path = False,+ )+ ),+ ]++ full_debug_info_tset = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ children = full_debug_info_tsets,+ )+ if full_debug_info_tset._tset:+ debug_info_map.update({info.label: info.artifacts for infos in full_debug_info_tset._tset.traverse() for info in infos})++ sub_targets[DEBUGINFO_DB_SUBTARGET] = [+ DefaultInfo(+ default_output = ctx.actions.write_json(DEBUGINFO_DB_SUBTARGET, debug_info_map, has_content_based_path = False),+ ),+ ]+ return AggregatedAppleDebugInfo(+ debug_info = _AppleDebugInfo(+ debug_info_tset = debug_info_tset,+ filtered_map = debug_info_map if any_info_has_filtered_map else None,+ ),+ sub_targets = sub_targets,+ )
@@ -0,0 +1,191 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_platforms.bzl", "APPLE_PLATFORMS_KEY")+load(+ ":mockingbird_types.bzl",+ "MockingbirdLibraryInfo",+ "MockingbirdLibraryRecord",+ "MockingbirdSourcesInfo",+ "MockingbirdToolchainInfo",+)++def mockingbird_mock_impl(ctx: AnalysisContext) -> list[Provider]:+ if not MockingbirdLibraryInfo in ctx.attrs.module:+ fail("This module does not contain any swift files. Mockingbird only creates generated mock files for swift code.")++ mockingbird_info = ctx.attrs.module[MockingbirdLibraryInfo]++ dep_names = [dep[MockingbirdLibraryInfo].name for dep in ctx.attrs.deps]+ included_srcs = [src.basename for src in ctx.attrs.srcs]+ excluded_srcs = [src.basename for src in ctx.attrs.excluded_srcs]++ for src_name in included_srcs:+ if not src_name.endswith(".swift"):+ fail("srcs should only specify Swift files. Other source files, such as {}, do not need to be included.".format(src_name))++ for src_name in excluded_srcs:+ if not src_name.endswith(".swift"):+ fail("excluded_srcs should only specify Swift files. Other source files, such as {}, do not need to be included.".format(src_name))++ (json_project_description, src_dirs) = _get_mockingbird_json_project_description(+ info = mockingbird_info, included_srcs = included_srcs, excluded_srcs = excluded_srcs, dep_names = dep_names+ )+ json_project_description_output = ctx.actions.declare_output("mockingbird_project.json", has_content_based_path = True)+ ctx.actions.write_json(json_project_description_output.as_output(), json_project_description)++ mockingbird_source = ctx.actions.declare_output(mockingbird_info.name + "Mocks.generated.swift", dir = False, has_content_based_path = True)+ cmd = cmd_args(+ hidden = src_dirs,+ )++ params = [+ ctx.attrs._mockingbird_toolchain[MockingbirdToolchainInfo].bin,+ "generate",+ "--target",+ mockingbird_info.name,+ "--project",+ json_project_description_output,+ "--output",+ mockingbird_source.as_output(),+ "--support",+ ctx.attrs._mockingbird_toolchain[MockingbirdToolchainInfo].support,+ "--verbose",+ "--disable-cache",+ ]++ if ctx.attrs.only_protocols:+ params.append("--only-protocols")++ cmd.add(params)++ ctx.actions.run(+ cmd,+ category = "mockingbird",+ local_only = True, # Mockingbird creates sockets for interprocess communication, which is deliberately blocked on RE.+ allow_cache_upload = True,+ )++ return [+ DefaultInfo(mockingbird_source),+ MockingbirdSourcesInfo(srcs = [mockingbird_source]),+ ]++def mockingbird_mock_attrs():+ attribs = {+ ## If the superclass for an object being mocked is in another module add it as a dep so mockingbird can find the implementation.+ "deps": attrs.list(attrs.dep(), default = []),+ ## The list of source files to exclude. Only the name of the file, excluding the path, should be set. If set, the srcs attribute will be ignored.+ "excluded_srcs": attrs.set(attrs.source(), sorted = True, default = []),+ ## The module to generate mocks for.+ "module": attrs.dep(),+ ## Whether to only generate mocks for Swift protocols.+ "only_protocols": attrs.bool(default = False),+ ## A list of source files to include. Only the name of the file, excluding the path, should be set. By default all source files are included and this doesn't need to be specified.+ "srcs": attrs.set(attrs.source(), sorted = True, default = []),+ "_mockingbird_toolchain": attrs.toolchain_dep(providers = [MockingbirdToolchainInfo], default = "toolchains//:mockingbird"),+ APPLE_PLATFORMS_KEY: attrs.dict(key = attrs.string(), value = attrs.dep(), sorted = False, default = {}),+ }+ return attribs++# Produce JSON project description for Mockingbird codegen+# https://mockingbirdswift.com/json-project-description+# {+# "targets": [+# {+# "name": "MyLibrary",+# "type": "library",+# "path": "/path/to/MyLibrary",+# "dependencies": [],+# "sources": [+# "SourceFileA.swift",+# "SourceFileB.swift"+# ]+# },+# {+# "name": "MyOtherLibrary",+# "type": "library",+# "path": "/path/to/MyOtherLibrary",+# "dependencies": [+# "MyLibrary"+# ],+# "sources": [+# "SourceFileA.swift",+# "SourceFileB.swift"+# ]+# },+# {+# "name": "MyLibraryTests",+# "type": "test",+# "path": "/path/to/MyLibraryTests",+# "dependencies": [+# "MyLibrary"+# ],+# "sources": [+# "SourceFileA.swift",+# "SourceFileB.swift"+# ]+# }+# ]+# }+def _get_mockingbird_json_project_description(+ info: MockingbirdLibraryInfo, included_srcs: list[str], excluded_srcs: list[str], dep_names: list[str]+) -> (dict, list):+ targets = []+ src_dirs = []+ for record in info.tset.traverse():+ if record.name == info.name:+ targets.append(+ _target_dict_for_mockingbird_record(record = record, included_srcs = included_srcs, excluded_srcs = excluded_srcs, include_non_exported_deps = True)+ )+ src_dirs.append(record.src_dir)+ elif record.name in dep_names:+ targets.append(_target_dict_for_mockingbird_record(record = record, included_srcs = [], excluded_srcs = [], include_non_exported_deps = False))+ src_dirs.append(record.src_dir)+ json = {+ "targets": targets,+ }++ return (json, src_dirs)++def _target_dict_for_mockingbird_record(+ record: MockingbirdLibraryRecord, included_srcs: list[str], excluded_srcs: list[str], include_non_exported_deps: bool+) -> dict:+ srcs = []+ if len(included_srcs) > 0 and len(excluded_srcs) > 0:+ fail("Included srcs and excluded srcs cannot both be set at the same time")++ record_src_names = [src.basename for src in record.srcs]++ for specified_src in included_srcs + excluded_srcs:+ if specified_src not in record_src_names:+ fail("The source file {} does not exist in target {}".format(specified_src, record.name))++ if len(included_srcs) > 0:+ for src_name in record_src_names:+ if src_name in included_srcs:+ srcs.append(src_name)+ elif len(excluded_srcs) > 0:+ for src_name in record_src_names:+ if src_name not in excluded_srcs:+ srcs.append(src_name)+ else:+ srcs = record_src_names++ deps = record.exported_dep_names++ if include_non_exported_deps:+ deps = deps + record.dep_names++ return {+ "dependencies": deps,+ "name": record.name,+ "path": record.src_dir,+ "sources": srcs,+ "type": record.type,+ }
@@ -0,0 +1,50 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++MockingbirdLibraryInfoTSet = transitive_set()++MockingbirdTargetType = enum("library", "test")++MockingbirdLibraryInfo = provider(+ fields = {+ # The Swift module name.+ "name": provider_field(str),+ # Contains a tset with this module's MockingbirdLibraryRecord as the value+ # and all of its dependencies' MockingbirdLibraryRecord in the children.+ "tset": provider_field(MockingbirdLibraryInfoTSet),+ },+)++MockingbirdLibraryRecord = record(+ # The Swift module names of this module's dependencies.+ dep_names = field(list[str]),+ # The Swift module names of this module's exported dependencies.+ exported_dep_names = field(list[str]),+ # The Swift module name.+ name = str,+ # Swift sources in this target.+ srcs = field(list[Artifact]),+ # Whether this is a library or a test.+ type = field(MockingbirdTargetType),+ # Symlinked directory containing the source files.+ src_dir = field(Artifact),+)++MockingbirdSourcesInfo = provider(+ fields = {+ # Source files containing the auto generated mocks produced by mockingbird-cli.+ "srcs": provider_field(list[Artifact]),+ },+)++MockingbirdToolchainInfo = provider(+ fields = {+ "bin": cmd_args,+ "support": Artifact,+ }+)
@@ -0,0 +1,55 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactTSet",+ "make_artifact_tset",+ "project_artifacts",+)++ModularizationDependencyGraphInfo = provider(+ fields = {+ "tset": provider_field(ArtifactTSet),+ },+)++def create_modularization_dep_graph_subtargets_and_provider(+ ctx: AnalysisContext,+ modularization_dependency_graph: Artifact | None,+ deps: list[Dependency],+) -> (dict[str, list[Provider]], ModularizationDependencyGraphInfo):+ children = [info.tset for info in filter(None, [dep.get(ModularizationDependencyGraphInfo) for dep in deps])]++ tset = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label if modularization_dependency_graph else None,+ artifacts = [modularization_dependency_graph] if modularization_dependency_graph else [],+ children = children,+ )++ all_graphs = project_artifacts(actions = ctx.actions, tsets = tset)++ sub_targets = {+ "all-modularization-dependency-graphs": [+ DefaultInfo(+ default_output = None,+ other_outputs = all_graphs,+ ),+ ],+ "modularization-dependency-graph": [+ DefaultInfo(+ default_output = modularization_dependency_graph,+ other_outputs = all_graphs,+ ),+ ],+ }++ info = ModularizationDependencyGraphInfo(tset = tset)++ return (sub_targets, info)
@@ -0,0 +1,111 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")+load(+ "@prelude//apple/swift:swift_incremental_support.bzl",+ "get_uses_content_based_paths",+)+load("@prelude//apple/swift:swift_toolchain.bzl", "supports_modulemaps_with_hmaps")+load(+ "@prelude//cxx:headers.bzl",+ "CHeader", # @unused Used as a type+)+load(+ "@prelude//cxx:preprocessor.bzl",+ "CPreprocessor",+)++def create_modulemap(+ ctx: AnalysisContext, name: str, module_name: str, headers: list[CHeader], swift_header: Artifact | None = None, is_framework: bool = False+) -> CPreprocessor:+ # We don't want to name this module.modulemap to avoid implicit importing+ if name == "module" and not is_framework:+ fail("Don't use the name `module` for modulemaps, this will allow for implicit importing.")++ uses_content_based_paths = get_uses_content_based_paths(ctx)+ use_relative_paths = supports_modulemaps_with_hmaps(ctx)++ # Create a map of header import path to artifact location+ header_map = {}+ for h in headers:+ if h.namespace:+ header_map["{}/{}".format(h.namespace, h.name)] = h.artifact+ else:+ header_map[h.name] = h.artifact++ swift_header_name = None+ if swift_header:+ # We need to include the Swift header in the symlink tree too+ swift_header_name = "{}/{}-Swift.h".format(module_name, module_name)+ header_map[swift_header_name] = swift_header++ if use_relative_paths:+ symlink_tree = None+ else:+ # Create a symlink dir for the headers to import+ symlink_tree_name = name.replace(".", "_") + "_symlink_tree"+ symlink_tree = ctx.actions.symlinked_dir(symlink_tree_name, header_map, has_content_based_path = uses_content_based_paths)++ output = ctx.actions.declare_output(name + ".modulemap", has_content_based_path = uses_content_based_paths)+ cmd = cmd_args(ctx.attrs._apple_tools[AppleToolsInfo].make_modulemap)+ cmd.add(+ "--output",+ output.as_output(),+ "--name",+ module_name,+ )++ if swift_header:+ cmd.add(+ "--swift-header",+ swift_header if use_relative_paths else cmd_args(symlink_tree, format = "{}/" + swift_header_name),+ )++ if getattr(ctx.attrs, "use_submodules", False):+ cmd.add("--use-submodules")++ if is_framework:+ cmd.add("--framework")++ for include_path in sorted(header_map.keys()):+ # Don't include the Swift header in the mappings, this is handled separately.+ if include_path == swift_header_name:+ continue++ if is_framework:+ # Framework headers are the same as their include paths, they are+ # compiled relative to the framework's Headers folder.+ cmd.add(include_path)+ cmd.add(include_path)+ elif use_relative_paths:+ # The path to the header artifact is relative to the containing+ # folder of the modulemap. We can't get the paths in the prelude,+ # the relativizing is done in the generation tool.+ cmd.add(include_path)+ cmd.add(header_map[include_path])+ else:+ # With symlink trees the include path should match the symlink name+ # nested in the symlink tree root.+ cmd.add(include_path)+ cmd.add(cmd_args(symlink_tree, format = "{}/" + include_path))++ ctx.actions.run(cmd, category = "modulemap", identifier = name)++ header_artifacts = header_map.values()+ modular_args = [cmd_args(output, format = "-fmodule-map-file={}", hidden = header_artifacts)]+ if not use_relative_paths and not is_framework:+ # When using relative paths we rely on the hmaps provided by regular+ # cxx preprocessor.+ modular_args.append(cmd_args(symlink_tree, format = "-I{}"))+ header_artifacts.append(symlink_tree)++ return CPreprocessor(+ modular_args = modular_args,+ modulemap_artifact = output.with_associated_artifacts(header_artifacts),+ )
@@ -0,0 +1,340 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactInfoTag",+ "ArtifactTSet",+ "make_artifact_tset",+)+load("@prelude//apple:apple_stripping.bzl", "apple_strip_args")+load("@prelude//apple:apple_utility.bzl", "get_base_swiftinterface_compilation_flags")+load("@prelude//apple/swift:apple_sdk_modules_utility.bzl", "is_sdk_modules_provided")+load(+ "@prelude//apple/swift:swift_compilation.bzl",+ "create_swift_dependency_info",+ "get_external_debug_info_tsets",+ "get_external_swift_ast_dump_tsets",+ "get_external_swiftmodule_change_analysis_tsets",+ "get_swift_anonymous_targets_for_prebuilt_framework",+)+load(+ "@prelude//apple/swift:swift_incremental_support.bzl",+ "get_uses_content_based_paths",+)+load("@prelude//apple/swift:swift_pcm_compilation.bzl", "compile_framework_pcm")+load(+ "@prelude//apple/swift:swift_pcm_compilation_types.bzl",+ "SwiftPCMUncompiledInfo",+)+load("@prelude//apple/swift:swift_swiftinterface_compilation.bzl", "compile_swiftinterface_common")+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftCompiledModuleTset", "SwiftToolchainInfo")+load("@prelude//apple/swift:swift_types.bzl", "FrameworkImplicitSearchPathInfo", "SwiftDependencyInfo", "get_implicit_framework_search_path_providers")+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")+load(+ "@prelude//cxx:cxx_library_utility.bzl",+ "cxx_attr_preferred_linkage",+ "cxx_platform_supported",+)+load(+ "@prelude//cxx:preprocessor.bzl",+ "CPreprocessor",+ "CPreprocessorArgs",+ "cxx_inherited_preprocessor_infos",+ "cxx_merge_cpreprocessors",+)+load("@prelude//cxx:target_sdk_version.bzl", "get_target_triple", "get_unversioned_target_triple")+load(+ "@prelude//linking:link_groups.bzl",+ "merge_link_group_lib_info",+)+load(+ "@prelude//linking:link_info.bzl",+ "Archive",+ "ArchiveLinkable",+ "LibOutputStyle",+ "LinkInfo",+ "LinkInfos",+ "SharedLibLinkable",+ "create_merged_link_info",+)+load(+ "@prelude//linking:linkable_graph.bzl",+ "create_linkable_graph",+ "create_linkable_graph_node",+ "create_linkable_node",+)+load(+ "@prelude//linking:shared_libraries.bzl",+ "SharedLibraryInfo",+ "merge_shared_libraries",+)+load("@prelude//linking:strip.bzl", "strip_object")+load("@prelude//linking:types.bzl", "Linkage")+load("@prelude//utils:utils.bzl", "filter_and_map_idx")+load(":apple_bundle_types.bzl", "AppleBundleInfo", "AppleBundleTypeDefault")+load(":apple_dsym.bzl", "DSYM_SUBTARGET")+load(":apple_frameworks.bzl", "to_framework_name")+load(":apple_toolchain_types.bzl", "AppleToolsInfo")+load(":apple_utility.bzl", "get_apple_stripped_attr_value_with_default_fallback")+load(":debug.bzl", "AppleDebuggableInfo")++def _get_compiled_swift_deps_tset(ctx: AnalysisContext, deps_providers: list) -> SwiftCompiledModuleTset:+ deps = [d[SwiftDependencyInfo].exported_swiftmodules for d in deps_providers if SwiftDependencyInfo in d]+ return ctx.actions.tset(SwiftCompiledModuleTset, children = deps)++def prebuilt_apple_framework_impl(ctx: AnalysisContext) -> [list[Provider], Promise]:+ def get_prebuilt_apple_framework_providers(deps_providers) -> list[Provider]:+ providers = []++ framework_directory_artifact = ctx.attrs.framework+ framework_name = to_framework_name(framework_directory_artifact.basename)+ framework_binary_name = ctx.attrs.binary if ctx.attrs.binary else framework_name+ framework_library_artifact = framework_directory_artifact.project(framework_binary_name)++ # Check this rule's `supported_platforms_regex` with the current platform.+ if cxx_platform_supported(ctx):+ uses_content_based_path = get_uses_content_based_paths(ctx)++ # Sandbox the framework, to avoid leaking other frameworks via search paths.+ framework_dir = ctx.actions.symlinked_dir(+ "Frameworks",+ {framework_name + ".framework": framework_directory_artifact},+ has_content_based_path = uses_content_based_path,+ )++ # Add framework & pp info from deps.+ inherited_pp_info = cxx_inherited_preprocessor_infos(ctx.attrs.deps)+ providers.append(+ cxx_merge_cpreprocessors(+ ctx.actions,+ [CPreprocessor(args = CPreprocessorArgs(args = ["-F", framework_dir]))],+ inherited_pp_info,+ )+ )++ if cxx_attr_preferred_linkage(ctx) == Linkage("static"):+ linkable = ArchiveLinkable(+ archive = Archive(artifact = framework_library_artifact),+ linker_type = get_cxx_toolchain_info(ctx).linker_info.type,+ )+ else:+ # If unspecified we default to "shared".+ linkable = SharedLibLinkable(+ lib = framework_library_artifact,+ )++ link = LinkInfo(+ name = framework_name,+ linkables = [linkable],+ pre_flags = [ctx.attrs.exported_linker_flags],+ )+ link_info = LinkInfos(default = link)++ providers.append(+ create_merged_link_info(+ ctx,+ get_cxx_toolchain_info(ctx).pic_behavior,+ {output_style: link_info for output_style in LibOutputStyle},+ )+ )++ # Create, augment and provide the linkable graph.+ linkable_graph = create_linkable_graph(+ ctx,+ node = create_linkable_graph_node(+ ctx,+ linkable_node = create_linkable_node(+ ctx,+ link_infos = {output_style: link_info for output_style in LibOutputStyle},+ # TODO(cjhopman): this should be set to non-None+ default_soname = None,+ ),+ excluded = {ctx.label: None},+ ),+ )+ providers.append(linkable_graph)++ providers.append(merge_link_group_lib_info(deps = ctx.attrs.deps))+ providers.append(merge_shared_libraries(ctx.actions, deps = filter_and_map_idx(SharedLibraryInfo, ctx.attrs.deps)))++ # The default output is the provided framework.+ sub_targets = {+ "distribution": _sanitize_framework_for_app_distribution(ctx, framework_directory_artifact) + providers,+ }++ if ctx.attrs.dsyms:+ sub_targets[DSYM_SUBTARGET] = [DefaultInfo(default_outputs = ctx.attrs.dsyms)]+ providers.append(AppleDebuggableInfo(dsyms = ctx.attrs.dsyms, debug_info_tset = ArtifactTSet()))++ providers.append(DefaultInfo(default_output = framework_directory_artifact, sub_targets = sub_targets))+ providers.append(+ AppleBundleInfo(+ bundle = framework_directory_artifact,+ bundle_type = AppleBundleTypeDefault,+ skip_copying_swift_stdlib = True,+ contains_watchapp = None,+ extra_codesign_paths = ctx.attrs.extra_codesign_paths,+ )+ )++ if ctx.attrs.modular:+ pcm_provider = _create_uncompiled_pcm_module_info(ctx, framework_directory_artifact, framework_name)+ providers.append(pcm_provider)++ # Since not all frameworks expose a swiftinterface, we use the `contains_swift` attribute to determine if one is available.+ if ctx.attrs.contains_swift:+ swift_dependency_info = _compile_swiftinterface(+ ctx,+ framework_name,+ pcm_provider,+ deps_providers,+ framework_directory_artifact,+ )+ providers.append(swift_dependency_info)++ implicit_search_path_tset = get_implicit_framework_search_path_providers(+ ctx,+ cmd_args("-F", cmd_args(framework_directory_artifact, parent = 1)),+ ctx.attrs.deps,+ )++ providers.append(+ FrameworkImplicitSearchPathInfo(tset = implicit_search_path_tset),+ )++ return providers++ # We cannot determine whether Swift Explicit modules are enabled at this point.+ # Therefore, we always return providers for both Implicit and Explicit modules, if SDK modules are available.+ # This approach is safe and won't trigger compilation of swiftinterfaces or pcm modules,+ # as no upper-level targets will depend on the artifacts from these compilations.+ swift_toolchain = ctx.attrs._apple_toolchain[SwiftToolchainInfo]+ if is_sdk_modules_provided(swift_toolchain):+ return get_swift_anonymous_targets_for_prebuilt_framework(ctx, get_prebuilt_apple_framework_providers)+ else:+ return get_prebuilt_apple_framework_providers([])++def _create_uncompiled_pcm_module_info(ctx: AnalysisContext, framework_directory_artifact: Artifact, framework_name: str) -> SwiftPCMUncompiledInfo:+ modulemap_artifact = framework_directory_artifact.project("Modules/module.modulemap").with_associated_artifacts([framework_directory_artifact])+ clang_importer_args = cmd_args(framework_directory_artifact, parent = 1, format = "-F{}")+ return SwiftPCMUncompiledInfo(+ clang_importer_args = cmd_args(),+ exported_clang_importer_args = clang_importer_args,+ exported_deps = ctx.attrs.deps,+ is_transient = False,+ modulemap_artifact = modulemap_artifact,+ name = framework_name,+ uncompiled_sdk_modules = ctx.attrs.sdk_modules,+ )++def _compile_swiftinterface(+ ctx: AnalysisContext, framework_name: str, pcm_provider: SwiftPCMUncompiledInfo, deps_providers, framework_directory_artifact: Artifact+) -> SwiftDependencyInfo:+ # To compile the framework's swiftinterface, the PCM module must be precompiled first.+ compiled_underlying_pcm = compile_framework_pcm(+ ctx,+ framework_name,+ pcm_provider,+ deps_providers,+ ["-target", get_target_triple(ctx)],+ )++ partial_cmd = get_base_swiftinterface_compilation_flags(framework_name)++ swiftinterface_path = cmd_args(+ framework_directory_artifact,+ "/Modules/",+ framework_name,+ ".swiftmodule/" + get_unversioned_target_triple(ctx) + ".swiftinterface",+ delimiter = "",+ )++ swift_third_party_deps = _get_compiled_swift_deps_tset(ctx, ctx.attrs.deps)++ swift_compiled_module, _ = compile_swiftinterface_common(+ ctx,+ ctx.attrs.deps,+ True, # is_framework+ framework_name,+ partial_cmd,+ deps_providers,+ swiftinterface_path,+ "prebuilt_framework_swiftinterface_compilation",+ compiled_underlying_pcm,+ additional_compiled_swiftmodules = swift_third_party_deps,+ )++ debug_info_tset = make_artifact_tset(+ actions = ctx.actions,+ artifacts = [swift_compiled_module.output_artifact, compiled_underlying_pcm.output_artifact],+ children = get_external_debug_info_tsets(False, ctx.attrs.deps),+ label = ctx.label,+ tags = [ArtifactInfoTag("swift_debug_info")],+ )++ swiftmodule_change_analysis_tset = make_artifact_tset(+ actions = ctx.actions,+ # Just the swiftmodule, not the underlying PCM (unlike debug_info_tset+ # above): PCM-only changes aren't swiftmodule changes, and including it+ # would re-run this analysis action whenever the PCM changes for no+ # reason.+ artifacts = [swift_compiled_module.output_artifact],+ children = get_external_swiftmodule_change_analysis_tsets(False, ctx.attrs.deps),+ label = ctx.label,+ )++ swift_ast_dump_tset = make_artifact_tset(+ actions = ctx.actions,+ children = get_external_swift_ast_dump_tsets(False, ctx.attrs.deps),+ label = ctx.label,+ )++ swift_dependency_info = create_swift_dependency_info(+ ctx,+ ctx.attrs.deps,+ deps_providers,+ swift_compiled_module,+ debug_info_tset,+ swiftmodule_change_analysis_tset,+ swift_ast_dump_tset,+ False,+ )++ return swift_dependency_info++def _sanitize_framework_for_app_distribution(ctx: AnalysisContext, framework_directory_artifact: Artifact) -> list[Provider]:+ framework_name = to_framework_name(framework_directory_artifact.basename)+ bundle_for_app_distribution = ctx.actions.declare_output(framework_name + ".framework", dir = True, has_content_based_path = False)++ apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]+ framework_sanitize_command = cmd_args([+ apple_tools.framework_sanitizer,+ "--input",+ framework_directory_artifact,+ "--output",+ bundle_for_app_distribution.as_output(),+ ])++ if get_apple_stripped_attr_value_with_default_fallback(ctx):+ strip_args = apple_strip_args(ctx)+ stripped = strip_object(ctx, get_cxx_toolchain_info(ctx), framework_directory_artifact.project(framework_name), strip_args, "framework_distribution")+ framework_sanitize_command.add("--replacement-binary", stripped)++ ctx.actions.run(framework_sanitize_command, category = "sanitize_prebuilt_apple_framework")+ providers = [DefaultInfo(default_output = bundle_for_app_distribution)]+ providers.append(+ AppleBundleInfo(+ bundle = bundle_for_app_distribution,+ bundle_type = AppleBundleTypeDefault,+ skip_copying_swift_stdlib = True,+ contains_watchapp = None,+ extra_codesign_paths = ctx.attrs.extra_codesign_paths,+ )+ )+ return providers
@@ -0,0 +1,276 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:arch.bzl", "AppleArch")+load("@prelude//utils:glob_defs.bzl", "subdir_glob")+load("@prelude//utils:selects.bzl", "selects")++def _generate_framework_and_dsym_select_maps(prebuilt_xcframework_args, platform_filter, default_arch, default_target_platform, genrule):+ """+ Generate genrules for frameworks and dsyms, and return select maps for the attributes.+ Returns a tuple of (framework_select_map, dsym_select_map) where each maps config conditions to targets/artifacts.+ """+ name = prebuilt_xcframework_args.name+ platforms = prebuilt_xcframework_args.platforms+ xcframework = prebuilt_xcframework_args.xcframework+ framework_name = prebuilt_xcframework_args.framework_name+ framework_platforms_to_dsym_filenames = prebuilt_xcframework_args.framework_platforms_to_dsym_filenames++ framework_select_map = {}+ dsym_select_map = {}++ for platform in platforms:+ if platform_filter(platform):+ bash_cmd = "mkdir $OUT && cp -R $(location {})/{}/{}.framework/* $OUT/".format(xcframework, platform["folder"], framework_name)+ assemble_name = "{}-{}-assemble".format(name, platform["folder"])+ genrule(+ name = assemble_name,+ bash = bash_cmd,+ out = framework_name + ".framework",+ default_target_platform = default_target_platform,+ has_content_based_path = True,+ )++ dsym_artifacts = selects.apply(+ framework_platforms_to_dsym_filenames,+ partial(_generate_dsym_artifacts, name, platform["folder"], xcframework, default_target_platform, genrule),+ )++ for arch in platform["archs"]:+ if arch not in ["arm64", "arm64e", "x86_64"]:+ fail("Unsupported " + platform["platform"] + " arch: " + arch)++ config_key = "ovr_config//cpu:" + arch+ framework_select_map[config_key] = ":" + assemble_name+ dsym_select_map[config_key] = dsym_artifacts++ # We want to set DEFAULT if+ # - We have specified a default_arch and it matches+ # - We haven't specified a default_arch in which case+ # we take the first match+ if (default_arch != None and AppleArch(arch) == default_arch) or framework_select_map.get("DEFAULT") == None:+ framework_select_map["DEFAULT"] = ":" + assemble_name+ dsym_select_map["DEFAULT"] = dsym_artifacts++ return (framework_select_map, dsym_select_map)++def _generate_dsym_artifacts(name, platform_folder, xcframework, default_target_platform, genrule, framework_platforms_to_dsym_filenames):+ return [+ _generate_dsym_artifact(name, platform_folder, xcframework, default_target_platform, dsym_filename, genrule)+ for dsym_filename in framework_platforms_to_dsym_filenames.get(platform_folder, [])+ ]++def _generate_dsym_artifact(name, platform_folder, xcframework, default_target_platform, dsym_filename, genrule):+ bash_cmd_dsyms = "mkdir $OUT && cp -R $(location {})/{}/dSYMs/{}/* $OUT/".format(xcframework, platform_folder, dsym_filename)+ dsym_name = "{}-{}-dsym".format(name, platform_folder)+ genrule(+ name = dsym_name,+ bash = bash_cmd_dsyms,+ out = dsym_filename,+ default_target_platform = default_target_platform,+ has_content_based_path = True,+ )+ return ":" + dsym_name++def _generate_iphonesimulator_select_maps(prebuilt_xcframework_args, **kwargs):+ return _generate_framework_and_dsym_select_maps(+ prebuilt_xcframework_args = prebuilt_xcframework_args,+ platform_filter = lambda platform: platform["platform"] == "ios" and platform["isSimulator"] and not platform["isCatalyst"],+ default_arch = AppleArch("arm64"),+ default_target_platform = "ovr_config//platform/iphoneos:iphonesimulator-arm64",+ **kwargs,+ )++def _generate_iphone_select_maps(prebuilt_xcframework_args, **kwargs):+ return _generate_framework_and_dsym_select_maps(+ prebuilt_xcframework_args = prebuilt_xcframework_args,+ platform_filter = lambda platform: platform["platform"] == "ios" and not platform["isSimulator"] and not platform["isCatalyst"],+ default_arch = None,+ default_target_platform = "ovr_config//platform/iphoneos:iphoneos-arm64",+ **kwargs,+ )++def _generate_mac_select_maps(prebuilt_xcframework_args, **kwargs):+ return _generate_framework_and_dsym_select_maps(+ prebuilt_xcframework_args = prebuilt_xcframework_args,+ platform_filter = lambda platform: platform["platform"] == "macos",+ default_arch = None,+ default_target_platform = "ovr_config//platform/macos:arm64-fbsource",+ **kwargs,+ )++def _generate_maccatalyst_select_maps(prebuilt_xcframework_args, **kwargs):+ return _generate_framework_and_dsym_select_maps(+ prebuilt_xcframework_args = prebuilt_xcframework_args,+ platform_filter = lambda platform: platform["platform"] == "ios" and not platform["isSimulator"] and platform["isCatalyst"],+ default_arch = None,+ default_target_platform = "ovr_config//platform/macos:arm64-catalyst",+ **kwargs,+ )++def prebuilt_apple_xcframework_macro_impl(+ prebuilt_apple_framework_rule,+ filegroup_rule,+ name,+ xcframework,+ framework_name,+ framework_platforms,+ framework_platforms_to_dsym_filenames = {},+ default_target_platform = None,+ **kwargs,+):+ compatible_with = kwargs.pop("compatible_with", None)++ parsed_platforms = [_parse_platform(platform) for platform in framework_platforms]++ # The xcframework is not required to be on disk, so we must make the folder path compatible with getting it from another target+ if ":" in xcframework:+ xcframework_target = xcframework+ else:+ xcframework_target = ":" + xcframework+ filegroup_rule(+ name = xcframework,+ srcs = subdir_glob(+ [+ (xcframework, "**/*"),+ ],+ ),+ )++ prebuilt_xcframework_args = struct(+ name = name,+ platforms = parsed_platforms,+ xcframework = xcframework_target,+ framework_name = framework_name,+ framework_platforms_to_dsym_filenames = framework_platforms_to_dsym_filenames,+ )++ genrule = kwargs.pop("genrule", None)+ if genrule == None:+ fail("genrule must be provided")++ # Generate framework/dsym genrules and get select maps for each platform+ iphonesimulator_framework_map, iphonesimulator_dsym_map = _generate_iphonesimulator_select_maps(prebuilt_xcframework_args, genrule = genrule)+ iphone_framework_map, iphone_dsym_map = _generate_iphone_select_maps(prebuilt_xcframework_args, genrule = genrule)+ mac_framework_map, mac_dsym_map = _generate_mac_select_maps(prebuilt_xcframework_args, genrule = genrule)+ maccatalyst_framework_map, maccatalyst_dsym_map = _generate_maccatalyst_select_maps(prebuilt_xcframework_args, genrule = genrule)++ # Determine default platform's maps (priority: iphonesimulator > iphone > mac > maccatalyst)+ default_framework_map = None+ default_dsym_map = None++ if len(iphonesimulator_framework_map) > 0:+ default_framework_map = iphonesimulator_framework_map+ default_dsym_map = iphonesimulator_dsym_map+ elif len(iphone_framework_map) > 0:+ default_framework_map = iphone_framework_map+ default_dsym_map = iphone_dsym_map+ elif len(mac_framework_map) > 0:+ default_framework_map = mac_framework_map+ default_dsym_map = mac_dsym_map+ elif len(maccatalyst_framework_map) > 0:+ default_framework_map = maccatalyst_framework_map+ default_dsym_map = maccatalyst_dsym_map++ if default_framework_map == None:+ fail("No valid platforms found in xcframework")++ # Build combined maps for iphonesimulator+maccatalyst (used for ovr_config//os:iphoneos and iphonesimulator SDK)+ iphonesimulator_and_maccatalyst_framework_map = iphonesimulator_framework_map+ iphonesimulator_and_maccatalyst_dsym_map = iphonesimulator_dsym_map+ if len(maccatalyst_framework_map) > 0:+ if len(iphonesimulator_framework_map) > 0:+ iphonesimulator_and_maccatalyst_framework_map = {+ "DEFAULT": select(iphonesimulator_framework_map),+ "ovr_config//runtime/constraints:maccatalyst": select(maccatalyst_framework_map),+ }+ iphonesimulator_and_maccatalyst_dsym_map = {+ "DEFAULT": select(iphonesimulator_dsym_map),+ "ovr_config//runtime/constraints:maccatalyst": select(maccatalyst_dsym_map),+ }+ else:+ iphonesimulator_and_maccatalyst_framework_map = maccatalyst_framework_map+ iphonesimulator_and_maccatalyst_dsym_map = maccatalyst_dsym_map++ # Build combined maps for iphone+maccatalyst (used for iphoneos SDK)+ iphone_and_maccatalyst_framework_map = iphone_framework_map+ iphone_and_maccatalyst_dsym_map = iphone_dsym_map+ if len(maccatalyst_framework_map) > 0:+ if len(iphone_framework_map) > 0:+ iphone_and_maccatalyst_framework_map = {+ "DEFAULT": select(iphone_framework_map),+ "ovr_config//runtime/constraints:maccatalyst": select(maccatalyst_framework_map),+ }+ iphone_and_maccatalyst_dsym_map = {+ "DEFAULT": select(iphone_dsym_map),+ "ovr_config//runtime/constraints:maccatalyst": select(maccatalyst_dsym_map),+ }+ else:+ iphone_and_maccatalyst_framework_map = maccatalyst_framework_map+ iphone_and_maccatalyst_dsym_map = maccatalyst_dsym_map++ # Build the nested select for framework attribute+ framework_select_map = {"DEFAULT": select(default_framework_map)}+ dsym_select_map = {"DEFAULT": select(default_dsym_map)}++ if len(iphonesimulator_and_maccatalyst_framework_map) > 0:+ framework_select_map["ovr_config//os:iphoneos"] = select(iphonesimulator_and_maccatalyst_framework_map)+ framework_select_map["ovr_config//os/sdk/apple:iphonesimulator"] = select(iphonesimulator_and_maccatalyst_framework_map)+ dsym_select_map["ovr_config//os:iphoneos"] = select(iphonesimulator_and_maccatalyst_dsym_map)+ dsym_select_map["ovr_config//os/sdk/apple:iphonesimulator"] = select(iphonesimulator_and_maccatalyst_dsym_map)++ if len(iphone_and_maccatalyst_framework_map) > 0:+ framework_select_map["ovr_config//os/sdk/apple:iphoneos"] = select(iphone_and_maccatalyst_framework_map)+ dsym_select_map["ovr_config//os/sdk/apple:iphoneos"] = select(iphone_and_maccatalyst_dsym_map)++ if len(mac_framework_map) > 0:+ framework_select_map["ovr_config//os:macos"] = select(mac_framework_map)+ dsym_select_map["ovr_config//os:macos"] = select(mac_dsym_map)++ # Create a single prebuilt_apple_framework with select() for framework and dsyms+ prebuilt_apple_framework_rule(+ name = name,+ framework = select(framework_select_map),+ dsyms = select(dsym_select_map),+ default_target_platform = default_target_platform,+ compatible_with = compatible_with,+ **kwargs,+ )++def _parse_platform(name):+ # parse metadata from conventional xcframework folders+ # produced by xcodebuild -create-xcframework+ #+ # examples:+ #+ # ios-arm64+ # ios-arm64_x86_64-simulator+ # ios-arm64_x86_64-maccatalyst+ # macos-arm64_x86_64+ substrings = name.split("-")+ isCatalyst = False+ isSimulator = False+ if len(substrings) > 2:+ isSimulator = substrings[2] == "simulator"+ isCatalyst = substrings[2] == "maccatalyst"+ archs = []+ remaining = substrings[1]+ for arch in ["arm64e", "arm64_32", "arm64", "x86_64"]:+ if arch in remaining:+ archs.append(arch)+ remaining = remaining.replace(arch, "")+ if not archs:+ fail("Failed to parse architectures for xcframework platform " + name)++ return {+ "archs": archs,+ "folder": name,+ "isCatalyst": isCatalyst,+ "isSimulator": isSimulator,+ "platform": substrings[0],+ }
@@ -0,0 +1,226 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//cxx:groups_types.bzl", "Group", "MATCH_ALL_LABEL")+load(+ "@prelude//utils:graph_utils.bzl",+ "depth_first_traversal_by",+)+load(":apple_asset_catalog_types.bzl", "AppleAssetCatalogSpec")+load(":apple_core_data_types.bzl", "AppleCoreDataSpec")+load(":apple_resource_types.bzl", "AppleResourceSelectionOutput", "AppleResourceSpec", "CxxResourceSpec", "SelectedAppleAssetCatalogSpec")+load(":scene_kit_assets_types.bzl", "SceneKitAssetsSpec")+load(":xcassets_asset_symbols.bzl", "MetaXcassetsAssetSymbolSpec")++ResourceGroupInfo = provider(+ # @unsorted-dict-items+ fields = {+ "groups": provider_field(list[Group]),+ "groups_hash": provider_field(int),+ "mappings": provider_field(dict[Label, str]),+ # Additional deps needed to cover labels referenced by the groups above.+ # This is useful in cases where the consumer of this provider won't already+ # have deps covering these.+ # NOTE(agallagher): We do this to maintain existing behavior w/ the+ # standalone `resource_group_map()` rule, but it's not clear if it's+ # actually desirable behavior.+ "resource_group_to_implicit_deps_mapping": provider_field(dict[str, list[Dependency]]),+ },+)++RESOURCE_GROUP_MAP_ATTR = attrs.option(attrs.dep(providers = [ResourceGroupInfo]), default = None)++ResourceGraphNode = record(+ label = field(Label),+ # Attribute labels on the target.+ labels = field(list[str], []),+ # Deps of this target which might have resources transitively.+ deps = field(list[Label], []),+ # Exported deps of this target which might have resources transitively.+ exported_deps = field(list[Label], []),+ # Actual resource data, present when node corresponds to `apple_resource` target.+ resource_spec = field([AppleResourceSpec, None], None),+ # Actual asset catalog data, present when node corresponds to `apple_asset_catalog` target.+ asset_catalog_spec = field([AppleAssetCatalogSpec, None], None),+ # Actual core data, present when node corresponds to `core_data_model` target+ core_data_spec = field([AppleCoreDataSpec, None], None),+ # Actual scene kit assets, present when node corresponds to `scene_kit_assets` target+ scene_kit_assets_spec = field([SceneKitAssetsSpec, None], None),+ # Actual resource data, present when node corresponds to `cxx_library` target containing resources.+ cxx_resource_spec = field([CxxResourceSpec, None], None),+ # Asset symbol metadata from an asset catalog opted into trimming. Carries the+ # producer and catalog identity through bundle-level resource selection.+ xcassets_symbol_spec = field([MetaXcassetsAssetSymbolSpec, None], None),+)++ResourceGraphTSet = transitive_set()++ResourceGraphInfo = provider(+ fields = {+ "label": provider_field(Label),+ "nodes": provider_field(ResourceGraphTSet),+ "should_propagate": provider_field(bool),+ }+)++def create_resource_graph(+ ctx: AnalysisContext,+ labels: list[str],+ deps: list[Dependency],+ exported_deps: list[Dependency],+ bundle_binary: [Dependency, None] = None,+ resource_spec: [AppleResourceSpec, None] = None,+ asset_catalog_spec: [AppleAssetCatalogSpec, None] = None,+ core_data_spec: [AppleCoreDataSpec, None] = None,+ scene_kit_assets_spec: [SceneKitAssetsSpec, None] = None,+ cxx_resource_spec: [CxxResourceSpec, None] = None,+ xcassets_symbol_spec: [MetaXcassetsAssetSymbolSpec, None] = None,+ should_propagate: bool = True,+) -> ResourceGraphInfo:+ # Collect deps and exported_deps with resources that should propagate.+ dep_labels, dep_graphs = _filtered_labels_and_graphs(deps)+ exported_dep_labels, exported_dep_graphs = _filtered_labels_and_graphs(exported_deps)++ # Bundle binary targets always propagate resources to their bundle.+ # The bundle target will not pass up a ResourceGraphInfo provider itself+ # so the resources do not propagate outside the bundle folder.+ if bundle_binary and ResourceGraphInfo in bundle_binary:+ dep_graphs.append(bundle_binary[ResourceGraphInfo])++ # We use ResourceGraphInfo.label here to ensure the graph lookup works+ # when we have binary targets specified with the [shared] subtarget.+ dep_labels.append(bundle_binary[ResourceGraphInfo].label)++ node = ResourceGraphNode(+ label = ctx.label,+ labels = labels,+ deps = dep_labels,+ exported_deps = exported_dep_labels,+ resource_spec = resource_spec,+ asset_catalog_spec = asset_catalog_spec,+ core_data_spec = core_data_spec,+ scene_kit_assets_spec = scene_kit_assets_spec,+ cxx_resource_spec = cxx_resource_spec,+ xcassets_symbol_spec = xcassets_symbol_spec,+ )+ children = [child_node.nodes for child_node in dep_graphs + exported_dep_graphs]+ return ResourceGraphInfo(+ label = ctx.label,+ nodes = ctx.actions.tset(ResourceGraphTSet, value = node, children = children),+ should_propagate = should_propagate,+ )++def get_resource_graph_node_map_func(graph: ResourceGraphInfo):+ def get_resource_graph_node_map() -> dict[Label, ResourceGraphNode]:+ nodes = graph.nodes.traverse()+ return {node.label: node for node in filter(None, nodes)}++ return get_resource_graph_node_map++def _filtered_labels_and_graphs(deps: list[Dependency]) -> (list[Label], list[ResourceGraphInfo]):+ """+ Filters dependencies and returns only those which are relevant+ to working with resources i.e. those which contains resource graph provider+ and that should propagate.+ """+ resource_labels = []+ resource_deps = []+ for d in deps:+ graph = d.get(ResourceGraphInfo)+ if graph and graph.should_propagate:+ resource_deps.append(graph)+ resource_labels.append(graph.label)++ return resource_labels, resource_deps++def get_resource_group_info(ctx: AnalysisContext) -> [ResourceGroupInfo, None]:+ """+ Parses the currently analyzed context for any resource group definitions+ and returns a list of all resource groups with their mappings.+ """+ resource_group_map = ctx.attrs.resource_group_map++ if not resource_group_map:+ return None++ if isinstance(resource_group_map, Dependency):+ return resource_group_map[ResourceGroupInfo]++ fail("Resource group maps must be provided as a resource_group_map rule dependency.")++def get_filtered_resources(+ root: Label, resource_graph_node_map_func, resource_group: [str, None], resource_group_mappings: [dict[Label, str], None]+) -> AppleResourceSelectionOutput:+ """+ Walks the provided DAG and collects resources matching resource groups definition.+ """++ resource_graph_node_map = resource_graph_node_map_func()++ def get_traversed_deps(target: Label) -> list[Label]:+ node = resource_graph_node_map[target] # buildifier: disable=uninitialized+ return node.exported_deps + node.deps++ targets = depth_first_traversal_by(+ resource_graph_node_map,+ get_traversed_deps(root),+ get_traversed_deps,+ )++ resource_specs = []+ asset_catalog_specs = []+ selected_asset_catalog_specs = []+ core_data_specs = []+ scene_kit_assets_specs = []+ cxx_resource_specs = []++ for target in targets:+ target_resource_group = resource_group_mappings.get(target)++ # Ungrouped targets belong to the unlabeled bundle+ if (+ (not target_resource_group and not resource_group)+ or+ # Does it match special "MATCH_ALL" mapping?+ target_resource_group == MATCH_ALL_LABEL+ or+ # Does it match currently evaluated group?+ target_resource_group == resource_group+ ):+ node = resource_graph_node_map[target]+ resource_spec = node.resource_spec+ if resource_spec:+ resource_specs.append(resource_spec)+ asset_catalog_spec = node.asset_catalog_spec+ if asset_catalog_spec:+ asset_catalog_specs.append(asset_catalog_spec)+ selected_asset_catalog_specs.append(+ SelectedAppleAssetCatalogSpec(+ asset_catalog_spec = asset_catalog_spec,+ xcassets_symbol_spec = node.xcassets_symbol_spec,+ target = target,+ ),+ )+ core_data_spec = node.core_data_spec+ if core_data_spec:+ core_data_specs.append(core_data_spec)+ scene_kit_assets_spec = node.scene_kit_assets_spec+ if scene_kit_assets_spec:+ scene_kit_assets_specs.append(scene_kit_assets_spec)+ cxx_resource_spec = node.cxx_resource_spec+ if cxx_resource_spec:+ cxx_resource_specs.append(cxx_resource_spec)++ return AppleResourceSelectionOutput(+ resource_specs = resource_specs,+ asset_catalog_specs = asset_catalog_specs,+ selected_asset_catalog_specs = selected_asset_catalog_specs,+ core_data_specs = core_data_specs,+ scene_kit_assets_spec = scene_kit_assets_specs,+ cxx_resource_specs = cxx_resource_specs,+ )
@@ -0,0 +1,99 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")+load(+ "@prelude//ide_integrations/xcode:data.bzl",+ "XCODE_DATA_SUB_TARGET",+ "XcodeDataInfoKeys",+ "generate_xcode_data",+)+load(":apple_bundle_utility.bzl", "get_bundle_min_target_version", "get_bundle_resource_processing_options")+load(":apple_sdk.bzl", "get_apple_sdk_name")+load(":resource_groups.bzl", "create_resource_graph")+load(":scene_kit_assets_types.bzl", "SceneKitAssetsSpec")++def scene_kit_assets_impl(ctx: AnalysisContext) -> list[Provider]:+ spec = SceneKitAssetsSpec(+ path = ctx.attrs.path,+ )+ graph = create_resource_graph(+ ctx = ctx,+ labels = ctx.attrs.labels,+ deps = [],+ exported_deps = [],+ scene_kit_assets_spec = spec,+ )++ xcode_data_default_info, xcode_data_info = generate_xcode_data(ctx, "apple_asset_catalog", None, _xcode_populate_attributes)++ return [+ DefaultInfo(+ sub_targets = {+ XCODE_DATA_SUB_TARGET: xcode_data_default_info,+ },+ ),+ graph,+ xcode_data_info,+ ]++def compile_scene_kit_assets(ctx: AnalysisContext, specs: list[SceneKitAssetsSpec]) -> Artifact | None:+ if len(specs) == 0:+ return None++ output = ctx.actions.declare_output("SceneKitAssetsCompiled", has_content_based_path = False)++ copy_scene_kit_assets_cmds = []+ for spec in specs:+ copy_scene_kit_assets_cmd = _get_copy_scene_kit_assets_cmd(ctx, spec)+ copy_scene_kit_assets_cmds.append(copy_scene_kit_assets_cmd)++ # Sandboxing and fs isolation on RE machines results in Xcode tools failing+ # when those are working in freshly created directories in buck-out.+ # See https://fb.workplace.com/groups/1042353022615812/permalink/1872164996301273/+ # As a workaround create a directory in tmp, use it for Xcode tools, then+ # copy the result to buck-out.+ wrapper_script, _ = ctx.actions.write(+ "copy_scene_kit_assets_wrapper.sh",+ [+ cmd_args("set -euo pipefail"),+ cmd_args('export TMPDIR="$(mktemp -d)"'),+ cmd_args(copy_scene_kit_assets_cmds),+ cmd_args(output, format = 'mkdir -p {} && cp -r "$TMPDIR"/ {}'),+ ],+ allow_args = True,+ has_content_based_path = False,+ )+ combined_command = cmd_args(["/bin/sh", wrapper_script], hidden = copy_scene_kit_assets_cmds + [output.as_output()])+ processing_options = get_bundle_resource_processing_options(ctx)+ ctx.actions.run(+ combined_command,+ prefer_local = processing_options.prefer_local,+ prefer_remote = processing_options.prefer_remote,+ allow_cache_upload = processing_options.allow_cache_upload,+ category = "scene_kit_assets",+ )+ return output++def _get_copy_scene_kit_assets_cmd(ctx: AnalysisContext, scene_kit_assets_spec: SceneKitAssetsSpec) -> cmd_args:+ scnassets_folder = scene_kit_assets_spec.path.basename+ return cmd_args(+ [+ ctx.attrs._apple_toolchain[AppleToolchainInfo].copy_scene_kit_assets,+ scene_kit_assets_spec.path,+ "-o",+ cmd_args(scnassets_folder, format = "$TMPDIR/{}"),+ "--target-platform=" + get_apple_sdk_name(ctx),+ "--target-version=" + get_bundle_min_target_version(ctx, ctx.attrs.binary),+ ],+ delimiter = " ",+ )++def _xcode_populate_attributes(ctx) -> dict[str, typing.Any]:+ data = {XcodeDataInfoKeys.EXTRA_XCODE_FILES: [ctx.attrs.path]}+ return data
@@ -0,0 +1,11 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++SceneKitAssetsSpec = record(+ path = field(Artifact),+)
@@ -0,0 +1,49 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(":swift_sdk_pcm_compilation.bzl", "get_shared_pcm_compilation_args")+load(":swift_toolchain_types.bzl", "SdkSwiftOverlayInfo", "SdkUncompiledModuleInfo")++def apple_sdk_clang_module_impl(ctx: AnalysisContext) -> list[Provider]:+ cmd = get_shared_pcm_compilation_args(ctx.attrs.module_name)+ overlays = []+ if ctx.attrs.overlays:+ overlays = [SdkSwiftOverlayInfo(overlays = ctx.attrs.overlays)]++ module_info = SdkUncompiledModuleInfo(+ module_name = ctx.attrs.module_name,+ is_framework = ctx.attrs.is_framework,+ is_swiftmodule = False,+ partial_cmd = cmd,+ input_relative_path = ctx.attrs.modulemap_relative_path,+ deps = ctx.attrs.deps,+ cxx_deps = ctx.attrs.cxx_deps,+ overlays_transitive_deps = ctx.attrs.overlays_transitive_deps,+ )++ return [+ DefaultInfo(),+ module_info,+ ] + overlays++# This rule represent a Clang module from SDK and forms a graph of dependencies between such modules.+apple_sdk_clang_module = rule(+ impl = apple_sdk_clang_module_impl,+ attrs = {+ "cxx_deps": attrs.list(attrs.dep(), default = []),+ "deps": attrs.list(attrs.dep(), default = []),+ "is_framework": attrs.bool(default = False),+ # This is a real module name, contrary to `name`+ # which has a special suffix to distinguish Swift and Clang modules with the same name+ "module_name": attrs.string(),+ "modulemap_relative_path": attrs.string(),+ "overlays": attrs.dict(key = attrs.string(), value = attrs.list(attrs.string(), default = []), sorted = False, default = {}),+ # Transitive closure filtered to overlay owners and underlyings.+ "overlays_transitive_deps": attrs.list(attrs.string(), default = []),+ },+)
@@ -0,0 +1,93 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ ":swift_toolchain_types.bzl",+ "SdkSwiftOverlayInfo",+ "SdkUncompiledModuleInfo",+ "SwiftCompiledModuleTset",+ "SwiftToolchainInfo", # @unused Used as a type+ "WrappedSdkCompiledModuleInfo",+)++def is_sdk_modules_provided(toolchain: SwiftToolchainInfo) -> bool:+ has_swift_modules = bool(toolchain.uncompiled_swift_sdk_modules_deps)+ has_clang_modules = bool(toolchain.uncompiled_clang_sdk_modules_deps)+ return has_swift_modules or has_clang_modules++def get_compiled_sdk_clang_deps_tset(ctx: AnalysisContext, deps_providers: list) -> SwiftCompiledModuleTset:+ sdk_deps = [+ d[WrappedSdkCompiledModuleInfo].clang_deps+ for d in deps_providers+ if WrappedSdkCompiledModuleInfo in d and d[WrappedSdkCompiledModuleInfo].clang_deps != None+ ]+ return ctx.actions.tset(SwiftCompiledModuleTset, children = sdk_deps)++def get_compiled_sdk_swift_deps_tset(ctx: AnalysisContext, deps_providers: list) -> SwiftCompiledModuleTset:+ sdk_deps = [+ d[WrappedSdkCompiledModuleInfo].swift_deps+ for d in deps_providers+ if WrappedSdkCompiledModuleInfo in d and d[WrappedSdkCompiledModuleInfo].swift_deps != None+ ]+ return ctx.actions.tset(SwiftCompiledModuleTset, children = sdk_deps)++def get_uncompiled_sdk_deps(sdk_modules: list[str], required_modules: list[str], toolchain: SwiftToolchainInfo) -> list[Dependency]:+ if not is_sdk_modules_provided(toolchain):+ fail("SDK deps are not set for swift_toolchain")++ swift_map = toolchain.uncompiled_swift_sdk_modules_deps+ clang_map = toolchain.uncompiled_clang_sdk_modules_deps++ direct_names = set(sdk_modules + required_modules)++ sdk_deps = []+ for sdk_module_dep_name in list(direct_names):+ if sdk_module_dep_name in swift_map:+ sdk_deps.append(swift_map[sdk_module_dep_name])+ if sdk_module_dep_name in clang_map:+ sdk_deps.append(clang_map[sdk_module_dep_name])++ # ModuleA declares a cross-import overlay on ModuleADependency, which the+ # compiler auto-loads whenever both are visible, even if ModuleADependency+ # only arrives transitively. Match overlays against the precomputed+ # overlay-filtered transitive closure, not just the direct sdk_modules.+ reachable = set(direct_names)+ for sdk_module_dep_name in list(direct_names):+ for uncompiled_sdk_modules_map in (swift_map, clang_map):+ if sdk_module_dep_name not in uncompiled_sdk_modules_map:+ continue+ sdk_dep = uncompiled_sdk_modules_map[sdk_module_dep_name]+ if SdkUncompiledModuleInfo not in sdk_dep:+ continue+ transitive_names = sdk_dep[SdkUncompiledModuleInfo].overlays_transitive_deps or []+ for transitive_name in transitive_names:+ reachable.add(transitive_name)++ sdk_overlays = []+ # Seed with the direct deps: an overlay listed explicitly in sdk_modules+ # is already in sdk_deps above and must not be added a second time.+ seen_overlays = set(direct_names)+ for reachable_name in list(reachable):+ for uncompiled_sdk_modules_map in (swift_map, clang_map):+ if reachable_name not in uncompiled_sdk_modules_map:+ continue+ sdk_dep = uncompiled_sdk_modules_map[reachable_name]+ if SdkSwiftOverlayInfo not in sdk_dep:+ continue+ overlay_info = sdk_dep[SdkSwiftOverlayInfo]+ for underlying_module, overlay_modules in overlay_info.overlays.items():+ # Only add a cross import SDK overlay if both modules associated with the overlay are required+ if underlying_module in reachable:+ # Cross import overlays themselves are always Swift modules, but the underlying module+ # can be a Swift module or a Clang module+ for overlay_name in overlay_modules:+ if overlay_name in swift_map and overlay_name not in seen_overlays:+ seen_overlays.add(overlay_name)+ sdk_overlays.append(swift_map[overlay_name])++ return sdk_deps + sdk_overlays
@@ -0,0 +1,66 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_utility.bzl", "get_base_swiftinterface_compilation_flags")+load(":swift_toolchain_types.bzl", "SdkSwiftOverlayInfo", "SdkUncompiledModuleInfo")++def apple_sdk_swift_module_impl(ctx: AnalysisContext) -> list[Provider]:+ module_name = ctx.attrs.module_name+ cmd = get_base_swiftinterface_compilation_flags(module_name)++ if module_name == "Swift" or module_name == "SwiftOnoneSupport":+ cmd.add([+ "-parse-stdlib",+ ])++ overlays = []+ if ctx.attrs.overlays:+ overlays = [SdkSwiftOverlayInfo(overlays = ctx.attrs.overlays)]++ # The target triple varies in swiftinterface files to use either+ # macos or macosx. To avoid unnecessary module compilation we align+ # on macosx.+ target = ctx.attrs.target+ if "macos" in target and "macosx" not in target:+ target = target.replace("macos", "macosx")++ module_info = SdkUncompiledModuleInfo(+ cxx_deps = ctx.attrs.cxx_deps,+ deps = ctx.attrs.deps,+ input_relative_path = ctx.attrs.swiftinterface_relative_path,+ is_framework = ctx.attrs.is_framework,+ is_swiftmodule = True,+ module_name = ctx.attrs.module_name,+ overlays_transitive_deps = ctx.attrs.overlays_transitive_deps,+ partial_cmd = cmd,+ target = target,+ )++ return [+ DefaultInfo(),+ module_info,+ ] + overlays++# This rule represent a Swift module from SDK and forms a graph of dependencies between such modules.+apple_sdk_swift_module = rule(+ impl = apple_sdk_swift_module_impl,+ attrs = {+ "cxx_deps": attrs.list(attrs.dep(), default = []),+ "deps": attrs.list(attrs.dep(), default = []),+ "is_framework": attrs.bool(default = False),+ # This is a real module name, contrary to `name`+ # which has a special suffix to distinguish Swift and Clang modules with the same name+ "module_name": attrs.string(),+ "overlays": attrs.dict(key = attrs.string(), value = attrs.list(attrs.string(), default = []), sorted = False, default = {}),+ # Transitive closure filtered to overlay owners and underlyings.+ "overlays_transitive_deps": attrs.list(attrs.string(), default = []),+ # A prefixed path ($SDKROOT/$PLATFORM_DIR) to swiftinterface textual file.+ "swiftinterface_relative_path": attrs.option(attrs.string(), default = None), # if `swiftinterface` is None represents a Root node.+ "target": attrs.string(),+ },+)
@@ -0,0 +1,1727 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactInfoTag",+ "ArtifactTSet", # @unused Used as a type+ "make_artifact_tset",+ "project_artifacts",+)+load("@prelude//:paths.bzl", "paths")+load("@prelude//apple:apple_error_handler.bzl", "apple_build_error_handler")+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")+load("@prelude//apple:apple_utility.bzl", "get_disable_pch_validation_flags", "get_module_name")+load("@prelude//apple:modulemap.bzl", "create_modulemap")+load("@prelude//apple/swift:swift_helpers.bzl", "compile_with_argsfile", "compile_with_argsfile_cmd", "uses_explicit_modules")+load(+ "@prelude//apple/swift:swift_types.bzl",+ "EXPLICIT_MODULES_CATEGORY_SUFFIX",+ "SWIFTMODULE_COMPILE_CATEGORY",+ "SWIFTMODULE_EXTENSION",+ "SWIFT_COMPILE_CATEGORY",+ "SWIFT_EXTENSION",+ "SwiftDependencyInfo",+ "SwiftMacroPlugin",+ "get_implicit_framework_search_path_providers",+)+load("@prelude//cxx:argsfiles.bzl", "CompileArgsfile", "CompileArgsfiles")+load("@prelude//cxx:cxx_context.bzl", "get_cxx_platform_info", "get_cxx_toolchain_info")+load("@prelude//cxx:cxx_library_utility.bzl", "cxx_attr_deps", "cxx_attr_exported_deps")+load(+ "@prelude//cxx:cxx_sources.bzl",+ "CxxSrcWithFlags", # @unused Used as a type+)+load("@prelude//cxx:cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload")+load(+ "@prelude//cxx:headers.bzl",+ "CHeader",+ "HeaderMode",+ "prepare_headers",+)+load(+ "@prelude//cxx:link_groups.bzl",+ "get_link_group",+)+load(+ "@prelude//cxx:preprocessor.bzl",+ "CPreprocessor",+ "CPreprocessorArgs",+ "CPreprocessorInfo", # @unused Used as a type+ "cxx_inherited_preprocessor_infos",+ "cxx_merge_cpreprocessors",+)+load("@prelude//cxx:target_sdk_version.bzl", "get_target_triple")+load(+ "@prelude//linking:link_info.bzl",+ "LinkInfo", # @unused Used as a type+ "SwiftmoduleLinkable", # @unused Used as a type+)+load("@prelude//utils:actions.bzl", "ActionExecutionAttributes")+load("@prelude//utils:arglike.bzl", "ArgLike")+load(+ ":apple_sdk_modules_utility.bzl",+ "get_compiled_sdk_clang_deps_tset",+ "get_compiled_sdk_swift_deps_tset",+ "get_uncompiled_sdk_deps",+ "is_sdk_modules_provided",+)+load(+ ":swift_debug_info_utils.bzl",+ "extract_and_merge_clang_debug_infos",+ "extract_and_merge_swift_debug_infos",+)+load(+ ":swift_incremental_support.bzl",+ "INCREMENTAL_SWIFT_COMPILE_BATCH_SIZE",+ "INCREMENTAL_SWIFT_COMPILE_MAX_NUM_THREADS",+ "IncrementalCompilationInput",+ "get_incremental_file_hashing_enabled",+ "get_incremental_object_compilation_flags",+ "get_incremental_remote_outputs_enabled",+ "get_incremental_split_actions",+ "get_incremental_swiftmodule_compilation_flags",+ "get_uses_content_based_paths",+ "should_build_swift_incrementally",+ "should_build_swiftmodule_incrementally",+)+load(":swift_module_map.bzl", "write_swift_module_map_with_deps")+load(":swift_output_file_map.bzl", "add_dependencies_output", "get_modularization_dependency_graph_output_map")+load(":swift_pcm_compilation.bzl", "compile_underlying_pcm", "get_compiled_pcm_deps_tset", "get_swift_pcm_anon_targets")+load(+ ":swift_pcm_compilation_types.bzl",+ "SwiftPCMUncompiledInfo",+)+load(":swift_sdk_flags.bzl", "get_sdk_flags")+load(":swift_sdk_pcm_compilation.bzl", "get_swift_sdk_pcm_anon_targets")+load(":swift_swiftinterface_compilation.bzl", "get_swift_interface_anon_targets")+load(":swift_toolchain.bzl", "get_swift_toolchain_info", "include_path_for_relative_module_map_paths", "supports_modulemaps_with_hmaps")+load(+ ":swift_toolchain_types.bzl",+ "SwiftCompiledModuleInfo",+ "SwiftCompiledModuleTset",+ "SwiftObjectFormat",+ "SwiftToolchainInfo",+ "clang_module_file_args",+)++SwiftCompilationDatabase = record(+ db = field(Artifact),+ other_outputs = field(ArgLike),+)++SwiftObjectOutput = record(+ object_files = field(list[Artifact]),+ argsfiles = field(CompileArgsfiles),+ output_map_artifact = field(Artifact | None),+ swiftdeps = field(list[Artifact]),+)++SwiftLibraryForDistributionOutput = record(+ swiftinterface = field(Artifact),+ private_swiftinterface = field(Artifact),+ swiftdoc = field(Artifact),+)++SwiftCompilationOutput = record(+ # The object file output from compilation.+ object_files = field(list[Artifact]),+ object_format = field(SwiftObjectFormat),+ # The swiftmodule file output from compilation.+ swiftmodule = field(Artifact),+ # Stderr output when running `-typecheck`+ typecheck_file = field(Artifact),+ # The dependency info provider that contains the swiftmodule+ # search paths required for compilation and linking.+ dependency_info = field(SwiftDependencyInfo),+ # Preprocessor info required for ObjC compilation of this library.+ pre = field(CPreprocessor),+ # Exported preprocessor info required for ObjC compilation of rdeps.+ exported_pre = field(CPreprocessor),+ # Exported -Swift.h header+ exported_swift_header = field(Artifact),+ # Argsfiles used to compile object files.+ argsfiles = field(CompileArgsfiles),+ # A tset of (SDK/first-party) swiftmodule artifacts required to be linked into binary.+ # Different outputs of Swift compilation actions might contain duplicates of SDK swiftmodule artifacts.+ swift_debug_info = field(ArtifactTSet),+ # A tset of PCM artifacts used to compile a Swift module.+ clang_debug_info = field(ArtifactTSet),+ # Info required for `[swift-compilation-database]` subtarget.+ compilation_database = field(SwiftCompilationDatabase),+ # An artifact that represent the Swift module map for this target.+ output_map_artifact = field(Artifact | None),+ # The JSON file passed to swiftc via -explicit-swift-module-map-file that+ # describes all transitive Swift module dependencies. Only populated when+ # explicit modules are enabled.+ swift_module_map_artifact = field(Artifact | None, None),+ # An optional artifact with files that support consuming the generated library with later versions of the swift compiler.+ swift_library_for_distribution_output = field(SwiftLibraryForDistributionOutput | None),+ # A list of artifacts that stores the index data+ index_store = field(Artifact),+ # A list of artifacts of the swiftdeps files produced during incremental compilation.+ swiftdeps = field(list[Artifact]),+ compiled_underlying_pcm_artifact = field(Artifact | None),+ # Modularization dependency dot graph+ modularization_dependency_graph = field(Artifact | None),+)++SwiftCompileResult = record(+ swift_compilation = field(SwiftCompilationOutput | None),+ objc_swift_interface = field(DefaultInfo),+ swiftinterface = field(Artifact | None),+ ast = field(Artifact | None),+)++SwiftDebugInfo = record(+ static = list[ArtifactTSet],+ shared = list[ArtifactTSet],+)++_REQUIRED_SDK_MODULES = ["Swift", "SwiftOnoneSupport", "Darwin", "_Concurrency", "_StringProcessing"]++_REQUIRED_SDK_CXX_MODULES = _REQUIRED_SDK_MODULES + ["std"]++_INDEX_SYSTEM_MODULES = read_root_config("swift", "index_system_modules", "false").lower() == "true"++def _get_target_flags(ctx) -> list[str]:+ if get_cxx_platform_info(ctx).name.startswith("linux"):+ # Linux triples are unversioned+ return ["-target", "{}-unknown-linux-gnu".format(get_swift_toolchain_info(ctx).architecture)]+ else:+ return ["-target", get_target_triple(ctx)]++def get_swift_anonymous_targets_for_prebuilt_framework(ctx: AnalysisContext, get_providers: typing.Callable) -> Promise:+ # Get SDK deps from direct dependencies,+ # all transitive deps will be compiled recursively.+ direct_uncompiled_sdk_deps = get_uncompiled_sdk_deps(+ ctx.attrs.sdk_modules,+ _REQUIRED_SDK_MODULES,+ get_swift_toolchain_info(ctx),+ )++ # Recursively compiling headers of direct and transitive deps as PCM modules,+ # prebuilt_apple_framework rule doesn't support custom compiler_flags, so we pass only target triple.+ pcm_targets = get_swift_pcm_anon_targets(+ ctx,+ ctx.attrs.deps,+ _get_target_flags(ctx),+ False, # C++ Interop is disabled for now.+ )++ # Recursively compiling SDK's Clang dependencies,+ # prebuilt_apple_framework rule doesn't support custom compiler_flags, so we pass only target triple.+ sdk_pcm_targets = get_swift_sdk_pcm_anon_targets(+ ctx,+ False,+ direct_uncompiled_sdk_deps,+ _get_target_flags(ctx),+ )++ # Recursively compile SDK and prebuilt_apple_framework's Swift dependencies.+ swift_interface_anon_targets = get_swift_interface_anon_targets(+ ctx,+ direct_uncompiled_sdk_deps,+ )+ return ctx.actions.anon_targets(pcm_targets + sdk_pcm_targets + swift_interface_anon_targets).promise.map(get_providers)++def get_swift_anonymous_targets(ctx: AnalysisContext, get_apple_library_providers: typing.Callable) -> Promise:+ swift_cxx_flags = get_swift_cxx_flags(ctx)++ # Get SDK deps from direct dependencies,+ # all transitive deps will be compiled recursively.+ direct_uncompiled_sdk_deps = get_uncompiled_sdk_deps(+ ctx.attrs.sdk_modules,+ _REQUIRED_SDK_CXX_MODULES if ctx.attrs.enable_cxx_interop else _REQUIRED_SDK_MODULES,+ get_swift_toolchain_info(ctx),+ )++ # Recursively compiling headers of direct and transitive deps as PCM modules,+ # passing apple_library's cxx flags through that must be used for all downward PCM compilations.+ pcm_targets = get_swift_pcm_anon_targets(+ ctx,+ ctx.attrs.deps + getattr(ctx.attrs, "exported_deps", []),+ swift_cxx_flags,+ ctx.attrs.enable_cxx_interop,+ )++ # Recursively compiling SDK's Clang dependencies,+ # passing apple_library's cxx flags through that must be used for all downward PCM compilations.+ sdk_pcm_targets = get_swift_sdk_pcm_anon_targets(+ ctx,+ ctx.attrs.enable_cxx_interop,+ direct_uncompiled_sdk_deps,+ swift_cxx_flags,+ )++ # Recursively compiling SDK's Swift dependencies,+ # passing apple_library's cxx flags through that must be used for all downward PCM compilations.+ swift_interface_anon_targets = get_swift_interface_anon_targets(+ ctx,+ direct_uncompiled_sdk_deps,+ )+ return ctx.actions.anon_targets(pcm_targets + sdk_pcm_targets + swift_interface_anon_targets).promise.map(get_apple_library_providers)++def get_swift_cxx_flags(ctx: AnalysisContext) -> list[str]:+ """Iterates through `swift_compiler_flags` and returns a list of flags that might affect Clang compilation"""+ gather, next = ([], False)++ # Each target needs to propagate the compilers target triple.+ # This can vary depending on the deployment target of each library.+ gather += _get_target_flags(ctx)++ for f in ctx.attrs.swift_compiler_flags:+ if next:+ gather.append("-Xcc")+ gather.append(str(f).replace('"', ""))+ next = False+ elif str(f) == '"-Xcc"':+ next = True+ elif str(f) == '"-warnings-as-errors"':+ gather.append("-warnings-as-errors")+ elif str(f) == '"-no-warnings-as-errors"':+ gather.append("-no-warnings-as-errors")++ if ctx.attrs.enable_cxx_interop:+ gather += ["-cxx-interoperability-mode=default"]++ gather += ["-swift-version", ctx.attrs.swift_version]++ return gather++def _get_compiled_underlying_pcm(+ ctx: AnalysisContext,+ module_name: str,+ module_pp_info: CPreprocessor | None,+ exported_headers: list[CHeader],+ deps_providers: list,+ swift_cxx_flags: list[str],+ framework_search_paths: cmd_args,+) -> SwiftCompiledModuleInfo | None:+ if supports_modulemaps_with_hmaps(ctx):+ # We need to provide a headermap pointing to the exported headers of+ # this target. Normally this would be passed through from the cxx+ # layer, but the underlying module compilation happens before the cxx+ # header map is generated, so we need to create one specifically for+ # this module.+ exported_headers_dict = {paths.join(h.namespace, h.name): h.artifact for h in exported_headers}+ header_map = prepare_headers(+ ctx.actions,+ get_cxx_toolchain_info(ctx),+ exported_headers_dict,+ "swift-underlying-headers",+ HeaderMode("header_map_only"),+ allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs),+ )+ header_map_args = cmd_args(header_map.include_path, format = "-I{}")++ # We need to collect the preprocessor info from exported_deps for their+ # header map search paths.+ preprocessor_info = cxx_merge_cpreprocessors(+ ctx.actions,+ [CPreprocessor(args = CPreprocessorArgs(args = [header_map_args]))],+ cxx_inherited_preprocessor_infos(ctx.attrs.exported_deps),+ )+ else:+ preprocessor_info = None++ underlying_swift_pcm_uncompiled_info = get_swift_pcm_uncompile_info(+ ctx,+ preprocessor_info,+ module_pp_info,+ )+ if not underlying_swift_pcm_uncompiled_info:+ return None++ return compile_underlying_pcm(+ ctx,+ module_name,+ underlying_swift_pcm_uncompiled_info,+ deps_providers,+ swift_cxx_flags,+ framework_search_paths,+ )++def _generate_umbrella_header(ctx: AnalysisContext, module_name: str, exported_headers: list[CHeader], uses_content_based_paths: bool) -> [CHeader, None]:+ """Auto-generate an umbrella header for mixed ObjC/Swift modules.++ The -Swift.h generated by the compiler may contain+ `#import <ModuleName/ModuleName.h>`. If no manually-created umbrella+ header exists, we generate one that #imports all exported ObjC headers+ so that import resolves correctly.+ """+ umbrella_header_name = module_name + ".h"+ umbrella_import_path = module_name + "/" + umbrella_header_name+ for h in exported_headers:+ if h.namespace:+ header_import_path = h.namespace + "/" + h.name+ else:+ header_import_path = h.name+ if header_import_path == umbrella_import_path:+ return None++ umbrella_content = "// Auto-generated umbrella header for {}\n".format(module_name)+ for h in exported_headers:+ if h.namespace:+ umbrella_content += "#import <{}/{}>\n".format(h.namespace, h.name)+ else:+ umbrella_content += "#import <{}/{}>\n".format(module_name, h.name)+ umbrella_artifact = ctx.actions.declare_output(+ "__{}_umbrella__/{}".format(module_name, umbrella_header_name),+ has_content_based_path = uses_content_based_paths,+ )+ ctx.actions.write(umbrella_artifact.as_output(), umbrella_content)+ return CHeader(+ artifact = umbrella_artifact,+ name = umbrella_header_name,+ namespace = module_name,+ named = False,+ )++def compile_swift(+ ctx: AnalysisContext,+ srcs: list[CxxSrcWithFlags],+ parse_as_library: bool,+ deps_providers: list,+ module_name: str,+ exported_headers: list[CHeader],+ exported_objc_modulemap_pp_info: [CPreprocessor, None],+ framework_search_paths_flags: cmd_args,+ extra_search_paths_flags: list[ArgLike] = [],+ compile_category = SWIFT_COMPILE_CATEGORY,+ compile_swiftmodule_category = SWIFTMODULE_COMPILE_CATEGORY,+ is_macro = False,+) -> SwiftCompileResult:+ # If this target imports XCTest we need to pass the search path to its swiftmodule.+ framework_search_paths = cmd_args()+ framework_search_paths.add(_get_xctest_swiftmodule_search_path(ctx))++ uses_content_based_paths = get_uses_content_based_paths(ctx)++ # Pass the framework search paths to the driver and clang importer. This is required+ # for pcm compilation, which does not pass through driver search paths.+ framework_search_paths.add(framework_search_paths_flags)+ framework_search_paths.add(cmd_args(framework_search_paths_flags, prepend = "-Xcc"))++ # If a target exports ObjC headers and Swift explicit modules are enabled,+ # we need to precompile a PCM of the underlying module and supply it to the Swift compilation.+ swift_cxx_flags = get_swift_cxx_flags(ctx)+ if uses_explicit_modules(ctx):+ exported_compiled_underlying_pcm = (+ _get_compiled_underlying_pcm(+ ctx,+ module_name,+ exported_objc_modulemap_pp_info,+ exported_headers,+ deps_providers,+ swift_cxx_flags,+ framework_search_paths,+ )+ if exported_objc_modulemap_pp_info+ else None+ )+ else:+ exported_compiled_underlying_pcm = None++ # We always track inputs for dependency file tracking, but optionally set+ # the tag on the action depending on the use_depsfiles config.+ inputs_tag = ctx.actions.artifact_tag()++ shared_flags, swift_module_map_artifact = _get_shared_flags(+ ctx = ctx,+ deps_providers = deps_providers,+ parse_as_library = parse_as_library,+ public_module = exported_compiled_underlying_pcm,+ module_name = module_name,+ public_modulemap_pp_info = exported_objc_modulemap_pp_info,+ extra_search_paths_flags = extra_search_paths_flags,+ inputs_tag = inputs_tag,+ is_macro = is_macro,+ )+ shared_flags.add(framework_search_paths)+ objc_swift_interface_info = _create_objc_swift_interface(ctx, shared_flags, module_name)++ if not srcs:+ return SwiftCompileResult(swift_compilation = None, objc_swift_interface = objc_swift_interface_info, swiftinterface = None, ast = None)++ # Content-based path hashing and Swift incremental compilation are incompatible.+ if uses_content_based_paths and should_build_swift_incrementally(ctx):+ fail("Content-based path hashing and Swift incremental compilation cannot be enabled at the same time.")++ toolchain = get_swift_toolchain_info(ctx)+ output_header = ctx.actions.declare_output(module_name + "-Swift.h", has_content_based_path = uses_content_based_paths)+ output_swiftmodule = ctx.actions.declare_output(module_name + SWIFTMODULE_EXTENSION, has_content_based_path = uses_content_based_paths)++ swift_framework_output = None+ output_swiftinterface = None+ swiftinterface_subtarget_enabled = getattr(ctx.attrs, "swiftinterface_subtarget_enabled", False)++ if _should_compile_with_evolution(ctx):+ swift_framework_output = SwiftLibraryForDistributionOutput(+ swiftinterface = ctx.actions.declare_output(module_name + ".swiftinterface", has_content_based_path = uses_content_based_paths),+ private_swiftinterface = ctx.actions.declare_output(module_name + ".private.swiftinterface", has_content_based_path = uses_content_based_paths),+ swiftdoc = ctx.actions.declare_output(+ module_name + ".swiftdoc", has_content_based_path = uses_content_based_paths+ ), # this is generated automatically once we pass -emit-module-info, so must have this name+ )+ if swiftinterface_subtarget_enabled:+ output_swiftinterface = swift_framework_output.swiftinterface+ elif swiftinterface_subtarget_enabled:+ output_swiftinterface = ctx.actions.declare_output(module_name + ".swiftinterface", has_content_based_path = uses_content_based_paths)+ _compile_swiftinterface(+ ctx,+ toolchain,+ shared_flags,+ srcs,+ output_swiftinterface,+ )++ output_ast = None+ if getattr(ctx.attrs, "swift_dump_ast_subtarget_enabled", False):+ output_ast = ctx.actions.declare_output(module_name + "-ast-dump", dir = True, has_content_based_path = uses_content_based_paths)+ _compile_dump_ast(+ ctx,+ toolchain,+ shared_flags,+ srcs,+ output_ast,+ )++ # When compiling with WMO or incremental with split actions enabled, we compile+ # the swiftmodule separately. In pure incremental mode, we generate the swiftmodule+ # as part of the compile action to make use of incrementality.+ if not should_build_swift_incrementally(ctx) or get_incremental_split_actions(ctx):+ _compile_swiftmodule(+ ctx,+ toolchain,+ shared_flags,+ srcs,+ output_swiftmodule,+ output_header,+ swift_framework_output,+ inputs_tag,+ compile_swiftmodule_category,+ )++ object_output = _compile_object(+ ctx = ctx,+ toolchain = toolchain,+ shared_flags = shared_flags,+ srcs = srcs,+ output_swiftmodule = output_swiftmodule,+ output_header = output_header,+ inputs_tag = inputs_tag,+ category = compile_category,+ )++ typecheck_file = _compile_typecheck_diagnostics(+ ctx = ctx,+ toolchain = toolchain,+ shared_flags = shared_flags,+ srcs = srcs,+ )++ modularization_dependency_graph = _compile_modularization_dependency_graph(ctx, toolchain, shared_flags, srcs)++ index_store = _compile_index_store(ctx, toolchain, shared_flags, srcs)++ generated_umbrella_header = (+ _generate_umbrella_header(+ ctx,+ module_name,+ exported_headers,+ uses_content_based_paths,+ )+ if exported_headers and not getattr(ctx.attrs, "disable_generated_umbrella_header", True)+ else None+ )++ # Swift libraries extend the ObjC modulemaps to include the -Swift.h header+ modulemap_pp_info = create_modulemap(+ ctx,+ name = "swift-extended",+ module_name = module_name,+ headers = exported_headers,+ swift_header = output_header,+ )+ exported_swift_header = CHeader(+ artifact = output_header,+ name = output_header.basename,+ namespace = module_name,+ named = False,+ )+ exported_pp_info = CPreprocessor(+ headers = [exported_swift_header] + ([generated_umbrella_header] if generated_umbrella_header else []),+ modular_args = modulemap_pp_info.modular_args,+ args = CPreprocessorArgs(args = modulemap_pp_info.args.args),+ modulemap_artifact = modulemap_pp_info.modulemap_artifact,+ )++ # We also need to include the unprefixed -Swift.h header in this libraries preprocessor info+ swift_header = CHeader(+ artifact = output_header,+ name = output_header.basename,+ namespace = "",+ named = False,+ )+ pre = CPreprocessor(headers = [swift_header])++ clang_debug_artifacts = [exported_pp_info.modulemap_artifact]+ if exported_compiled_underlying_pcm:+ # The compiled PCM of the underlying clang module+ clang_debug_artifacts.append(exported_compiled_underlying_pcm.output_artifact)++ # The modulemap and headers excluding the Swift header+ clang_debug_artifacts.append(exported_objc_modulemap_pp_info.modulemap_artifact)++ # Pass up the swiftmodule paths for this module and its exported_deps+ return SwiftCompileResult(+ swift_compilation = SwiftCompilationOutput(+ output_map_artifact = object_output.output_map_artifact,+ swift_module_map_artifact = swift_module_map_artifact,+ object_files = object_output.object_files,+ object_format = toolchain.object_format,+ swiftmodule = output_swiftmodule,+ typecheck_file = typecheck_file,+ compiled_underlying_pcm_artifact = exported_compiled_underlying_pcm.output_artifact if exported_compiled_underlying_pcm else None,+ dependency_info = get_swift_dependency_info(+ ctx,+ output_swiftmodule,+ deps_providers,+ is_macro,+ swift_ast_dump_artifacts = filter(None, [output_ast]),+ ),+ pre = pre,+ exported_pre = exported_pp_info,+ exported_swift_header = exported_swift_header.artifact,+ argsfiles = object_output.argsfiles,+ swift_debug_info = extract_and_merge_swift_debug_infos(ctx, deps_providers, [output_swiftmodule]),+ clang_debug_info = extract_and_merge_clang_debug_infos(+ ctx,+ deps_providers,+ clang_debug_artifacts,+ ),+ compilation_database = _create_compilation_database(ctx, srcs, object_output.argsfiles.relative[SWIFT_EXTENSION]),+ swift_library_for_distribution_output = swift_framework_output,+ index_store = index_store,+ swiftdeps = object_output.swiftdeps,+ modularization_dependency_graph = modularization_dependency_graph,+ ),+ objc_swift_interface = objc_swift_interface_info,+ swiftinterface = output_swiftinterface,+ ast = output_ast,+ )++def _compile_swiftinterface(+ ctx: AnalysisContext, toolchain: SwiftToolchainInfo, shared_flags: cmd_args, srcs: list[CxxSrcWithFlags], output_swiftinterface: Artifact+):+ swiftinterface_argsfile = cmd_args(shared_flags)+ swiftinterface_argsfile.add([+ # Required as emitting a swiftinterface without library evolution+ # produces a warning.+ "-no-warnings-as-errors",+ # Workaround to avoid producing swiftdoc and other auxiliary outputs.+ "-typecheck",+ "-wmo",+ ])+ swiftinterface_cmd = cmd_args([+ "-emit-module-interface",+ "-emit-module-interface-path",+ output_swiftinterface.as_output(),+ "-Xwrapper",+ "-remove-module-prefixes",+ ])+ _compile_with_argsfile(+ ctx = ctx,+ category = "emit_swiftinterface",+ shared_flags = swiftinterface_argsfile,+ srcs = srcs,+ additional_flags = swiftinterface_cmd,+ toolchain = toolchain,+ supports_serialized_errors = False,+ )++def _compile_dump_ast(ctx: AnalysisContext, toolchain: SwiftToolchainInfo, shared_flags: cmd_args, srcs: list[CxxSrcWithFlags], output_ast_dir: Artifact):+ ast_output = output_ast_dir.as_output()+ output_file_map = {}+ for src in srcs:+ # safe_name includes path in case basenames clash+ safe_name = src.file.short_path.replace("/", "_")+ output_file_map[src.file] = {+ "ast-dump": cmd_args(ast_output, format = "{}/" + safe_name + ".ast", delimiter = ""),+ }++ argfile_cmd = cmd_args(shared_flags)+ if ctx.attrs.swift_module_skip_function_bodies:+ argfile_cmd.add([+ "-Xfrontend",+ "-experimental-skip-non-inlinable-function-bodies-without-types",+ ])++ additional_flags = cmd_args(["-dump-ast"])+ additional_flags.add(cmd_args(hidden = ast_output))++ # `-dump-ast` disables `-wmo`. Without an explicit `-j`, those jobs run+ # serially over each file in larger modules, becoming potential bottlenecks.+ additional_flags.add([+ "-enable-batch-mode",+ "-driver-batch-size-limit",+ str(INCREMENTAL_SWIFT_COMPILE_BATCH_SIZE),+ "-j",+ str(INCREMENTAL_SWIFT_COMPILE_MAX_NUM_THREADS),+ ])++ _compile_with_argsfile(+ ctx = ctx,+ category = "dump_ast",+ shared_flags = argfile_cmd,+ srcs = srcs,+ additional_flags = additional_flags,+ toolchain = toolchain,+ num_threads = INCREMENTAL_SWIFT_COMPILE_MAX_NUM_THREADS,+ output_file_map = output_file_map,+ supports_serialized_errors = False,+ incremental_build_allowed = False,+ )++# We use separate actions for swiftmodule and object file output. This+# improves build parallelism at the cost of duplicated work, but by disabling+# type checking in function bodies the swiftmodule compilation can be done much+# faster than object file output.+def _compile_swiftmodule(+ ctx: AnalysisContext,+ toolchain: SwiftToolchainInfo,+ shared_flags: cmd_args,+ srcs: list[CxxSrcWithFlags],+ output_swiftmodule: Artifact,+ output_header: Artifact,+ swift_framework_output: SwiftLibraryForDistributionOutput | None,+ inputs_tag: ArtifactTag,+ category: str,+) -> CompileArgsfiles:+ # The incremental swiftmodule action is opt-in and only supported when+ # we are not emitting library evolution outputs (which require WMO).+ build_swiftmodule_incrementally = should_build_swiftmodule_incrementally(ctx) and swift_framework_output == None++ argfile_cmd = cmd_args(shared_flags)+ argfile_cmd.add("-disable-cmo")++ # Shared between WMO and incremental swiftmodule actions: emit the+ # `.swiftmodule` + generated ObjC header, set up the include path for+ # relative module map paths, and (when requested) skip non-inlinable+ # function bodies for faster swiftmodule emission.+ cmd = cmd_args(+ "-emit-objc-header",+ "-emit-objc-header-path",+ output_header.as_output(),+ "-emit-module",+ "-emit-module-path",+ output_swiftmodule.as_output(),+ )+ cmd.add(include_path_for_relative_module_map_paths(ctx))+ if ctx.attrs.swift_module_skip_function_bodies:+ argfile_cmd.add([+ "-Xfrontend",+ "-experimental-skip-non-inlinable-function-bodies-without-types",+ ])++ output_file_map = {}+ incremental_artifacts = None+ skip_incremental_outputs = False++ if build_swiftmodule_incrementally:+ incremental_compilation_output = get_incremental_swiftmodule_compilation_flags(ctx, srcs)+ cmd.add(incremental_compilation_output.incremental_flags_cmd)+ output_file_map = incremental_compilation_output.output_file_map+ skip_incremental_outputs = incremental_compilation_output.skip_incremental_outputs+ incremental_artifacts = IncrementalCompilationInput(+ depfiles = incremental_compilation_output.depfiles,+ swiftdeps = incremental_compilation_output.swiftdeps,+ swiftdoc = None,+ )+ else:+ argfile_cmd.add([+ "-wmo",+ ])++ if swift_framework_output:+ argfile_cmd.add([+ "-enable-library-evolution",+ ])+ cmd.add([+ "-emit-module-interface",+ "-emit-module-interface-path",+ swift_framework_output.swiftinterface.as_output(),+ "-emit-private-module-interface-path",+ swift_framework_output.private_swiftinterface.as_output(),+ # Module verification fails here as the clang modules+ # are not loaded correctly.+ "-no-verify-emitted-module-interface",+ ])++ # There is no driver flag to specify the swiftdoc output path+ # TODO: use an output file map for this.+ cmd.add(cmd_args(hidden = swift_framework_output.swiftdoc.as_output()))++ dep_files = {}+ # With -skip-incremental-output the output_file_map is an output, so we+ # cannot support depsfiles. With incremental file hashing the dep_file+ # is also unnecessary.+ emit_depsfiles = (+ toolchain.use_depsfiles and not skip_incremental_outputs and not (build_swiftmodule_incrementally and get_incremental_file_hashing_enabled(ctx))+ )+ if emit_depsfiles:+ add_dependencies_output(ctx, output_file_map, cmd, "swiftmodule", inputs_tag)+ dep_files["swiftmodule"] = inputs_tag++ ret, _ = _compile_with_argsfile(+ ctx = ctx,+ category = category,+ extension = SWIFTMODULE_EXTENSION,+ shared_flags = argfile_cmd,+ srcs = srcs,+ additional_flags = cmd,+ toolchain = toolchain,+ num_threads = 1,+ dep_files = dep_files,+ output_file_map = output_file_map,+ artifact_tag = inputs_tag,+ incremental_build_allowed = build_swiftmodule_incrementally,+ skip_incremental_outputs = skip_incremental_outputs,+ objects = [],+ incremental_artifacts = incremental_artifacts,+ )+ return ret++def _compile_typecheck_diagnostics(ctx: AnalysisContext, toolchain: SwiftToolchainInfo, shared_flags: cmd_args, srcs: list[CxxSrcWithFlags]) -> Artifact:+ category = "swift_typecheck"+ uses_content_based_paths = get_uses_content_based_paths(ctx)++ if uses_explicit_modules(ctx):+ category += "_with_explicit_mods"++ additional_flags = cmd_args([+ "-typecheck",+ "-wmo",+ ])++ swift_cmd_output = compile_with_argsfile_cmd(+ ctx = ctx,+ category = category,+ shared_flags = shared_flags,+ srcs = srcs,+ additional_flags = additional_flags,+ toolchain = toolchain,+ output_file_map = {},+ supports_output_file_map = True,+ supports_serialized_errors = False,+ skip_incremental_outputs = True,+ incremental_remote_outputs = False,+ objects = [],+ incremental_artifacts = None,+ artifact_tag = None,+ )++ typecheck_file = ctx.actions.declare_output("swift-typecheck-stderr", has_content_based_path = uses_content_based_paths)++ cxx_toolchain = get_cxx_toolchain_info(ctx)+ typecheck_cmd = cmd_args([+ cxx_toolchain.internal_tools.stderr_to_file,+ cmd_args(typecheck_file.as_output(), format = "--out={}"),+ swift_cmd_output.cmd,+ ])++ ctx.actions.run(+ typecheck_cmd,+ category = category,+ )++ return typecheck_file++def _compile_object(+ ctx: AnalysisContext,+ toolchain: SwiftToolchainInfo,+ shared_flags: cmd_args,+ srcs: list[CxxSrcWithFlags],+ output_swiftmodule: Artifact,+ output_header: Artifact,+ inputs_tag: ArtifactTag,+ category: str,+) -> SwiftObjectOutput:+ dep_files = {}+ output_file_map = {}+ emit_depsfiles = toolchain.use_depsfiles and not get_incremental_file_hashing_enabled(ctx) and not get_incremental_split_actions(ctx)+ skip_incremental_outputs = False+ module_name = get_module_name(ctx)+ uses_content_based_paths = get_uses_content_based_paths(ctx)++ if should_build_swift_incrementally(ctx):+ output_swiftdoc = None+ if not get_incremental_split_actions(ctx):+ # define this here as we will only have an artifact for the purposes of incremental rebuilds.+ output_swiftdoc = ctx.actions.declare_output(module_name + ".swiftdoc", has_content_based_path = uses_content_based_paths)++ incremental_compilation_output = get_incremental_object_compilation_flags(ctx, srcs, output_swiftmodule, output_swiftdoc, output_header)+ cmd = incremental_compilation_output.incremental_flags_cmd++ # With -skip-incremental-output the output_file_map is an output, so+ # we cannot support depsfiles.+ emit_depsfiles = emit_depsfiles and not incremental_compilation_output.skip_incremental_outputs+ num_threads = incremental_compilation_output.num_threads+ objects = incremental_compilation_output.artifacts+ output_file_map = incremental_compilation_output.output_file_map+ skip_incremental_outputs = incremental_compilation_output.skip_incremental_outputs+ swiftdeps = incremental_compilation_output.swiftdeps+ depfiles = incremental_compilation_output.depfiles+ incremental_artifacts = IncrementalCompilationInput(depfiles = depfiles, swiftdeps = swiftdeps, swiftdoc = output_swiftdoc)+ else:+ num_threads = 1+ swiftdeps = []+ output_object = ctx.actions.declare_output(module_name + SWIFT_EXTENSION + ".o", has_content_based_path = uses_content_based_paths)+ objects = [output_object]+ object_format = toolchain.object_format.value+ embed_bitcode = False+ if toolchain.object_format == SwiftObjectFormat("object-embed-bitcode"):+ object_format = "object"+ embed_bitcode = True++ cmd = cmd_args([+ "-emit-{}".format(object_format),+ "-o",+ output_object.as_output(),+ "-wmo",+ ])+ incremental_artifacts = None++ if embed_bitcode:+ cmd.add("--embed-bitcode")++ if emit_depsfiles:+ add_dependencies_output(ctx, output_file_map, cmd, "object", inputs_tag)+ dep_files["object"] = inputs_tag++ if _should_compile_with_evolution(ctx):+ cmd.add(["-enable-library-evolution"])++ argsfiles, output_map_artifact = _compile_with_argsfile(+ ctx = ctx,+ category = category,+ extension = SWIFT_EXTENSION,+ shared_flags = shared_flags,+ srcs = srcs,+ additional_flags = cmd,+ toolchain = toolchain,+ num_threads = num_threads,+ dep_files = dep_files,+ output_file_map = output_file_map,+ skip_incremental_outputs = skip_incremental_outputs,+ objects = objects,+ incremental_artifacts = incremental_artifacts,+ artifact_tag = inputs_tag,+ )++ return SwiftObjectOutput(+ object_files = objects,+ argsfiles = argsfiles,+ output_map_artifact = output_map_artifact,+ swiftdeps = swiftdeps,+ )++def _compile_modularization_dependency_graph(+ ctx: AnalysisContext, toolchain: SwiftToolchainInfo, shared_flags: cmd_args, srcs: list[CxxSrcWithFlags]+) -> Artifact | None:+ # -emit-modularization-dependency-dot-graph is only understood by the Pika+ # toolchain's swiftc; Xcode's fails the action with "unknown argument".+ if not toolchain.supports_modularization_dependency_graph:+ return None++ modularization_dependecy_graph_output = ctx.actions.declare_output(+ "__modularization_dependency_graph__/swift_{}.dot".format(get_module_name(ctx)), has_content_based_path = False+ )+ cmd = cmd_args(+ "-emit-modularization-dependency-dot-graph",+ modularization_dependecy_graph_output.as_output(),+ "-emit-object",+ "-enable-batch-mode",+ "-driver-batch-size-limit",+ str(INCREMENTAL_SWIFT_COMPILE_BATCH_SIZE),+ "-j",+ str(INCREMENTAL_SWIFT_COMPILE_MAX_NUM_THREADS),+ )++ category = "modularization_dependency_graph_compile"++ output_file_map, output_objects, output_modularization_dependency_graph_shards = get_modularization_dependency_graph_output_map(ctx, srcs)+ for object in output_objects:+ cmd.add(cmd_args(hidden = object.as_output()))++ for shard in output_modularization_dependency_graph_shards:+ cmd.add(cmd_args(hidden = shard.as_output()))++ _compile_with_argsfile(+ ctx = ctx,+ category = category,+ extension = SWIFT_EXTENSION,+ shared_flags = shared_flags,+ srcs = srcs,+ additional_flags = cmd,+ toolchain = toolchain,+ num_threads = INCREMENTAL_SWIFT_COMPILE_MAX_NUM_THREADS,+ output_file_map = output_file_map,+ skip_incremental_outputs = False,+ objects = output_objects,+ )+ return modularization_dependecy_graph_output++def _compile_index_store(ctx: AnalysisContext, toolchain: SwiftToolchainInfo, shared_flags: cmd_args, srcs: list[CxxSrcWithFlags]) -> Artifact:+ module_name = get_module_name(ctx)++ # Create a directory where we can write .o files and ignore them.+ #+ # In index store directories, the hash used in the unit file name is derived from+ # the output path. E.g. if the output path is dir1/Foo.o, our unit file is+ # Foo.swift-ABC123. If the output path changes to dir2/Foo.o, our unit file is now+ # Foo.swift-DEF456.+ #+ # See this part of the index-while-building talk from the 2017 LLVM developer+ # meeting: https://www.youtube.com/watch?v=jGJhnIT-D2M&t=279s+ #+ # swiftc also requires that all output paths are unique, so we can't just use+ # /dev/null as the output path.+ #+ # Buck requires that all declared outputs are created when the rule succeeds, but we+ # want to create an index store even if there are errors in the source files.+ #+ # We solve this by declaring a directory as the buck output, and telling swiftc that+ # we want all our .o files there. Our target will then succeed whether or not we+ # create a .o file.+ objects_dir = ctx.actions.declare_output("__indexstore__/objects", dir = True, has_content_based_path = False)++ sh_cmd = cmd_args([+ "mkdir",+ "-p",+ objects_dir.as_output(),+ ])+ ctx.actions.run(+ sh_cmd,+ category = "swift_compilation_database",+ )++ # We need an output file map with index-unit-output-path entries to be able+ # to index all of the srcs in a single pass.+ output_file_map = {}+ for src in srcs:+ output_file_map[src.file] = {+ "diagnostics": cmd_args(objects_dir, format = "{}/" + src.file.basename + ".dia", delimiter = ""),+ # The output here is only used for the identifier of the index unit file+ "index-unit-output-path": src.file,+ "object": cmd_args(objects_dir, format = "{}/" + src.file.basename + ".o", delimiter = ""),+ }++ index_store_output = ctx.actions.declare_output("__indexstore__/swift_{}".format(module_name), dir = True, has_content_based_path = False)+ additional_flags = cmd_args(+ ([] if _INDEX_SYSTEM_MODULES else ["-index-ignore-system-modules"])+ + [+ "-index-store-path",+ index_store_output.as_output(),+ "-c",+ "-disable-batch-mode",+ "-Xwrapper",+ "-ignore-errors",+ ]+ )++ _compile_with_argsfile(+ ctx = ctx,+ category = "swift_index_compile",+ shared_flags = shared_flags,+ srcs = srcs,+ additional_flags = additional_flags,+ toolchain = toolchain,+ cacheable = True,+ # Incremental builds are never cached, but caching the index store build is very useful+ # when building all the transitive index stores (e.g. during the Glean indexer).+ incremental_build_allowed = False,+ output_file_map = output_file_map,+ )++ return index_store_output++def _compile_with_argsfile(+ ctx: AnalysisContext,+ category: str,+ shared_flags: cmd_args,+ srcs: list[CxxSrcWithFlags],+ additional_flags: cmd_args,+ toolchain: SwiftToolchainInfo,+ extension: str | None = None,+ num_threads: int = 1,+ dep_files: dict[str, ArtifactTag] = {},+ output_file_map: dict = {},+ cacheable = True,+ skip_incremental_outputs = False,+ supports_serialized_errors = True,+ incremental_build_allowed = True,+ objects = [],+ incremental_artifacts: IncrementalCompilationInput | None = None,+ artifact_tag: ArtifactTag | None = None,+) -> (CompileArgsfiles | None, Artifact | None):+ build_swift_incrementally = incremental_build_allowed and should_build_swift_incrementally(ctx)++ explicit_modules_enabled = uses_explicit_modules(ctx)++ # The main compilation actions add a category suffix when explicit modules+ # are enabled for debugging and telemetry reasons. This is very important,+ # so do not be tempted to remove the suffixing.+ if extension and explicit_modules_enabled:+ category += EXPLICIT_MODULES_CATEGORY_SUFFIX++ allow_cache_upload, action_execution_attributes = _get_action_properties(toolchain, cacheable, build_swift_incrementally, explicit_modules_enabled)++ argsfile, output_file_map = compile_with_argsfile(+ ctx = ctx,+ category = category,+ shared_flags = shared_flags,+ srcs = srcs,+ additional_flags = additional_flags,+ toolchain = toolchain,+ num_threads = num_threads,+ dep_files = dep_files,+ output_file_map = output_file_map,+ allow_cache_upload = allow_cache_upload,+ local_only = action_execution_attributes.local_only,+ prefer_local = action_execution_attributes.prefer_local,+ # We need to preserve the action outputs for incremental compilation.+ no_outputs_cleanup = build_swift_incrementally,+ # Skip incremental outputs requires an empty output file map, so is not+ # compatible with serialized diagnostics.+ supports_serialized_errors = (not skip_incremental_outputs) and supports_serialized_errors,+ skip_incremental_outputs = skip_incremental_outputs,+ objects = objects,+ incremental_artifacts = incremental_artifacts,+ artifact_tag = artifact_tag,+ incremental_remote_outputs = get_incremental_remote_outputs_enabled(ctx) and build_swift_incrementally,+ )++ if extension:+ # Swift correctly handles relative paths and we can utilize the relative argsfile for Xcode.+ return CompileArgsfiles(relative = {extension: argsfile}, xcode = {extension: argsfile}), output_file_map+ else:+ return None, output_file_map++def _get_action_properties(+ toolchain: SwiftToolchainInfo, cacheable: bool, build_swift_incrementally: bool, explicit_modules_enabled: bool+) -> (bool, ActionExecutionAttributes): # (allow_cache_upload, ActionExecutionAttributes)+ # By default, we allow Buck and any command line arguments to determine execution preference.+ # However, based upon certain functionality or execution environments, we modify these+ # default properties for cacheability and performance.++ # If we prefer to execute locally (e.g., for perf reasons), ensure we upload to the cache so+ # that CI builds populate caches used by developer machines.+ allow_cache_upload = True++ local_only = False++ # Swift compilation on RE without explicit modules is impractically expensive because there's+ # no shared module cache across different libraries.+ prefer_local = not explicit_modules_enabled++ if build_swift_incrementally:+ # When Swift code is built incrementally, the swift-driver embeds absolute paths into the+ # artifacts without relative resource dir support. In this case we can only build locally.+ if not toolchain.supports_relative_resource_dir:+ allow_cache_upload = False+ local_only = True+ prefer_local = False++ if not cacheable:+ allow_cache_upload = False+ local_only = True+ prefer_local = False++ return (allow_cache_upload, ActionExecutionAttributes(prefer_local = prefer_local, local_only = local_only))++def _get_serialize_debugging_options(ctx: AnalysisContext, uses_explicit_modules: bool):+ if ctx.attrs.serialize_debugging_options == False:+ return False++ if uses_explicit_modules:+ # If the toolchain supports explicit modules we can+ # enable, regardless if this is a mixed library or not+ return get_swift_toolchain_info(ctx).supports_explicit_module_debug_serialization++ # Serialized debugging options contain absolute paths until+ # https://github.com/swiftlang/swift/pull/84112+ return False++def _get_shared_flags(+ ctx: AnalysisContext,+ deps_providers: list,+ parse_as_library: bool,+ public_module: SwiftCompiledModuleInfo | None,+ module_name: str,+ public_modulemap_pp_info: CPreprocessor | None,+ extra_search_paths_flags: list[ArgLike],+ inputs_tag: ArtifactTag,+ is_macro: bool,+) -> (cmd_args, Artifact | None):+ toolchain = get_swift_toolchain_info(ctx)+ cmd = cmd_args()++ if not toolchain.supports_relative_resource_dir:+ # Setting this to empty will get the driver to make all paths absolute when+ # passed to the frontend. We later debug prefix these to ensure relative paths+ # in the debug info.+ cmd.add(["-working-directory="])++ cmd.add(get_sdk_flags(ctx))+ cmd.add(_get_target_flags(ctx))+ cmd.add(+ "-swift-version",+ ctx.attrs.swift_version,+ # Always use color, consistent with clang.+ "-color-diagnostics",+ # Unset the working directory in the debug information.+ "-file-compilation-dir",+ ".",+ "-module-name",+ module_name,+ "-Xfrontend",+ "-enable-cross-import-overlays",+ "-Xfrontend",+ "-disable-cxx-interop-requirement-at-import",+ "-Xfrontend",+ "-emit-clang-header-nonmodular-includes",+ # RE actions are run in a sandbox, which will fail to run macros as+ # you cannot nest sandbox actions.+ # https://github.com/swiftlang/swift/pull/70079+ "-disable-sandbox",+ )++ if parse_as_library:+ cmd.add([+ "-parse-as-library",+ ])++ if ctx.attrs.swift_package_name != None:+ cmd.add([+ "-package-name",+ ctx.attrs.swift_package_name,+ ])++ explicit_modules_enabled = uses_explicit_modules(ctx)+ if explicit_modules_enabled:+ cmd.add([+ "-Xcc",+ "-Xclang",+ "-Xcc",+ # We set -fmodule-file-home-is-cwd as this is used to correctly+ # set the working directory of modules when generating debug info.+ "-fmodule-file-home-is-cwd",+ "-Xcc",+ "-Xclang",+ "-Xcc",+ # This is the default for compilation, but not in sourcekitd.+ # Set it explicitly here so that indexing will not fail with+ # invalid module format errors.+ "-fmodule-format=obj",+ ])+ cmd.add(get_disable_pch_validation_flags())+ else:+ # Clang module breadcrumbs include module hashes and temporary paths+ # and need to be excluded for deterministic build output.+ cmd.add("-Xfrontend", "-no-clang-module-breadcrumbs")++ if toolchain.resource_dir:+ cmd.add([+ "-resource-dir",+ toolchain.resource_dir,+ ])++ if ctx.attrs.enable_cxx_interop:+ cmd.add(["-cxx-interoperability-mode=default"])++ if _get_serialize_debugging_options(ctx, explicit_modules_enabled):+ cmd.add([+ "-Xfrontend",+ "-serialize-debugging-options",+ "-Xfrontend",+ "-prefix-serialized-debugging-options",+ ])+ else:+ cmd.add([+ "-Xfrontend",+ "-no-serialize-debugging-options",+ ])++ upcoming_features = toolchain.swift_upcoming_features[ctx.attrs.swift_version]+ experimental_features = toolchain.swift_experimental_features[ctx.attrs.swift_version]++ for feature in upcoming_features:+ cmd.add([+ "-Xfrontend",+ "-enable-upcoming-feature",+ "-Xfrontend",+ feature,+ ])++ for feature in experimental_features:+ cmd.add([+ "-Xfrontend",+ "-enable-experimental-feature",+ "-Xfrontend",+ feature,+ ])++ if ctx.attrs._swift_enable_testing:+ cmd.add("-enable-testing")++ if getattr(ctx.attrs, "application_extension", False):+ cmd.add("-application-extension")++ # Only apple_library and apple_test has swift_macro_deps+ swift_macros = getattr(ctx.attrs, "swift_macro_deps", [])+ if swift_macros:+ for m in ctx.plugins[SwiftMacroPlugin]:+ macro_artifact = m[DefaultInfo].default_outputs[0]+ cmd.add([+ "-load-plugin-executable",+ cmd_args(inputs_tag.tag_artifacts(macro_artifact), format = "{}#" + macro_artifact.basename),+ ])++ pcm_deps_tset = get_compiled_pcm_deps_tset(ctx, deps_providers)++ # If Swift Explicit Modules are enabled, a few things must be provided to a compilation job:+ # 1. Direct and transitive SDK deps from `sdk_modules` attribute.+ # 2. Direct and transitive user-defined deps.+ # 3. Transitive SDK deps of user-defined deps.+ # (This is the case, when a user-defined dep exports a type from SDK module,+ # thus such SDK module should be implicitly visible to consumers of that custom dep)+ swift_module_map_artifact = None+ if uses_explicit_modules(ctx):+ sdk_clang_deps_tset = get_compiled_sdk_clang_deps_tset(ctx, deps_providers)+ sdk_swift_deps_tset = get_compiled_sdk_swift_deps_tset(ctx, deps_providers)+ swift_module_map_artifact = _add_swift_module_map_args(+ ctx = ctx,+ sdk_swiftmodule_deps_tset = sdk_swift_deps_tset,+ pcm_deps_tset = pcm_deps_tset,+ sdk_deps_tset = sdk_clang_deps_tset,+ inputs_tag = inputs_tag,+ cmd = cmd,+ is_macro = is_macro,+ )++ _add_clang_deps_flags(ctx, pcm_deps_tset, cmd, inputs_tag)+ _add_swift_deps_flags(ctx, cmd, is_macro)++ # Add flags for importing the ObjC part of this library+ _add_mixed_library_flags_to_cmd(+ ctx,+ cmd,+ public_module,+ public_modulemap_pp_info,+ )++ # Add toolchain and target flags last to allow for overriding defaults+ cmd.add(toolchain.compiler_flags)+ cmd.add(ctx.attrs.swift_compiler_flags)+ cmd.add(extra_search_paths_flags)++ return (cmd, swift_module_map_artifact)++def _add_swift_module_map_args(+ ctx: AnalysisContext,+ sdk_swiftmodule_deps_tset: SwiftCompiledModuleTset,+ pcm_deps_tset: SwiftCompiledModuleTset,+ sdk_deps_tset: SwiftCompiledModuleTset,+ inputs_tag: ArtifactTag,+ cmd: cmd_args,+ is_macro: bool,+) -> Artifact:+ module_name = get_module_name(ctx)+ sdk_swiftmodule_deps_tset = [sdk_swiftmodule_deps_tset] if sdk_swiftmodule_deps_tset else []+ all_deps_tset = ctx.actions.tset(+ SwiftCompiledModuleTset,+ children = _get_swift_paths_tsets(is_macro, ctx.attrs.deps + getattr(ctx.attrs, "exported_deps", []))+ + [pcm_deps_tset, sdk_deps_tset]+ + sdk_swiftmodule_deps_tset,+ )+ swift_module_map_artifact, swift_module_map_args = write_swift_module_map_with_deps(+ ctx,+ module_name,+ all_deps_tset,+ )+ cmd.add([+ "-Xfrontend",+ "-explicit-swift-module-map-file",+ "-Xfrontend",+ inputs_tag.tag_artifacts(swift_module_map_args),+ ])+ return swift_module_map_artifact++def _add_swift_deps_flags(ctx: AnalysisContext, cmd: cmd_args, is_macro: bool):+ if uses_explicit_modules(ctx):+ cmd.add([+ "-Xcc",+ "-fno-implicit-modules",+ "-Xcc",+ "-fno-implicit-module-maps",+ "-Xfrontend",+ "-disable-implicit-swift-modules",+ ])+ else:+ depset = ctx.actions.tset(SwiftCompiledModuleTset, children = _get_swift_paths_tsets(is_macro, ctx.attrs.deps + getattr(ctx.attrs, "exported_deps", [])))+ cmd.add(depset.project_as_args("module_search_path"))++ implicit_search_path_tset = get_implicit_framework_search_path_providers(+ ctx,+ None,+ ctx.attrs.deps + getattr(ctx.attrs, "exported_deps", []),+ )+ cmd.add(implicit_search_path_tset.project_as_args("swift_framework_implicit_search_paths_args"))++def _add_clang_deps_flags(ctx: AnalysisContext, pcm_deps_tset: SwiftCompiledModuleTset, cmd: cmd_args, inputs_tag: ArtifactTag) -> None:+ if uses_explicit_modules(ctx):+ clang_flags = pcm_deps_tset.project_as_args("clang_importer_flags")+ cmd.add(inputs_tag.tag_artifacts(clang_flags))+ else:+ inherited_preprocessor_infos = cxx_inherited_preprocessor_infos(ctx.attrs.deps + getattr(ctx.attrs, "exported_deps", []))+ preprocessors = cxx_merge_cpreprocessors(ctx.actions, [], inherited_preprocessor_infos)+ cmd.add(cmd_args(preprocessors.set.project_as_args("args"), prepend = "-Xcc"))+ cmd.add(cmd_args(preprocessors.set.project_as_args("modular_args"), prepend = "-Xcc"))++def _add_mixed_library_flags_to_cmd(+ ctx: AnalysisContext, cmd: cmd_args, underlying_module: SwiftCompiledModuleInfo | None, public_modulemap_pp_info: CPreprocessor | None+) -> None:+ if uses_explicit_modules(ctx):+ if underlying_module:+ cmd.add(underlying_module.clang_importer_args)+ cmd.add(clang_module_file_args(underlying_module))+ cmd.add("-import-underlying-module")+ return++ for objc_modulemap_pp_info in filter(None, [public_modulemap_pp_info]):+ # TODO(T99100029): We cannot use VFS overlays to mask this import from+ # the debugger as they require absolute paths. Instead we will enforce+ # that mixed libraries do not have serialized debugging info and rely on+ # rdeps to serialize the correct paths.+ for arg in objc_modulemap_pp_info.args.args:+ cmd.add("-Xcc")+ cmd.add(arg)++ for arg in objc_modulemap_pp_info.modular_args:+ cmd.add("-Xcc")+ cmd.add(arg)++ if public_modulemap_pp_info:+ cmd.add("-import-underlying-module")++def _get_swift_dependency_info(is_macro: bool, deps: list[Dependency]) -> list[SwiftDependencyInfo]:+ ret = []+ for d in deps:+ if SwiftDependencyInfo in d:+ if d[SwiftDependencyInfo].is_macro != is_macro:+ fail(+ "Cannot have a {} dep in a {} target".format(+ "macro" if d[SwiftDependencyInfo].is_macro else "non-macro",+ "macro" if is_macro else "non-macro",+ )+ )+ ret.append(d[SwiftDependencyInfo])++ return ret++def _get_swift_paths_tsets(is_macro: bool, deps: list[Dependency]) -> list[SwiftCompiledModuleTset]:+ return [d.exported_swiftmodules for d in _get_swift_dependency_info(is_macro, deps)]++def get_external_debug_info_tsets(is_macro: bool, deps: list[Dependency]) -> list[ArtifactTSet]:+ return [d.debug_info_tset for d in _get_swift_dependency_info(is_macro, deps)]++def get_external_swiftmodule_change_analysis_tsets(is_macro: bool, deps: list[Dependency]) -> list[ArtifactTSet]:+ return [d.swiftmodule_change_analysis_tset for d in _get_swift_dependency_info(is_macro, deps)]++def get_external_swift_ast_dump_tsets(is_macro: bool, deps: list[Dependency]) -> list[ArtifactTSet]:+ return [d.swift_ast_dump_tset for d in _get_swift_dependency_info(is_macro, deps)]++def get_swift_pcm_uncompile_info(+ ctx: AnalysisContext, propagated_exported_preprocessor_info: [CPreprocessorInfo, None], exported_pre: [CPreprocessor, None]+) -> [SwiftPCMUncompiledInfo, None]:+ swift_toolchain = get_swift_toolchain_info(ctx)++ if is_sdk_modules_provided(swift_toolchain):+ clang_importer_args = cmd_args()+ if propagated_exported_preprocessor_info:+ # We need to include exported preprocessor from exported_deps to+ # handle misconfigured targets that have non-modular exported_deps+ clang_importer_args.add(cmd_args(propagated_exported_preprocessor_info.set.project_as_args("args"), prepend = "-Xcc"))++ exported_clang_importer_args = cmd_args()+ if exported_pre:+ if supports_modulemaps_with_hmaps(ctx):+ # The cxx preprocessor info will not include the modular args,+ # so include the required modulemap flags for this target only.+ # The deps modular args will be included via projections on the+ # deps SwiftCompiledModuleTsets.+ clang_importer_args.add(cmd_args(exported_pre.modular_args, prepend = "-Xcc"))+ else:+ # We need special handling for our own exported_pre, which+ # contains the header search path flags for the modules header+ # symlink tree. This needs to be propagated to rdeps.+ exported_clang_importer_args.add(cmd_args(exported_pre.modular_args, prepend = "-Xcc"))++ return SwiftPCMUncompiledInfo(+ clang_importer_args = clang_importer_args,+ exported_clang_importer_args = exported_clang_importer_args,+ exported_deps = _exported_deps(ctx),+ is_transient = not ctx.attrs.modular or not exported_pre,+ modulemap_artifact = exported_pre.modulemap_artifact if exported_pre else None,+ name = get_module_name(ctx),+ uncompiled_sdk_modules = ctx.attrs.sdk_modules,+ )+ return None++def create_swift_dependency_info(+ ctx: AnalysisContext,+ deps,+ deps_providers: list,+ compiled_info: [SwiftCompiledModuleInfo, None],+ debug_info_tset: ArtifactTSet,+ swiftmodule_change_analysis_tset: ArtifactTSet,+ swift_ast_dump_tset: ArtifactTSet,+ is_macro: bool,+):+ # We pass through the SDK swiftmodules here to match Buck 1 behaviour. This is+ # pretty loose, but it matches Buck 1 behavior so cannot be improved until+ # migration is complete.+ transitive_swiftmodule_deps = _get_swift_paths_tsets(is_macro, deps) + [get_compiled_sdk_swift_deps_tset(ctx, deps_providers)]++ if compiled_info:+ exported_swiftmodules = ctx.actions.tset(SwiftCompiledModuleTset, value = compiled_info, children = transitive_swiftmodule_deps)+ else:+ exported_swiftmodules = ctx.actions.tset(SwiftCompiledModuleTset, children = transitive_swiftmodule_deps)++ return SwiftDependencyInfo(+ debug_info_tset = debug_info_tset,+ exported_swiftmodules = exported_swiftmodules,+ # prebuilt_apple_framework do not have exported_headers, we can exclude+ # them from validation safely.+ has_exported_headers = len(getattr(ctx.attrs, "exported_headers", [])) > 0,+ is_modular = ctx.attrs.modular,+ is_macro = is_macro,+ swift_ast_dump_tset = swift_ast_dump_tset,+ swiftmodule_change_analysis_tset = swiftmodule_change_analysis_tset,+ )++def get_swift_dependency_info(+ ctx: AnalysisContext,+ output_module: Artifact | None,+ deps_providers: list,+ is_macro: bool,+ swift_ast_dump_artifacts: list[Artifact] = [],+) -> SwiftDependencyInfo:+ exported_deps = _exported_deps(ctx)++ if output_module:+ compiled_info = SwiftCompiledModuleInfo(+ is_framework = False,+ is_sdk_module = False,+ is_swiftmodule = True,+ module_name = get_module_name(ctx),+ output_artifact = output_module,+ )+ else:+ compiled_info = None++ all_deps = ctx.attrs.deps + getattr(ctx.attrs, "exported_deps", [])++ debug_info_tset = make_artifact_tset(+ actions = ctx.actions,+ artifacts = filter(None, [output_module]),+ children = get_external_debug_info_tsets(is_macro, all_deps),+ label = ctx.label,+ tags = [ArtifactInfoTag("swift_debug_info")],+ )++ # Deliberately broader than `all_deps` above (also covers toolchain+ # `default_deps` and `deps_query`, via `cxx_attr_deps`/`cxx_attr_exported_deps`):+ # this tset is new, so widening it to match the rest of the codebase's+ # convention has no existing behavior to preserve. `debug_info_tset` and+ # `swift_ast_dump_tset` predate this and keep the narrower `all_deps` to+ # avoid changing their already-shipped output.+ swiftmodule_change_analysis_deps = cxx_attr_deps(ctx) + cxx_attr_exported_deps(ctx)++ swiftmodule_change_analysis_tset = make_artifact_tset(+ actions = ctx.actions,+ artifacts = filter(None, [output_module]),+ children = get_external_swiftmodule_change_analysis_tsets(is_macro, swiftmodule_change_analysis_deps),+ label = ctx.label,+ )++ swift_ast_dump_tset = make_artifact_tset(+ actions = ctx.actions,+ artifacts = swift_ast_dump_artifacts,+ children = get_external_swift_ast_dump_tsets(is_macro, all_deps),+ label = ctx.label,+ )++ return create_swift_dependency_info(+ ctx,+ exported_deps,+ deps_providers,+ compiled_info,+ debug_info_tset,+ swiftmodule_change_analysis_tset,+ swift_ast_dump_tset,+ is_macro,+ )++def get_swiftmodule_linkable(swift_compile_output: [SwiftCompilationOutput, None]) -> [SwiftmoduleLinkable, None]:+ return SwiftmoduleLinkable(swiftmodules = swift_compile_output.swift_debug_info) if swift_compile_output else None++def extract_swiftmodule_linkables(link_infos: [list[LinkInfo], None]) -> list[SwiftmoduleLinkable]:+ linkables = []+ for info in link_infos:+ for linkable in info.linkables:+ if isinstance(linkable, SwiftmoduleLinkable):+ linkables.append(linkable)++ return linkables++def get_swiftmodule_linker_flags(ctx: AnalysisContext, swiftmodule_linkable: [SwiftmoduleLinkable, None]) -> cmd_args:+ if swiftmodule_linkable:+ tset = swiftmodule_linkable.swiftmodules+ artifacts = project_artifacts(+ actions = ctx.actions,+ tsets = tset,+ )+ return cmd_args([cmd_args(swiftmodule, format = "-Wl,-add_ast_path,{}") for swiftmodule in artifacts])+ return cmd_args()++def _get_xctest_swiftmodule_search_path(ctx: AnalysisContext) -> cmd_args:+ # With explicit modules we don't need to search at all.+ if uses_explicit_modules(ctx):+ return cmd_args()++ for fw in ctx.attrs.frameworks:+ if fw.endswith("XCTest.framework"):+ toolchain = ctx.attrs._apple_toolchain[AppleToolchainInfo]+ return cmd_args(toolchain.platform_path, format = "-I{}/Developer/usr/lib")++ return cmd_args()++def get_swift_debug_infos(+ ctx: AnalysisContext, swift_dependency_info: [SwiftDependencyInfo, None], swift_output: [SwiftCompilationOutput, None]+) -> SwiftDebugInfo:+ # When determining the debug info for shared libraries, if the shared library is a link group, we rely on the link group links to+ # obtain the debug info for linked libraries and only need to provide any swift debug info for this library itself. Otherwise+ # if linking standard shared, we need to obtain the transitive debug info.+ if get_link_group(ctx):+ swift_shared_debug_info = []+ else:+ swift_shared_debug_info = _get_swift_shared_debug_info(swift_dependency_info) if swift_dependency_info else []++ clang_debug_info = [swift_output.clang_debug_info] if swift_output else []+ swift_debug_info = [swift_output.swift_debug_info] if swift_output else []++ return SwiftDebugInfo(+ static = clang_debug_info + swift_debug_info,+ shared = swift_shared_debug_info + clang_debug_info + swift_debug_info,+ )++def _get_swift_shared_debug_info(swift_dependency_info: SwiftDependencyInfo) -> list[ArtifactTSet]:+ return [swift_dependency_info.debug_info_tset] if swift_dependency_info.debug_info_tset else []++def _get_project_root_file(ctx) -> Artifact:+ content = cmd_args(ctx.label.project_root)+ return ctx.actions.write("project_root_file", content, absolute = True, has_content_based_path = False)++def _create_compilation_database(ctx: AnalysisContext, srcs: list[CxxSrcWithFlags], argfile: CompileArgsfile) -> SwiftCompilationDatabase:+ module_name = get_module_name(ctx)++ swift_toolchain = get_swift_toolchain_info(ctx)+ mk_comp_db = swift_toolchain.mk_swift_comp_db++ identifier = module_name + ".swift_comp_db.json"+ cdb_artifact = ctx.actions.declare_output(identifier, has_content_based_path = False)++ srcs_args = cmd_args([s.file for s in srcs])++ cmd = cmd_args(mk_comp_db)+ cmd.add(cmd_args(cdb_artifact.as_output(), format = "--output={}"))+ cmd.add(cmd_args(_get_project_root_file(ctx), format = "--project-root-file={}"))+ cmd.add("--files", srcs_args)++ cmd.add("--")++ cmd_form_and_srcs = cmd_args(argfile.cmd_form, srcs_args)+ cmd.add(cmd_form_and_srcs)++ ctx.actions.run(+ cmd,+ category = "swift_compilation_database",+ identifier = identifier,+ error_handler = apple_build_error_handler,+ )++ return SwiftCompilationDatabase(db = cdb_artifact, other_outputs = cmd_form_and_srcs)++def _create_objc_swift_interface(ctx: AnalysisContext, shared_flags: cmd_args, module_name: str) -> DefaultInfo:+ """Generates the Swift interface representation of a modular Obj-C(++) target."""+ swift_toolchain = get_swift_toolchain_info(ctx)+ swift_ide_test_tool = swift_toolchain.swift_ide_test_tool+ if not swift_ide_test_tool:+ return DefaultInfo()+ mk_swift_interface = swift_toolchain.mk_swift_interface+ uses_content_based_paths = get_uses_content_based_paths(ctx)++ identifier = module_name + ".swift_interface"++ argsfile, _ = ctx.actions.write(+ identifier + "_argsfile",+ shared_flags,+ allow_args = True,+ has_content_based_path = uses_content_based_paths,+ )+ interface_artifact = ctx.actions.declare_output(identifier, has_content_based_path = uses_content_based_paths)++ mk_swift_args = cmd_args(+ mk_swift_interface,+ "--swift-ide-test-tool",+ swift_ide_test_tool,+ "--module",+ module_name,+ "--out",+ interface_artifact.as_output(),+ "--",+ cmd_args(cmd_args(argsfile, format = "@{}", delimiter = ""), hidden = [shared_flags]),+ )++ ctx.actions.run(+ mk_swift_args,+ category = "mk_swift_interface",+ identifier = identifier,+ error_handler = apple_build_error_handler,+ )++ return DefaultInfo(+ default_output = interface_artifact,+ other_outputs = [+ argsfile,+ ],+ )++def _exported_deps(ctx) -> list[Dependency]:+ if ctx.attrs.reexport_all_header_dependencies:+ return getattr(ctx.attrs, "exported_deps", []) + ctx.attrs.deps+ else:+ return getattr(ctx.attrs, "exported_deps", [])++def _should_compile_with_evolution(ctx) -> bool:+ if ctx.attrs.enable_library_evolution != None:+ return ctx.attrs.enable_library_evolution+ return ctx.attrs._enable_library_evolution
@@ -0,0 +1,60 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactInfoTag",+ "ArtifactTSet",+ "make_artifact_tset",+)+load(":swift_pcm_compilation_types.bzl", "WrappedSwiftPCMCompiledInfo")+load(":swift_toolchain.bzl", "get_swift_toolchain_info")+load(+ ":swift_toolchain_types.bzl",+ "WrappedSdkCompiledModuleInfo",+)++def extract_and_merge_swift_debug_infos(ctx: AnalysisContext, compiled_pcm_deps_providers, artifacts: list[Artifact] = []) -> ArtifactTSet:+ provide_swift_debug_info = get_swift_toolchain_info(ctx).provide_swift_debug_info+ swift_debug_tsets = (+ [+ d[WrappedSdkCompiledModuleInfo].swift_debug_info+ for d in compiled_pcm_deps_providers+ if WrappedSdkCompiledModuleInfo in d and d[WrappedSdkCompiledModuleInfo].swift_debug_info != None+ ]+ if provide_swift_debug_info+ else []+ )++ return make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ artifacts = artifacts if provide_swift_debug_info else [],+ children = swift_debug_tsets,+ tags = [ArtifactInfoTag("swift_debug_info")],+ )++def extract_and_merge_clang_debug_infos(ctx: AnalysisContext, compiled_pcm_deps_providers, pcms_and_modulemaps: list[Artifact] = []) -> ArtifactTSet:+ clang_debug_tsets = []+ for d in compiled_pcm_deps_providers:+ if WrappedSdkCompiledModuleInfo in d and d[WrappedSdkCompiledModuleInfo].clang_debug_info != None:+ clang_debug_tsets.append(d[WrappedSdkCompiledModuleInfo].clang_debug_info)+ if WrappedSwiftPCMCompiledInfo in d:+ clang_debug_tsets.append(d[WrappedSwiftPCMCompiledInfo].clang_debug_info)++ swift_toolchain = get_swift_toolchain_info(ctx)+ swift_toolchain_debug_info_tsets = [swift_toolchain.sdk_debug_info] if swift_toolchain.sdk_debug_info else []++ return make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ # Even with explicit modules, lldb requires the presence of the modulemaps.+ artifacts = pcms_and_modulemaps,+ children = clang_debug_tsets + swift_toolchain_debug_info_tsets,+ tags = [ArtifactInfoTag("swift_debug_info")],+ )
@@ -0,0 +1,298 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load("@prelude//apple:apple_error_handler.bzl", "apple_build_error_handler", "swift_error_deserializer", "swift_error_handler")+load("@prelude//apple/swift:apple_sdk_modules_utility.bzl", "is_sdk_modules_provided")+load("@prelude//cxx:argsfiles.bzl", "CompileArgsfile")+load("@prelude//cxx:cxx_sources.bzl", "CxxSrcWithFlags")+load(+ ":swift_incremental_support.bzl",+ "IncrementalCompilationInput", # @unused Used as a type+ "get_incremental_split_actions",+ "get_uses_content_based_paths",+ "should_build_swift_incrementally",+)+load(":swift_output_file_map.bzl", "add_output_file_map_flags", "add_serialized_diagnostics_output")+load(":swift_toolchain.bzl", "get_swift_toolchain_info")+load(":swift_toolchain_types.bzl", "SwiftToolchainInfo")+load(+ ":swift_types.bzl",+ "EXPLICIT_MODULES_CATEGORY_SUFFIX",+ "SWIFTMODULE_COMPILE_CATEGORY",+ "SWIFT_COMPILE_CATEGORY",+)++CompileWithArgsFileCmdOutput = record(+ cmd = field(cmd_args),+ argsfile = field(Artifact),+ argsfile_cmd_form = field(cmd_args),+ shell_quoted_args = field(cmd_args),+ error_outputs = field(list[OutputArtifact]),+ output_file_map_artifact = field(Artifact | None),+ error_deserializer = field(RunInfo | None),+)++ENFORCED_CATEGORIES = [+ SWIFTMODULE_COMPILE_CATEGORY + EXPLICIT_MODULES_CATEGORY_SUFFIX,+ SWIFTMODULE_COMPILE_CATEGORY,+ SWIFT_COMPILE_CATEGORY + EXPLICIT_MODULES_CATEGORY_SUFFIX,+ SWIFT_COMPILE_CATEGORY,+]++# def _get_should_expect_eligible_for_dedupe(ctx: AnalysisContext, category: str) -> bool:+# uses_content_based_paths = get_uses_content_based_paths(ctx)+# toolchain = get_swift_toolchain_info(ctx)+#+# expect_eligible_for_dedupe = toolchain.enforce_dedupe_eligibility and uses_content_based_paths and category in ENFORCED_CATEGORIES+#+# return expect_eligible_for_dedupe++def _is_swiftmodule_emit_category(category: str) -> bool:+ return "swiftmodule" in category++def _is_swiftmodule_or_pcm_category(category: str) -> bool:+ # Matches swiftmodule_compile[_with_explicit_mods] and every *pcm_compile+ # category (swift_pcm_compile, swift_underlying_pcm_compile,+ # swift_prebuilt_framework_pcm_compile).+ return _is_swiftmodule_emit_category(category) or "pcm_compile" in category++def _is_swift_object_category(category: str) -> bool:+ # Bulk Swift object compiles (not swiftmodule/pcm).+ return category in (SWIFT_COMPILE_CATEGORY, SWIFT_COMPILE_CATEGORY + EXPLICIT_MODULES_CATEGORY_SUFFIX)++def _low_pass_filter_for_category(category: str, prioritized: bool) -> bool:+ # Disable low-pass gating for prioritized swiftmodule and PCM actions.+ if prioritized and _is_swiftmodule_or_pcm_category(category):+ return False+ return True++def _prefer_local_for_category(+ category: str,+ prioritized: bool,+ local_only: bool,+ prefer_local: bool,+) -> bool:+ if local_only:+ return prefer_local++ if prioritized and _is_swiftmodule_emit_category(category):+ return True+ return prefer_local++def compile_with_argsfile_cmd(+ ctx: AnalysisContext,+ category: str,+ shared_flags: cmd_args,+ srcs: list[CxxSrcWithFlags],+ additional_flags: cmd_args,+ toolchain: SwiftToolchainInfo,+ output_file_map: dict,+ supports_output_file_map: bool,+ supports_serialized_errors: bool,+ skip_incremental_outputs: bool,+ incremental_remote_outputs: bool,+ objects: list[Artifact],+ incremental_artifacts: IncrementalCompilationInput | None,+ artifact_tag: ArtifactTag | None,+) -> CompileWithArgsFileCmdOutput:+ object_outputs = [obj.as_output() for obj in objects]++ uses_content_based_paths = get_uses_content_based_paths(ctx)++ writable_incremental_args = []+ if incremental_artifacts:+ writable_incremental_args.extend(object_outputs)+ writable_incremental_args.extend([swiftdep.as_output() for swiftdep in incremental_artifacts.swiftdeps])+ writable_incremental_args.extend([depfile.as_output() for depfile in incremental_artifacts.depfiles])+ if incremental_artifacts.swiftdoc:+ writable_incremental_args.append(incremental_artifacts.swiftdoc.as_output())++ cmd = cmd_args(toolchain.compiler)+ cmd.add(additional_flags)++ # Hack to make output_file_map mutable when the default is used.+ output_file_map = output_file_map or {}++ # Assemble argsfile with compiler flags. We don't use `with_inputs` in the+ # write action as this strips tagged values and breaks dependency file+ # input tracking.+ shell_quoted_args = cmd_args(shared_flags, quote = "shell")++ if artifact_tag != None and uses_content_based_paths:+ # This is a little bit convoluted due to the way that content-based paths affect argfiles.+ # If an unused tagged input changes, we don't want to re-run the action, but if it is a+ # content-based input that is written to the argfile, then the argfile will also change+ # and that would cause a re-run.+ #+ # We therefore write the argfile twice: the "real" argfile, which is used in the action+ # and tagged as unused so that it is not used for dep-file comparison, and an argfile+ # that uses placeholders instead of content-based paths, which is not tagged for dep-files+ # and therefore causes a dep-file miss if it changes.+ argsfile, _ = ctx.actions.write(".{}_argsfile".format(category), shell_quoted_args, allow_args = True, has_content_based_path = uses_content_based_paths)+ placeholder_argsfile, _ = ctx.actions.write(+ ".{}_argsfile_placeholder".format(category),+ shell_quoted_args,+ allow_args = True,+ use_dep_files_placeholder_for_content_based_paths = True,+ has_content_based_path = uses_content_based_paths,+ )+ cmd.add(cmd_args(hidden = placeholder_argsfile))+ argsfile_cmd_form = cmd_args(artifact_tag.tag_artifacts(argsfile), format = "@{}", delimiter = "", hidden = shared_flags)+ else:+ argsfile, _ = ctx.actions.write(".{}_argsfile".format(category), shell_quoted_args, allow_args = True, has_content_based_path = uses_content_based_paths)+ argsfile_cmd_form = cmd_args(argsfile, format = "@{}", delimiter = "", hidden = shared_flags)+ cmd.add(argsfile_cmd_form)++ # Assemble argsfile with Swift source files.+ if srcs:+ swift_quoted_files = cmd_args([s.file for s in srcs], quote = "shell")++ # This path needs to be kept in sync with the _SWIFT_FILES_ARGSFILE+ # variable in swift_exec.py.+ swift_files, _ = ctx.actions.write(+ ".{}_swift_srcs".format(category), swift_quoted_files, allow_args = True, has_content_based_path = uses_content_based_paths+ )+ swift_files_cmd_form = cmd_args(swift_files, format = "@{}", delimiter = "", hidden = swift_quoted_files)+ cmd.add(swift_files_cmd_form)++ # If the toolchain supports serialized error output, add the output files+ # to deserialize the errors. This uses the output file map if supported,+ # otherwise will pass frontend flags.+ error_deserializer = swift_error_deserializer(ctx)+ error_outputs = []++ if supports_serialized_errors and error_deserializer:+ json_error_output = ctx.actions.declare_output("__diagnostics__/{}.json".format(category), has_content_based_path = uses_content_based_paths).as_output()+ error_outputs.append(json_error_output)+ is_incremental = incremental_artifacts != None+ add_serialized_diagnostics_output(+ ctx = ctx,+ output_file_map = output_file_map if supports_output_file_map else None,+ cmd = cmd,+ diagnostics_output = json_error_output,+ is_incremental = is_incremental,+ skip_incremental_outputs = skip_incremental_outputs,+ split_actions = get_incremental_split_actions(ctx),+ )+ cmd.add(+ "-Xwrapper",+ cmd_args(error_deserializer, format = "-serialized-diagnostics-to-json={}"),+ "-Xwrapper",+ cmd_args(json_error_output, format = "-json-error-output-path={}"),+ )+ if incremental_remote_outputs and should_build_swift_incrementally(ctx) and not skip_incremental_outputs:+ # Serialized diagnostics in Swift incremental mode will produce a+ # .dia output for each .o output. These need to be made writable.+ for obj in objects:+ name_without_extension, _ = paths.split_extension(obj.short_path)+ diag_output = ctx.actions.declare_output("{}.dia".format(name_without_extension), has_content_based_path = uses_content_based_paths)+ cmd.add(cmd_args(hidden = diag_output.as_output()))+ writable_incremental_args.append(diag_output.as_output())++ # If an output file map is provided, serialize it and add to the command.+ if output_file_map:+ if not supports_output_file_map:+ fail("Output file maps are not supported for {}".format(category))+ output_file_map_artifact = add_output_file_map_flags(ctx, output_file_map, cmd, category)+ else:+ output_file_map_artifact = None++ if writable_incremental_args and incremental_remote_outputs:+ cmd.add(["-Xwrapper", "--writable-incremental-paths"])+ for flag in writable_incremental_args:+ cmd.add(["-Xwrapper", flag])++ return CompileWithArgsFileCmdOutput(+ cmd = cmd,+ argsfile = argsfile,+ argsfile_cmd_form = argsfile_cmd_form,+ shell_quoted_args = shell_quoted_args,+ error_outputs = error_outputs,+ output_file_map_artifact = output_file_map_artifact,+ error_deserializer = error_deserializer,+ )++def compile_with_argsfile(+ ctx: AnalysisContext,+ category: str,+ shared_flags: cmd_args,+ srcs: list[CxxSrcWithFlags],+ additional_flags: cmd_args,+ toolchain: SwiftToolchainInfo,+ num_threads: int = 1,+ dep_files: dict[str, ArtifactTag] = {},+ output_file_map: dict = {},+ allow_cache_upload = False,+ local_only = False,+ prefer_local = False,+ no_outputs_cleanup = False,+ supports_output_file_map = True,+ supports_serialized_errors = True,+ skip_incremental_outputs = False,+ incremental_remote_outputs = False,+ objects = [],+ incremental_artifacts: IncrementalCompilationInput | None = None,+ artifact_tag: ArtifactTag | None = None,+) -> (CompileArgsfile, Artifact | None):+ cmd_output = compile_with_argsfile_cmd(+ ctx = ctx,+ category = category,+ shared_flags = shared_flags,+ srcs = srcs,+ additional_flags = additional_flags,+ toolchain = toolchain,+ output_file_map = output_file_map,+ supports_output_file_map = supports_output_file_map,+ supports_serialized_errors = supports_serialized_errors,+ skip_incremental_outputs = skip_incremental_outputs,+ incremental_remote_outputs = incremental_remote_outputs,+ objects = objects,+ incremental_artifacts = incremental_artifacts,+ artifact_tag = artifact_tag,+ )++ # TODO(xcshen): Re-enable when content-based paths for PCMs no longer+ # leak into .swiftmodule files, breaking @_implementationOnly blast radius.+ expect_eligible_for_dedupe = False # _get_should_expect_eligible_for_dedupe(ctx, category)+ if toolchain.prioritize_swift_critical_path and _is_swift_object_category(category):+ # Empirically tuned to preserve local capacity for prioritized swiftmodule+ # emits. Re-benchmark builds before changing.+ weight = num_threads * 4+ else:+ weight = num_threads+ ctx.actions.run(+ cmd_output.cmd,+ allow_cache_upload = allow_cache_upload,+ allow_dep_file_cache_upload = (len(dep_files) > 0),+ category = category,+ dep_files = dep_files,+ error_handler = swift_error_handler if cmd_output.error_deserializer else apple_build_error_handler,+ local_only = local_only,+ low_pass_filter = _low_pass_filter_for_category(category, toolchain.prioritize_swift_critical_path),+ no_outputs_cleanup = no_outputs_cleanup,+ incremental_remote_outputs = incremental_remote_outputs,+ outputs_for_error_handler = cmd_output.error_outputs,+ prefer_local = _prefer_local_for_category(category, toolchain.prioritize_swift_critical_path, local_only, prefer_local),+ unique_input_inodes = True,+ weight = weight,+ expect_eligible_for_dedupe = expect_eligible_for_dedupe,+ )++ argsfile = CompileArgsfile(+ file = cmd_output.argsfile,+ cmd_form = cmd_output.argsfile_cmd_form,+ args = cmd_output.shell_quoted_args,+ args_without_file_prefix_args = shared_flags,+ )++ return argsfile, cmd_output.output_file_map_artifact++def uses_explicit_modules(ctx: AnalysisContext) -> bool:+ swift_toolchain = get_swift_toolchain_info(ctx)+ return ctx.attrs.uses_explicit_modules and is_sdk_modules_provided(swift_toolchain)
@@ -0,0 +1,380 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftObjectFormat")+load("@prelude//apple/swift:swift_types.bzl", "SwiftCompilationModes")+load(+ "@prelude//cxx:cxx_sources.bzl",+ "CxxSrcWithFlags", # @unused Used as a type+)+load(":swift_toolchain.bzl", "get_swift_toolchain_info", "include_path_for_relative_module_map_paths")++_OutputFileMapData = record(+ artifacts = field(list[Artifact]),+ outputs = field(list[Artifact]),+ output_file_map = field(dict),+ swiftdeps = field(list[Artifact]),+ depfiles = field(list[Artifact]),+)++IncrementalCompilationOutput = record(+ artifacts = field(list[Artifact]),+ incremental_flags_cmd = field(cmd_args),+ num_threads = field(int),+ output_file_map = field(dict),+ skip_incremental_outputs = field(bool),+ incremental_remote_outputs = field(bool),+ swiftdeps = field(list[Artifact]),+ depfiles = field(list[Artifact]),+ swiftdoc = field(Artifact | None),+)++IncrementalCompilationInput = record(+ swiftdeps = field(list[Artifact]),+ depfiles = field(list[Artifact]),+ swiftdoc = field(Artifact | None),+)++SwiftmoduleIncrementalCompilationOutput = record(+ # Driver flags specific to the incremental swiftmodule action. The caller+ # composes this with the shared emit-module / emit-objc-header / include-+ # path / skip-function-bodies flags it built itself.+ incremental_flags_cmd = field(cmd_args),+ output_file_map = field(dict),+ skip_incremental_outputs = field(bool),+ swiftdeps = field(list[Artifact]),+ depfiles = field(list[Artifact]),+)++SwiftCompilationMode = enum(*SwiftCompilationModes)++# The maxmium number of threads, we don't use+# host_info to prevent cache misses across+# different hardware models.+INCREMENTAL_SWIFT_COMPILE_MAX_NUM_THREADS = 6++# This is the default, but specifying it explicitly+# is clearer.+INCREMENTAL_SWIFT_COMPILE_BATCH_SIZE = 25++def should_build_swift_incrementally(ctx: AnalysisContext) -> bool:+ toolchain = get_swift_toolchain_info(ctx)++ # Incremental builds are only supported when object files are generated.+ if toolchain.object_format != SwiftObjectFormat("object"):+ return False++ return SwiftCompilationMode(ctx.attrs.swift_compilation_mode) == SwiftCompilationMode("incremental")++def get_incremental_object_compilation_flags(+ ctx: AnalysisContext, srcs: list[CxxSrcWithFlags], output_swiftmodule: Artifact, output_swiftdoc: Artifact | None, output_header: Artifact+) -> IncrementalCompilationOutput:+ output_file_map_data = _get_output_file_map(ctx, srcs)+ return _get_incremental_compilation_flags_and_objects(+ ctx,+ output_file_map_data,+ output_swiftmodule,+ output_swiftdoc,+ output_header,+ len(srcs),+ )++def get_incremental_swiftmodule_compilation_flags(ctx: AnalysisContext, srcs: list[CxxSrcWithFlags]) -> SwiftmoduleIncrementalCompilationOutput:+ """Returns the incremental-driver-only flags + per-target incremental+ state (output file map, swiftdeps) for the incremental swiftmodule+ action. The shared emit-module / emit-objc-header / include-path /+ skip-function-bodies flags are intentionally NOT included here — the+ caller (\`_compile_swiftmodule\`) builds them once and shares them with+ the WMO path.+ """+ output_file_map_data = _get_swiftmodule_output_file_map(ctx, srcs)++ # The emit-module-separately job is a single driver task, so we don't+ # pass `-j` or `-driver-batch-size-limit` — the driver picks defaults.+ cmd = cmd_args(+ [+ "-enable-batch-mode",+ "-enable-incremental-imports",+ "-experimental-emit-module-separately",+ "-incremental",+ ],+ hidden = [output.as_output() for output in output_file_map_data.outputs],+ )++ skip_incremental_outputs = _get_skip_swift_incremental_outputs(ctx)+ uses_content_based_paths = get_uses_content_based_paths(ctx)+ if get_swift_incremental_logging_enabled(ctx):+ cmd.add([+ "-driver-show-incremental",+ "-driver-show-job-lifecycle",+ ])++ if skip_incremental_outputs:+ # When skipping incremental outputs, we write the contents of the+ # output_file_map in the swift wrapper and need to ensure this is+ # an output file (vs being an input in normal cases)+ output_map_artifact = ctx.actions.declare_output("__swift_module_incremental__/output_file_map.json", has_content_based_path = uses_content_based_paths)+ cmd.add(+ "-Xwrapper",+ "-skip-incremental-outputs",+ "-output-file-map",+ output_map_artifact.as_output(),+ )+ elif get_incremental_file_hashing_enabled(ctx):+ cmd.add(+ "-enable-incremental-file-hashing",+ "-avoid-emit-module-source-info",+ )+ if get_incremental_remote_outputs_enabled(ctx):+ cmd.add(+ "-Xwrapper",+ "--no-file-prefix-map",+ "-dwarf-version=5",+ "-Xcc",+ "-working-directory",+ "-Xcc",+ ".",+ )++ return SwiftmoduleIncrementalCompilationOutput(+ incremental_flags_cmd = cmd,+ output_file_map = output_file_map_data.output_file_map,+ skip_incremental_outputs = skip_incremental_outputs,+ swiftdeps = output_file_map_data.swiftdeps,+ depfiles = output_file_map_data.depfiles,+ )++def _get_incremental_num_threads(num_srcs: int) -> int:+ if num_srcs == 0:+ return 1++ src_threads = (num_srcs + INCREMENTAL_SWIFT_COMPILE_BATCH_SIZE - 1) // INCREMENTAL_SWIFT_COMPILE_BATCH_SIZE+ return min(INCREMENTAL_SWIFT_COMPILE_MAX_NUM_THREADS, src_threads)++def _get_skip_swift_incremental_outputs(ctx: AnalysisContext):+ return getattr(ctx.attrs, "_skip_swift_incremental_outputs", False)++def get_incremental_file_hashing_enabled(ctx: AnalysisContext):+ toolchain = get_swift_toolchain_info(ctx)+ return toolchain.supports_incremental_file_hashing and getattr(ctx.attrs, "swift_incremental_file_hashing", False) and should_build_swift_incrementally(ctx)++def get_swift_incremental_logging_enabled(ctx: AnalysisContext):+ return getattr(ctx.attrs, "swift_incremental_logging", False)++def get_incremental_split_actions(ctx: AnalysisContext):+ return getattr(ctx.attrs, "_swift_incremental_split_actions", False)++def get_incremental_swiftmodule_action(ctx: AnalysisContext):+ return getattr(ctx.attrs, "_swift_incremental_swiftmodule_action", False)++def should_build_swiftmodule_incrementally(ctx: AnalysisContext) -> bool:+ # The new incremental swiftmodule action requires:+ # * Swift built incrementally+ # * Split actions on (the object action is what we split from)+ # * The new opt-in attribute on+ return should_build_swift_incrementally(ctx) and get_incremental_split_actions(ctx) and get_incremental_swiftmodule_action(ctx)++def get_incremental_remote_outputs_enabled(ctx: AnalysisContext):+ return getattr(ctx.attrs, "incremental_remote_outputs", False)++def get_uses_content_based_paths(ctx):+ if getattr(ctx.attrs, "has_content_based_path", None) != None:+ return ctx.attrs.has_content_based_path++ toolchain = get_swift_toolchain_info(ctx)+ return toolchain.uses_content_based_paths++def _get_incremental_compilation_flags_and_objects(+ ctx: AnalysisContext,+ output_file_map_data: _OutputFileMapData,+ output_swiftmodule: Artifact,+ output_swiftdoc: Artifact | None,+ output_header: Artifact,+ num_srcs: int,+) -> IncrementalCompilationOutput:+ extra_hidden = [output_swiftdoc.as_output()] if output_swiftdoc else []++ # Match the driver -j to the Buck `weight` (num_threads) so the frontend-thread count matches+ # the permits Buck reserves. Otherwise -j was always 6 while weight could be 1, oversubscribing+ # up to ~6x and under-counting CPU in the (weight-based) low-pass-filter capacity.+ num_threads = _get_incremental_num_threads(num_srcs)+ cmd = cmd_args(+ [+ "-disable-cmo",+ "-emit-object",+ "-enable-batch-mode",+ "-enable-incremental-imports",+ "-experimental-emit-module-separately",+ "-incremental",+ "-j",+ str(num_threads),+ "-driver-batch-size-limit",+ str(INCREMENTAL_SWIFT_COMPILE_BATCH_SIZE),+ ],+ hidden = [output.as_output() for output in output_file_map_data.outputs] + extra_hidden,+ )+ cmd.add(include_path_for_relative_module_map_paths(ctx))++ if not get_incremental_split_actions(ctx):+ cmd.add(+ [+ "-emit-objc-header",+ "-emit-objc-header-path",+ output_header.as_output(),+ "-emit-module",+ "-emit-module-path",+ output_swiftmodule.as_output(),+ ],+ )++ skip_incremental_outputs = _get_skip_swift_incremental_outputs(ctx)+ incremental_remote_outputs = False+ uses_content_based_paths = get_uses_content_based_paths(ctx)+ if get_swift_incremental_logging_enabled(ctx):+ cmd.add([+ "-driver-show-incremental",+ "-driver-show-job-lifecycle",+ ])++ if skip_incremental_outputs:+ # When skipping incremental outputs, we write the contents of the+ # output_file_map in the swift wrapper and need to ensure this is+ # an output file (vs being an input in normal cases)+ output_map_artifact = ctx.actions.declare_output("__swift_incremental__/output_file_map.json", has_content_based_path = uses_content_based_paths)+ cmd.add(+ "-Xwrapper",+ "-skip-incremental-outputs",+ "-output-file-map",+ output_map_artifact.as_output(),+ )+ elif get_incremental_file_hashing_enabled(ctx):+ cmd.add(+ "-enable-incremental-file-hashing",+ "-avoid-emit-module-source-info",+ )+ if get_incremental_remote_outputs_enabled(ctx):+ incremental_remote_outputs = True+ cmd.add(+ "-Xwrapper",+ "--no-file-prefix-map",+ "-dwarf-version=5",+ "-Xcc",+ "-working-directory",+ "-Xcc",+ ".",+ )++ return IncrementalCompilationOutput(+ artifacts = output_file_map_data.artifacts,+ incremental_flags_cmd = cmd,+ num_threads = num_threads,+ output_file_map = output_file_map_data.output_file_map,+ skip_incremental_outputs = skip_incremental_outputs,+ swiftdeps = output_file_map_data.swiftdeps,+ depfiles = output_file_map_data.depfiles,+ incremental_remote_outputs = incremental_remote_outputs,+ swiftdoc = output_swiftdoc,+ )++def _get_output_file_map(ctx: AnalysisContext, srcs: list[CxxSrcWithFlags]) -> _OutputFileMapData:+ uses_content_based_paths = get_uses_content_based_paths(ctx)+ if _get_skip_swift_incremental_outputs(ctx):+ all_outputs = []+ swiftdeps = []+ artifacts = []+ depfiles = []+ output_file_map = {}++ for src in srcs:+ file_name = src.file.basename+ output_artifact = ctx.actions.declare_output("__swift_incremental__/objects/" + file_name + ".o", has_content_based_path = uses_content_based_paths)+ artifacts.append(output_artifact)+ all_outputs.append(output_artifact)+ else:+ # swift-driver doesn't respect extension for root swiftdeps file and it always has to be `.priors`.+ module_swiftdeps = ctx.actions.declare_output(+ "__swift_incremental__/swiftdeps/module-build-record.priors", has_content_based_path = uses_content_based_paths+ )+ output_file_map = {+ "": {+ "swift-dependencies": module_swiftdeps,+ },+ }+ all_outputs = [module_swiftdeps]+ swiftdeps = [module_swiftdeps]+ artifacts = []+ depfiles = []+ toolchain = get_swift_toolchain_info(ctx)++ for src in srcs:+ file_name = src.file.basename+ output_artifact = ctx.actions.declare_output("__swift_incremental__/objects/" + file_name + ".o", has_content_based_path = uses_content_based_paths)+ artifacts.append(output_artifact)+ all_outputs.append(output_artifact)+ swiftdeps_artifact = ctx.actions.declare_output(+ "__swift_incremental__/swiftdeps/" + file_name + ".swiftdeps", has_content_based_path = uses_content_based_paths+ )+ output_file_map[src.file] = {+ "object": output_artifact,+ "swift-dependencies": swiftdeps_artifact,+ }+ swiftdeps.append(swiftdeps_artifact)+ all_outputs.append(swiftdeps_artifact)+ if toolchain.use_depsfiles and not get_incremental_file_hashing_enabled(ctx):+ deps_artifact = ctx.actions.declare_output("__swift_incremental__/objects/" + file_name + ".d", has_content_based_path = uses_content_based_paths)+ depfiles.append(deps_artifact)+ all_outputs.append(deps_artifact)++ return _OutputFileMapData(+ artifacts = artifacts,+ outputs = all_outputs,+ output_file_map = output_file_map,+ swiftdeps = swiftdeps,+ depfiles = depfiles,+ )++def _get_swiftmodule_output_file_map(ctx: AnalysisContext, srcs: list[CxxSrcWithFlags]) -> _OutputFileMapData:+ uses_content_based_paths = get_uses_content_based_paths(ctx)+ if _get_skip_swift_incremental_outputs(ctx):+ return _OutputFileMapData(+ artifacts = [],+ outputs = [],+ output_file_map = {},+ swiftdeps = [],+ depfiles = [],+ )++ module_swiftdeps = ctx.actions.declare_output(+ "__swift_module_incremental__/swiftdeps/module-build-record.priors", has_content_based_path = uses_content_based_paths+ )+ output_file_map = {+ "": {+ "swift-dependencies": module_swiftdeps,+ },+ }++ # For incremental swiftmodule generation, we need to capture the set of+ # incremental output files they produce.+ per_source_dir = ctx.actions.declare_output(+ "__swift_module_incremental__/per_source_incremental", dir = True, has_content_based_path = uses_content_based_paths+ )+ for src in srcs:+ file_name = src.file.basename+ output_file_map[src.file] = {+ "diagnostics": cmd_args(per_source_dir, format = "{}/" + file_name + ".dia", delimiter = ""),+ "swift-dependencies": cmd_args(per_source_dir, format = "{}/" + file_name + ".swiftdeps", delimiter = ""),+ "swiftmodule": cmd_args(per_source_dir, format = "{}/" + file_name + ".swiftmodule", delimiter = ""),+ }++ return _OutputFileMapData(+ artifacts = [],+ outputs = [module_swiftdeps, per_source_dir],+ output_file_map = output_file_map,+ swiftdeps = [module_swiftdeps, per_source_dir],+ depfiles = [],+ )
@@ -0,0 +1,52 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")+load("@prelude//utils:arglike.bzl", "ArgLike") # @unused Used as a type+load(+ ":swift_incremental_support.bzl",+ "get_uses_content_based_paths",+)+load(":swift_toolchain_types.bzl", "SwiftCompiledModuleTset")++def write_swift_module_map_with_deps(ctx: AnalysisContext, module_name: str, all_deps: SwiftCompiledModuleTset) -> (Artifact, ArgLike):+ uses_content_based_paths = get_uses_content_based_paths(ctx)+ artifact = ctx.actions.declare_output(+ module_name + ".swift_module_map.json",+ has_content_based_path = uses_content_based_paths,+ )+ args = ctx.actions.write_json(+ artifact.as_output(),+ all_deps.project_as_json("swift_module_map"),+ pretty = True,+ with_inputs = True,+ )++ # There are cases where we can see duplicate entries in the modulemaps.+ # This happens when there's different execution platforms across+ # `apple_library()` targets. For more info, see `get_swift_interface_anon_targets()`.+ deduplicated_artifact = ctx.actions.declare_output(+ module_name + ".deduplicated.swift_module_map.json",+ has_content_based_path = uses_content_based_paths,+ )+ ctx.actions.run(+ cmd_args(+ ctx.attrs._apple_tools[AppleToolsInfo].dedupe_swift_module_map,+ "--input",+ artifact,+ "--output",+ deduplicated_artifact.as_output(),+ ),+ category = "swift_module_map_dedupe",+ identifier = module_name,+ )++ # The de-duplicated map holds the same module artifact paths as the original,+ # so carry those inputs along for downstream consumers to materialize.+ deduplicated_args = cmd_args(deduplicated_artifact, hidden = args)+ return (deduplicated_artifact, deduplicated_args)
@@ -0,0 +1,95 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_utility.bzl", "get_module_name")+load(+ "@prelude//cxx:cxx_sources.bzl",+ "CxxSrcWithFlags", # @unused Used as a type+)+load(+ ":swift_incremental_support.bzl",+ "get_uses_content_based_paths",+)++def add_dependencies_output(ctx: AnalysisContext, output_file_map: dict, cmd: cmd_args, category: str, inputs_tag: ArtifactTag) -> None:+ # Add a Makefile style dependency file output. This output is not tracked,+ # we need to process it first.+ uses_content_based_paths = get_uses_content_based_paths(ctx)+ buck_dep_file = ctx.actions.declare_output(+ "__depfiles__/{}-{}.d".format(ctx.attrs.name, category), has_content_based_path = uses_content_based_paths+ ).as_output()+ map = output_file_map.setdefault("", {})+ map["dependencies"] = cmd_args(buck_dep_file, delimiter = "", format = "{}.raw")+ map["emit-module-dependencies"] = cmd_args(buck_dep_file, delimiter = "", format = "{}.raw")+ cmd.add("-emit-dependencies")++ # Add the flags for the wrapper to process the dependency file to Buck format.+ cmd.add(+ "-Xwrapper",+ cmd_args(inputs_tag.tag_artifacts(buck_dep_file), format = "-dependencies-file-output={}"),+ )++def add_serialized_diagnostics_output(+ ctx: AnalysisContext,+ output_file_map: dict | None,+ cmd: cmd_args,+ diagnostics_output: OutputArtifact,+ is_incremental: bool = False,+ split_actions: bool = False,+ skip_incremental_outputs: bool = False,+) -> None:+ if output_file_map == None:+ # Some actions, eg -emit-pcm, do not support output file maps. In this+ # case we need to pass the frontend flags directly.+ cmd.add(+ "-Xfrontend",+ cmd_args(diagnostics_output, format = "-serialize-diagnostics-path={}.dia"),+ )+ else:+ map = output_file_map.setdefault("", {})+ map["diagnostics"] = cmd_args(diagnostics_output, delimiter = "", format = "{}.dia")+ cmd.add(cmd_args("-serialize-diagnostics", hidden = [diagnostics_output]))++ if is_incremental and not skip_incremental_outputs and not split_actions:+ uses_content_based_paths = get_uses_content_based_paths(ctx)+ module_name = get_module_name(ctx)+ module_dia = ctx.actions.declare_output(+ "__swift_incremental__/swiftdeps/" + module_name + ".emit-module.dia", has_content_based_path = uses_content_based_paths+ )+ map["emit-module-diagnostics"] = module_dia+ cmd.add(cmd_args(hidden = [module_dia.as_output()]))++def add_output_file_map_flags(ctx: AnalysisContext, output_file_map: dict, cmd: cmd_args, category: str) -> Artifact:+ uses_content_based_paths = get_uses_content_based_paths(ctx)+ output_file_map_json = ctx.actions.write_json(+ "{}_output_file_map.json".format(category),+ output_file_map,+ pretty = True,+ has_content_based_path = uses_content_based_paths,+ )+ cmd.add("-output-file-map", output_file_map_json)+ return output_file_map_json++def get_modularization_dependency_graph_output_map(ctx: AnalysisContext, srcs: list[CxxSrcWithFlags]):+ output_file_map = {}+ output_modularization_dependency_graph_shards = []+ output_objects = []+ for src in srcs:+ file_name = src.file.basename+ object_file_artifact = ctx.actions.declare_output("__swift_modularization___/objects/" + file_name + ".o", has_content_based_path = False)+ modularization_dependency_graph_artifact = ctx.actions.declare_output(+ "__swift_modularization___/dependency_graphs/" + file_name + ".modularizationdependencygraph", has_content_based_path = False+ )+ output_file_map[src.file] = {+ "modularization-dependency-graph": modularization_dependency_graph_artifact,+ "object": object_file_artifact,+ }+ output_objects.append(object_file_artifact)+ output_modularization_dependency_graph_shards.append(modularization_dependency_graph_artifact)++ return output_file_map, output_objects, output_modularization_dependency_graph_shards
@@ -0,0 +1,290 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple/swift:swift_helpers.bzl", "compile_with_argsfile")+load(+ ":apple_sdk_modules_utility.bzl",+ "get_compiled_sdk_clang_deps_tset",+ "get_uncompiled_sdk_deps",+)+load(+ ":swift_debug_info_utils.bzl",+ "extract_and_merge_clang_debug_infos",+)+load(":swift_pcm_compilation_types.bzl", "SwiftPCMUncompiledInfo", "WrappedSwiftPCMCompiledInfo")+load(":swift_sdk_flags.bzl", "get_sdk_flags")+load(":swift_sdk_pcm_compilation.bzl", "get_shared_pcm_compilation_args", "get_swift_sdk_pcm_anon_targets")+load(":swift_toolchain.bzl", "get_swift_toolchain_info", "get_swift_toolchain_info_dep")+load(":swift_toolchain_types.bzl", "SwiftCompiledModuleInfo", "SwiftCompiledModuleTset", "SwiftToolchainInfo", "WrappedSdkCompiledModuleInfo")++_REQUIRED_SDK_MODULES = ["Foundation"]++_REQUIRED_SDK_CXX_MODULES = _REQUIRED_SDK_MODULES + ["std"]++def get_compiled_pcm_deps_tset(ctx: AnalysisContext, pcm_deps_providers: list) -> SwiftCompiledModuleTset:+ pcm_deps = [+ pcm_deps_provider[WrappedSwiftPCMCompiledInfo].clang_deps+ for pcm_deps_provider in pcm_deps_providers+ if WrappedSwiftPCMCompiledInfo in pcm_deps_provider+ ]+ return ctx.actions.tset(SwiftCompiledModuleTset, children = pcm_deps)++def get_swift_pcm_anon_targets(ctx: AnalysisContext, uncompiled_deps: list[Dependency], swift_cxx_args: list[str], enable_cxx_interop: bool):+ deps = []+ for uncompiled_dep in uncompiled_deps:+ if SwiftPCMUncompiledInfo not in uncompiled_dep:+ continue++ # T209485965: workaround for depagg to avoid duplicate clang modules+ # when traversing deps through the base target and [headers] subtarget.+ # By always requesting the [headers] subtarget we should use the same+ # anon actions for both paths.+ if "headers" in uncompiled_dep[DefaultInfo].sub_targets:+ uncompiled_dep = uncompiled_dep.sub_target("headers")++ deps.append(+ (+ _swift_pcm_compilation,+ {+ "dep": uncompiled_dep,+ "enable_cxx_interop": enable_cxx_interop,+ "has_content_based_path": False,+ "name": uncompiled_dep.label,+ "swift_cxx_args": swift_cxx_args,+ "_swift_toolchain": get_swift_toolchain_info_dep(ctx),+ },+ )+ )++ return deps++def _compiled_module_info(module_name: str, pcm_output: Artifact, pcm_info: SwiftPCMUncompiledInfo) -> SwiftCompiledModuleInfo:+ return SwiftCompiledModuleInfo(+ clang_importer_args = pcm_info.exported_clang_importer_args,+ clang_modulemap_path = cmd_args(pcm_info.modulemap_artifact),+ is_framework = False,+ is_sdk_module = False,+ is_swiftmodule = False,+ module_name = module_name,+ output_artifact = pcm_output,+ )++def _swift_pcm_compilation_impl(ctx: AnalysisContext) -> [Promise, list[Provider]]:+ def k(compiled_pcm_deps_providers) -> list[Provider]:+ uncompiled_pcm_info = ctx.attrs.dep[SwiftPCMUncompiledInfo]++ # `compiled_pcm_deps_providers` will contain `WrappedSdkCompiledModuleInfo` providers+ # from direct SDK deps and transitive deps that export sdk deps.+ sdk_deps_tset = get_compiled_sdk_clang_deps_tset(ctx, compiled_pcm_deps_providers)++ # To compile a pcm we only use the exported_deps as those are the only+ # ones that should be transitively exported through public headers+ pcm_deps_tset = get_compiled_pcm_deps_tset(ctx, compiled_pcm_deps_providers)++ # We don't need to compile non-modular or targets that do not export any headers,+ # but for the sake of BUCK1 compatibility, we need to pass them up,+ # in case they re-export some dependencies.+ if uncompiled_pcm_info.is_transient:+ return [+ DefaultInfo(),+ WrappedSwiftPCMCompiledInfo(+ clang_deps = pcm_deps_tset,+ clang_debug_info = extract_and_merge_clang_debug_infos(ctx, compiled_pcm_deps_providers),+ ),+ WrappedSdkCompiledModuleInfo(+ clang_deps = sdk_deps_tset,+ clang_debug_info = extract_and_merge_clang_debug_infos(ctx, compiled_pcm_deps_providers),+ ),+ ]++ module_name = uncompiled_pcm_info.name+ swift_toolchain_info = ctx.attrs._swift_toolchain[SwiftToolchainInfo]+ cmd, additional_cmd, pcm_output = _get_base_pcm_flags(+ ctx,+ module_name,+ swift_toolchain_info,+ uncompiled_pcm_info,+ sdk_deps_tset,+ pcm_deps_tset,+ ctx.attrs.swift_cxx_args,+ )++ compile_with_argsfile(+ ctx,+ category = "swift_pcm_compile",+ shared_flags = cmd,+ srcs = [],+ additional_flags = additional_cmd,+ toolchain = swift_toolchain_info,+ supports_output_file_map = False,+ )+ pcm_info = _compiled_module_info(module_name, pcm_output, uncompiled_pcm_info)+ debug_artifacts = [+ pcm_info.output_artifact,+ uncompiled_pcm_info.modulemap_artifact,+ ]++ return [+ DefaultInfo(default_outputs = [pcm_output]),+ WrappedSwiftPCMCompiledInfo(+ clang_deps = ctx.actions.tset(SwiftCompiledModuleTset, value = pcm_info, children = [pcm_deps_tset]),+ clang_debug_info = extract_and_merge_clang_debug_infos(ctx, compiled_pcm_deps_providers, debug_artifacts),+ ),+ WrappedSdkCompiledModuleInfo(+ clang_deps = sdk_deps_tset,+ # No need to further propagate debug info, it will be included+ # in WrappedSwiftPCMCompiledInfo.+ ),+ ]++ required_sdk_modules = _REQUIRED_SDK_CXX_MODULES if ctx.attrs.enable_cxx_interop else _REQUIRED_SDK_MODULES+ direct_uncompiled_sdk_deps = get_uncompiled_sdk_deps(+ ctx.attrs.dep[SwiftPCMUncompiledInfo].uncompiled_sdk_modules,+ required_sdk_modules,+ ctx.attrs._swift_toolchain[SwiftToolchainInfo],+ )++ # Recursively compiling SDK's Clang dependencies+ sdk_pcm_deps_anon_targets = get_swift_sdk_pcm_anon_targets(+ ctx,+ ctx.attrs.enable_cxx_interop,+ direct_uncompiled_sdk_deps,+ ctx.attrs.swift_cxx_args,+ )++ # Recursively compile PCMs of transitevely visible exported_deps+ swift_pcm_anon_targets = get_swift_pcm_anon_targets(+ ctx,+ ctx.attrs.dep[SwiftPCMUncompiledInfo].exported_deps,+ ctx.attrs.swift_cxx_args,+ ctx.attrs.enable_cxx_interop,+ )+ return ctx.actions.anon_targets(sdk_pcm_deps_anon_targets + swift_pcm_anon_targets).promise.map(k)++_swift_pcm_compilation = rule(+ impl = _swift_pcm_compilation_impl,+ attrs = {+ "dep": attrs.dep(),+ "enable_cxx_interop": attrs.bool(),+ "has_content_based_path": attrs.bool(),+ "swift_cxx_args": attrs.list(attrs.string(), default = []),+ "_swift_toolchain": attrs.dep(),+ },+)++def _compile_pcm(+ ctx: AnalysisContext,+ action_name: str,+ module_name: str,+ uncompiled_pcm_info: SwiftPCMUncompiledInfo,+ compiled_pcm_deps_providers,+ swift_cxx_args: list[str],+ additional_args: cmd_args,+) -> SwiftCompiledModuleInfo:+ # `compiled_pcm_deps_providers` will contain `WrappedSdkCompiledModuleInfo` providers+ # from direct SDK deps and transitive deps that export sdk deps.+ sdk_deps_tset = get_compiled_sdk_clang_deps_tset(ctx, compiled_pcm_deps_providers)++ # To compile a pcm we only use the exported_deps as those are the only+ # ones that should be transitively exported through public headers+ pcm_deps_tset = get_compiled_pcm_deps_tset(ctx, compiled_pcm_deps_providers)++ swift_toolchain_info = get_swift_toolchain_info(ctx)+ cmd, additional_cmd, pcm_output = _get_base_pcm_flags(+ ctx,+ module_name,+ swift_toolchain_info,+ uncompiled_pcm_info,+ sdk_deps_tset,+ pcm_deps_tset,+ swift_cxx_args,+ )+ cmd.add(additional_args)+ compile_with_argsfile(+ ctx,+ category = action_name,+ shared_flags = cmd,+ srcs = [],+ additional_flags = additional_cmd,+ toolchain = swift_toolchain_info,+ supports_output_file_map = False,+ )+ return _compiled_module_info(module_name, pcm_output, uncompiled_pcm_info)++def compile_framework_pcm(+ ctx: AnalysisContext, module_name: str, uncompiled_pcm_info: SwiftPCMUncompiledInfo, compiled_pcm_deps_providers, swift_cxx_args: list[str]+) -> SwiftCompiledModuleInfo:+ return _compile_pcm(+ ctx,+ "swift_prebuilt_framework_pcm_compile",+ module_name,+ uncompiled_pcm_info,+ compiled_pcm_deps_providers,+ swift_cxx_args,+ cmd_args(),+ )++def compile_underlying_pcm(+ ctx: AnalysisContext,+ module_name: str,+ uncompiled_pcm_info: SwiftPCMUncompiledInfo,+ compiled_pcm_deps_providers,+ swift_cxx_args: list[str],+ framework_search_path_flags: cmd_args,+) -> SwiftCompiledModuleInfo:+ return _compile_pcm(+ ctx,+ "swift_underlying_pcm_compile",+ module_name,+ uncompiled_pcm_info,+ compiled_pcm_deps_providers,+ swift_cxx_args,+ framework_search_path_flags,+ )++def _get_base_pcm_flags(+ ctx: AnalysisContext,+ module_name: str,+ swift_toolchain_info: SwiftToolchainInfo,+ uncompiled_pcm_info: SwiftPCMUncompiledInfo,+ sdk_deps_tset: SwiftCompiledModuleTset,+ pcm_deps_tset: SwiftCompiledModuleTset,+ swift_cxx_args: list[str],+) -> (cmd_args, cmd_args, Artifact):+ uses_content_based_paths = False+ pcm_output = ctx.actions.declare_output(module_name + ".pcm", has_content_based_path = uses_content_based_paths)+ cmd = cmd_args(+ get_shared_pcm_compilation_args(module_name),+ get_sdk_flags(ctx),+ swift_toolchain_info.compiler_flags,+ (+ [+ "-resource-dir",+ swift_toolchain_info.resource_dir,+ ]+ if swift_toolchain_info.resource_dir+ else []+ ),+ sdk_deps_tset.project_as_args("clang_module_file_flags"),+ pcm_deps_tset.project_as_args("clang_module_file_flags"),+ pcm_deps_tset.project_as_args("clang_importer_flags"),+ # Order is important here, we need to add the symlink tree search paths+ # before the headermaps to avoid mixing include paths.+ uncompiled_pcm_info.exported_clang_importer_args,+ uncompiled_pcm_info.clang_importer_args,+ )++ cmd.add(swift_cxx_args)++ additional_cmd = cmd_args(+ "-o",+ pcm_output.as_output(),+ uncompiled_pcm_info.modulemap_artifact,+ )++ return (cmd, additional_cmd, pcm_output)
@@ -0,0 +1,38 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactTSet",+)+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftCompiledModuleTset")++SwiftPCMUncompiledInfo = provider(+ fields = {+ # Compiler args required to compile this module.+ "clang_importer_args": provider_field(cmd_args),+ # Compiler args required by rdeps of this module, such as search paths for+ # header symlink trees or framework bundles.+ "exported_clang_importer_args": provider_field(cmd_args),+ "exported_deps": provider_field(list[Dependency], default = []),+ # If True represents an apple_library target that can't be compiled into a+ # pcm, but which can re-export modular deps.+ "is_transient": provider_field(bool, default = False),+ # For non-transient modules, the artifact of this module's modulemap.+ "modulemap_artifact": provider_field(Artifact | None, default = None),+ "name": provider_field(str),+ "uncompiled_sdk_modules": provider_field(list[str], default = []),+ }+)++WrappedSwiftPCMCompiledInfo = provider(+ fields = {+ "clang_debug_info": provider_field(ArtifactTSet),+ "clang_deps": provider_field(SwiftCompiledModuleTset), # Tset of `SwiftCompiledModuleInfo`+ }+)
@@ -0,0 +1,17 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//utils:arglike.bzl", "ArgLike")+load(":swift_toolchain.bzl", "get_swift_toolchain_info")++def get_sdk_flags(ctx: AnalysisContext) -> list[ArgLike]:+ swift_toolchain_info = get_swift_toolchain_info(ctx)+ if swift_toolchain_info.sdk_path:+ return ["-sdk", swift_toolchain_info.sdk_path]+ else:+ return []
@@ -0,0 +1,256 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_error_handler.bzl", "apple_build_error_handler")+load("@prelude//apple:apple_utility.bzl", "expand_relative_prefixed_sdk_path", "get_disable_pch_validation_flags")+load(":apple_sdk_modules_utility.bzl", "get_compiled_sdk_clang_deps_tset")+load(+ ":swift_debug_info_utils.bzl",+ "extract_and_merge_clang_debug_infos",+)+load(":swift_sdk_flags.bzl", "get_sdk_flags")+load(":swift_toolchain.bzl", "get_swift_toolchain_info_dep")+load(+ ":swift_toolchain_types.bzl",+ "SdkUncompiledModuleInfo",+ "SwiftCompiledModuleInfo",+ "SwiftCompiledModuleTset",+ "SwiftToolchainInfo",+ "WrappedSdkCompiledModuleInfo",+)++def get_shared_pcm_compilation_args(module_name: str) -> cmd_args:+ cmd = cmd_args()+ cmd.add([+ "-emit-pcm",+ "-module-name",+ module_name,+ "-Xfrontend",+ "-disable-implicit-swift-modules",+ "-Xcc",+ "-fno-implicit-modules",+ "-Xcc",+ "-fno-implicit-module-maps",+ # Embed all input files into the PCM so we don't need to include module map files when+ # building remotely.+ # https://github.com/apple/llvm-project/commit/fb1e7f7d1aca7bcfc341e9214bda8b554f5ae9b6+ "-Xcc",+ "-Xclang",+ "-Xcc",+ "-fmodules-embed-all-files",+ # Set the base directory of the pcm file to the working directory, which ensures+ # all paths serialized in the PCM are relative.+ "-Xcc",+ "-Xclang",+ "-Xcc",+ "-fmodule-file-home-is-cwd",+ # We cannot set an empty Swift working directory as that would end up serializing+ # absolute header search paths in the PCM. Instead unset the clang working directory+ # to avoid serializing it as an absolute path.+ "-Xcc",+ "-working-directory=",+ # AssetsLibrary is shipping with a #warning, which we shouldn't error on when compiling+ # the SDK module. I don't think this is actually avoidable or removable until the next xcode major version+ "-Xcc",+ "-Wno-error=#warnings",+ # When compiling PCMs with the new Swift driver, we need to manually set -file-compilation-dir.+ # If not defined, the driver will append this path automatically,+ # resulting in the emission of absolute paths in the PCMs.+ "-file-compilation-dir",+ ".",+ ])++ cmd.add(get_disable_pch_validation_flags())++ return cmd++def _remove_path_components_from_right(path: str, count: int):+ path_components = path.split("/")+ removed_path = "/".join(path_components[0:-count])+ return removed_path++def _add_sdk_module_search_path(cmd, uncompiled_sdk_module_info, swift_toolchain_info):+ modulemap_path = uncompiled_sdk_module_info.input_relative_path++ # If this input is a framework we need to search above the+ # current framework location, otherwise we include the+ # modulemap root.+ if uncompiled_sdk_module_info.is_framework:+ frameworks_dir_path = _remove_path_components_from_right(modulemap_path, 3)+ expanded_path = expand_relative_prefixed_sdk_path(swift_toolchain_info, frameworks_dir_path)+ else:+ module_root_path = _remove_path_components_from_right(modulemap_path, 1)+ expanded_path = expand_relative_prefixed_sdk_path(swift_toolchain_info, module_root_path)+ cmd.add(+ "-Xcc",+ ("-F" if uncompiled_sdk_module_info.is_framework else "-I"),+ "-Xcc",+ expanded_path,+ )++def get_swift_sdk_pcm_anon_targets(ctx: AnalysisContext, enable_cxx_interop: bool, uncompiled_sdk_deps: list[Dependency], swift_cxx_args: list[str]):+ # We include the Swift deps here too as we need+ # to include their transitive clang deps.+ return [+ (+ _swift_sdk_pcm_compilation,+ {+ "dep": module_dep,+ "enable_cxx_interop": enable_cxx_interop,+ "has_content_based_path": False,+ "name": module_dep.label,+ "swift_cxx_args": swift_cxx_args,+ "_swift_toolchain": get_swift_toolchain_info_dep(ctx),+ },+ )+ for module_dep in uncompiled_sdk_deps+ ]++def _swift_sdk_pcm_compilation_impl(ctx: AnalysisContext) -> [Promise, list[Provider]]:+ def k(sdk_pcm_deps_providers) -> list[Provider]:+ uncompiled_sdk_module_info = ctx.attrs.dep[SdkUncompiledModuleInfo]+ sdk_deps_tset = get_compiled_sdk_clang_deps_tset(ctx, sdk_pcm_deps_providers)+ uses_content_based_paths = False++ # We pass in Swift and Clang SDK module deps to get the transitive+ # Clang dependencies compiled with the correct Swift cxx args. For+ # Swift modules we just want to pass up the clang deps.+ if uncompiled_sdk_module_info.is_swiftmodule:+ return [+ DefaultInfo(),+ WrappedSdkCompiledModuleInfo(+ clang_deps = sdk_deps_tset,+ clang_debug_info = extract_and_merge_clang_debug_infos(ctx, sdk_pcm_deps_providers),+ ),+ ]++ module_name = uncompiled_sdk_module_info.module_name+ swift_toolchain = ctx.attrs._swift_toolchain[SwiftToolchainInfo]+ cmd = cmd_args(swift_toolchain.compiler)+ argsfile_cmd = cmd_args(uncompiled_sdk_module_info.partial_cmd)+ argsfile_cmd.add(get_sdk_flags(ctx))+ argsfile_cmd.add(swift_toolchain.compiler_flags)++ if swift_toolchain.resource_dir:+ argsfile_cmd.add([+ "-resource-dir",+ swift_toolchain.resource_dir,+ ])++ if not swift_toolchain.supports_relative_resource_dir:+ # When the compiler does not correctly serialize builtin header paths+ # we need to specify the CWD as a search path to find the headers.+ argsfile_cmd.add([+ "-Xcc",+ "-I.",+ ])++ argsfile_cmd.add(sdk_deps_tset.project_as_args("clang_module_file_flags"))++ # For SDK modules we need to set a few more args+ argsfile_cmd.add([+ "-Xcc",+ "-Xclang",+ "-Xcc",+ "-emit-module",+ "-Xcc",+ "-Xclang",+ "-Xcc",+ "-fsystem-module",+ ])++ argsfile_cmd.add(ctx.attrs.swift_cxx_args)++ if ctx.attrs.enable_cxx_interop:+ # The stdlib headers have deprecation warnings set when targeting+ # more recent versions. These warnings get serialized in the+ # modules and make it impossible to import the std module, so+ # suppress them during compilation instead.+ argsfile_cmd.add([+ "-Xcc",+ "-D_LIBCPP_DISABLE_DEPRECATION_WARNINGS",+ ])++ if module_name == "Darwin":+ # The Darwin module requires special handling with cxx interop+ # to ensure that it does not include the c++ headers. The module+ # is marked with [no_undeclared_includes] which will prevent+ # including headers declared in other modulemaps. So that the+ # cxx modules are visible we need to pass the module map path+ # without the corresponding module file, which we cannot build+ # until the Darwin module is available.+ argsfile_cmd.add([+ "-Xcc",+ cmd_args(swift_toolchain.sdk_path, format = "-fmodule-map-file={}/usr/include/c++/v1/module.modulemap"),+ ])++ _add_sdk_module_search_path(argsfile_cmd, uncompiled_sdk_module_info, swift_toolchain)++ shell_quoted_args = cmd_args(argsfile_cmd, quote = "shell")+ argsfile, _ = ctx.actions.write("sdk_pcm_compile_argsfile", shell_quoted_args, allow_args = True, has_content_based_path = uses_content_based_paths)+ cmd.add(cmd_args(argsfile, format = "@{}", delimiter = ""))+ cmd.add(cmd_args(hidden = [argsfile_cmd]))++ expanded_modulemap_path_cmd = expand_relative_prefixed_sdk_path(+ swift_toolchain,+ uncompiled_sdk_module_info.input_relative_path,+ )+ pcm_output = ctx.actions.declare_output(module_name + ".pcm", has_content_based_path = uses_content_based_paths)+ cmd.add([+ "-o",+ pcm_output.as_output(),+ expanded_modulemap_path_cmd,+ ])++ ctx.actions.run(+ cmd,+ category = "sdk_swift_pcm_compile",+ identifier = module_name,+ # Swift compiler requires unique inodes for all input files.+ unique_input_inodes = True,+ error_handler = apple_build_error_handler,+ )++ compiled_sdk = SwiftCompiledModuleInfo(+ clang_modulemap_path = expanded_modulemap_path_cmd,+ is_framework = uncompiled_sdk_module_info.is_framework,+ is_sdk_module = True,+ is_swiftmodule = False,+ module_name = module_name,+ output_artifact = pcm_output,+ )++ return [+ DefaultInfo(),+ WrappedSdkCompiledModuleInfo(+ clang_deps = ctx.actions.tset(SwiftCompiledModuleTset, value = compiled_sdk, children = [sdk_deps_tset]),+ clang_debug_info = extract_and_merge_clang_debug_infos(ctx, sdk_pcm_deps_providers, [pcm_output]),+ ),+ ]++ # Compile the transitive clang module deps of this target.+ deps = ctx.attrs.dep[SdkUncompiledModuleInfo].cxx_deps if ctx.attrs.enable_cxx_interop else ctx.attrs.dep[SdkUncompiledModuleInfo].deps+ clang_module_deps = get_swift_sdk_pcm_anon_targets(+ ctx,+ ctx.attrs.enable_cxx_interop,+ deps,+ ctx.attrs.swift_cxx_args,+ )++ return ctx.actions.anon_targets(clang_module_deps).promise.map(k)++_swift_sdk_pcm_compilation = rule(+ impl = _swift_sdk_pcm_compilation_impl,+ attrs = {+ "dep": attrs.dep(),+ "enable_cxx_interop": attrs.bool(),+ "has_content_based_path": attrs.bool(),+ "swift_cxx_args": attrs.list(attrs.string(), default = []),+ "_swift_toolchain": attrs.dep(),+ },+)
@@ -0,0 +1,190 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")+load("@prelude//apple:apple_utility.bzl", "expand_relative_prefixed_sdk_path")+load("@prelude//apple/swift:swift_pcm_compilation.bzl", "get_compiled_pcm_deps_tset")+load("@prelude//apple/swift:swift_types.bzl", "SWIFTMODULE_EXTENSION")+load(":apple_sdk_modules_utility.bzl", "get_compiled_sdk_clang_deps_tset", "get_compiled_sdk_swift_deps_tset")+load(+ ":swift_debug_info_utils.bzl",+ "extract_and_merge_clang_debug_infos",+ "extract_and_merge_swift_debug_infos",+)+load(+ ":swift_incremental_support.bzl",+ "get_uses_content_based_paths",+)+load(":swift_module_map.bzl", "write_swift_module_map_with_deps")+load(":swift_sdk_flags.bzl", "get_sdk_flags")+load(":swift_sdk_pcm_compilation.bzl", "get_swift_sdk_pcm_anon_targets")+load(":swift_toolchain.bzl", "get_swift_toolchain_info", "get_swift_toolchain_info_dep")+load(+ ":swift_toolchain_types.bzl",+ "SdkUncompiledModuleInfo",+ "SwiftCompiledModuleInfo",+ "SwiftCompiledModuleTset",+ "SwiftToolchainInfo",+ "WrappedSdkCompiledModuleInfo",+)++def get_swift_interface_anon_targets(ctx: AnalysisContext, uncompiled_sdk_deps: list[Dependency]):+ return [+ (+ _swift_interface_compilation,+ {+ # There's an "implicit" arg being passed - the execution platform+ # of the rule that's requesting the anon-targets. In this case,+ # callers of `get_swift_interface_anon_targets()` will call+ # `ctx.actions.anon_targets()`, so the exec platform will get+ # inherited.+ #+ # This has an important implication - the exact same SDK target+ # might get duplicated if it's requested `apple_library()`+ # targets which have different execution platforms, even if+ # everything else is the same - including the same toolchain.+ #+ # Because Swift compilation aggregates SDK modules from deps+ # and SDK modules from the target itself, a duplication of the+ # same compiled SDK module can occur in the module map.+ "dep": d,+ "has_content_based_path": True,+ "name": d.label,+ "_apple_tools": ctx.attrs._apple_tools,+ "_swift_toolchain": get_swift_toolchain_info_dep(ctx),+ },+ )+ for d in uncompiled_sdk_deps+ if d[SdkUncompiledModuleInfo].is_swiftmodule+ ]++def compile_swiftinterface_common(+ ctx,+ deps,+ is_framework,+ uncompiled_module_info_name,+ partial_cmd,+ sdk_deps_providers,+ expanded_swiftinterface_cmd,+ category,+ additional_compiled_pcm,+ additional_compiled_swiftmodules = None,+):+ uses_content_based_paths = get_uses_content_based_paths(ctx)+ swift_toolchain = get_swift_toolchain_info(ctx)+ cmd = cmd_args(swift_toolchain.compiler)+ cmd.add(partial_cmd)+ cmd.add(get_sdk_flags(ctx))++ if swift_toolchain.resource_dir:+ cmd.add([+ "-resource-dir",+ swift_toolchain.resource_dir,+ ])++ pcm_deps_tset = get_compiled_pcm_deps_tset(ctx, sdk_deps_providers)++ if additional_compiled_pcm:+ pcm_deps_tset = ctx.actions.tset(SwiftCompiledModuleTset, value = additional_compiled_pcm, children = [pcm_deps_tset])++ clang_deps_tset = get_compiled_sdk_clang_deps_tset(ctx, sdk_deps_providers)+ swift_deps_tset = get_compiled_sdk_swift_deps_tset(ctx, sdk_deps_providers + deps)++ #'additional_compiled_swiftmodules' in practice will be third-party frameworks+ if additional_compiled_swiftmodules:+ swift_deps_tset = ctx.actions.tset(SwiftCompiledModuleTset, children = [swift_deps_tset, additional_compiled_swiftmodules])++ all_deps_tset = ctx.actions.tset(+ SwiftCompiledModuleTset,+ children = [pcm_deps_tset, clang_deps_tset, swift_deps_tset],+ )++ _, swift_module_map_args = write_swift_module_map_with_deps(ctx, uncompiled_module_info_name, all_deps_tset)+ cmd.add([+ "-explicit-swift-module-map-file",+ swift_module_map_args,+ ])++ swiftmodule_output = ctx.actions.declare_output(uncompiled_module_info_name + SWIFTMODULE_EXTENSION, has_content_based_path = uses_content_based_paths)+ cmd.add([+ "-o",+ swiftmodule_output.as_output(),+ expanded_swiftinterface_cmd,+ ])++ ctx.actions.run(+ cmd,+ category = category,+ identifier = uncompiled_module_info_name,+ )++ return SwiftCompiledModuleInfo(+ is_framework = is_framework,+ is_sdk_module = True,+ is_swiftmodule = True,+ module_name = uncompiled_module_info_name,+ output_artifact = swiftmodule_output,+ ), swift_deps_tset++def _swift_interface_compilation_impl(ctx: AnalysisContext) -> [Promise, list[Provider]]:+ def k(sdk_deps_providers) -> list[Provider]:+ uncompiled_sdk_module_info = ctx.attrs.dep[SdkUncompiledModuleInfo]+ uncompiled_module_info_name = uncompiled_sdk_module_info.module_name+ swift_toolchain = ctx.attrs._swift_toolchain[SwiftToolchainInfo]++ expanded_swiftinterface_cmd = expand_relative_prefixed_sdk_path(+ swift_toolchain,+ uncompiled_sdk_module_info.input_relative_path,+ )++ compiled_sdk, swift_deps_tset = compile_swiftinterface_common(+ ctx,+ [],+ uncompiled_sdk_module_info.is_framework,+ uncompiled_module_info_name,+ uncompiled_sdk_module_info.partial_cmd,+ sdk_deps_providers,+ expanded_swiftinterface_cmd,+ "sdk_swiftinterface_compile",+ None,+ )++ wrapped_sdk_compiled_module_info = WrappedSdkCompiledModuleInfo(+ swift_deps = ctx.actions.tset(SwiftCompiledModuleTset, value = compiled_sdk, children = [swift_deps_tset]),+ swift_debug_info = extract_and_merge_swift_debug_infos(ctx, sdk_deps_providers, [compiled_sdk.output_artifact]),+ clang_debug_info = extract_and_merge_clang_debug_infos(ctx, sdk_deps_providers),+ )++ return [+ DefaultInfo(),+ wrapped_sdk_compiled_module_info,+ ]++ # For each swiftinterface compile its transitive clang deps with the provided target.+ module_info = ctx.attrs.dep[SdkUncompiledModuleInfo]+ clang_module_deps = get_swift_sdk_pcm_anon_targets(+ ctx,+ False,+ module_info.deps,+ ["-target", module_info.target],+ )++ # Compile the transitive swiftmodule deps.+ swift_module_deps = get_swift_interface_anon_targets(ctx, module_info.deps)++ return ctx.actions.anon_targets(clang_module_deps + swift_module_deps).promise.map(k)++_swift_interface_compilation = rule(+ impl = _swift_interface_compilation_impl,+ attrs = {+ "dep": attrs.dep(),+ "has_content_based_path": attrs.bool(),+ "_apple_tools": attrs.dep(providers = [AppleToolsInfo]),+ "_swift_toolchain": attrs.dep(),+ },+)
@@ -0,0 +1,143 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactInfoTag",+ "make_artifact_tset",+)+load(":swift_toolchain_types.bzl", "SdkUncompiledModuleInfo", "SwiftObjectFormat", "SwiftToolchainInfo")++def get_swift_toolchain_info(ctx: AnalysisContext) -> SwiftToolchainInfo:+ if hasattr(ctx.attrs, "_swift_toolchain"):+ return ctx.attrs._swift_toolchain[SwiftToolchainInfo]+ else:+ return ctx.attrs._apple_toolchain[SwiftToolchainInfo]++def get_swift_toolchain_info_dep(ctx: AnalysisContext) -> Dependency:+ if hasattr(ctx.attrs, "_swift_toolchain"):+ return ctx.attrs._swift_toolchain+ else:+ return ctx.attrs._apple_toolchain++def supports_modulemaps_with_hmaps(ctx: AnalysisContext) -> bool:+ return get_swift_toolchain_info(ctx).supports_modulemaps_with_hmaps++def include_path_for_relative_module_map_paths(ctx: AnalysisContext) -> list[str]:+ if supports_modulemaps_with_hmaps(ctx):+ # modulemap paths are relative to the modulemap file, but the compiler+ # needs search paths to be able to find the headers themselves. When+ # EmitClangHeaderWithNonModularIncludes is enabled, we need to be able+ # to resolve these paths back to something that is in a headermap. The+ # headermaps contain two forms:+ # 1. <ModuleName/HeaderName.h>+ # 2. <repo/relative/path/to/header.h>+ # We can use the latter in every case by adding the repo root as a+ # header search path for the ClangImporter when emitting ObjC headers.+ return ["-Xcc", "-I."]+ else:+ return []++def _traverse_sdk_modules_graph(+ swift_sdk_module_name_to_deps: dict[str, Dependency], clang_sdk_module_name_to_deps: dict[str, Dependency], sdk_module_dep: Dependency+):+ if SdkUncompiledModuleInfo not in sdk_module_dep:+ return++ uncompiled_sdk_module_info = sdk_module_dep[SdkUncompiledModuleInfo]++ # If input_relative_path is None then this module represents a root node of SDK modules graph.+ # In such case, we need to handle only its deps.+ if uncompiled_sdk_module_info.input_relative_path == None:+ for uncompiled_dep in uncompiled_sdk_module_info.deps:+ _traverse_sdk_modules_graph(swift_sdk_module_name_to_deps, clang_sdk_module_name_to_deps, uncompiled_dep)+ return++ # return if dep is already in dict+ if uncompiled_sdk_module_info.is_swiftmodule and uncompiled_sdk_module_info.module_name in swift_sdk_module_name_to_deps:+ return+ elif not uncompiled_sdk_module_info.is_swiftmodule and uncompiled_sdk_module_info.module_name in clang_sdk_module_name_to_deps:+ return++ for uncompiled_dep in uncompiled_sdk_module_info.deps + uncompiled_sdk_module_info.cxx_deps:+ _traverse_sdk_modules_graph(swift_sdk_module_name_to_deps, clang_sdk_module_name_to_deps, uncompiled_dep)++ if uncompiled_sdk_module_info.is_swiftmodule:+ swift_sdk_module_name_to_deps[uncompiled_sdk_module_info.module_name] = sdk_module_dep+ else:+ clang_sdk_module_name_to_deps[uncompiled_sdk_module_info.module_name] = sdk_module_dep++def compute_sdk_module_graph(sdk_module_deps: list[Dependency]) -> (dict[str, Dependency], dict[str, Dependency]):+ # All Clang's PCMs need to be compiled with cxx flags of the target that imports them,+ # because of that, we expose `dependency`s of SDK modules,+ # which might be accessed from apple_library/apple_test rules and compiled there.+ uncompiled_swift_sdk_modules_deps = {}+ uncompiled_clang_sdk_modules_deps = {}++ for sdk_module_dep in sdk_module_deps:+ _traverse_sdk_modules_graph(+ uncompiled_swift_sdk_modules_deps,+ uncompiled_clang_sdk_modules_deps,+ sdk_module_dep,+ )++ return uncompiled_swift_sdk_modules_deps, uncompiled_clang_sdk_modules_deps++def swift_toolchain_impl(ctx):+ uncompiled_swift_sdk_modules_deps, uncompiled_clang_sdk_modules_deps = compute_sdk_module_graph(ctx.attrs.sdk_modules)++ # Module map files can live in the SDK or the toolchain resource dir.+ # We need to pass through both to ensure the debuginfo target+ # materializes them.+ debug_info_artifacts = []+ if ctx.attrs.sdk_path:+ debug_info_artifacts.append(ctx.attrs.sdk_path)+ if ctx.attrs.resource_dir:+ debug_info_artifacts.append(ctx.attrs.resource_dir)++ sdk_debug_info = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ artifacts = debug_info_artifacts,+ tags = [ArtifactInfoTag("swift_debug_info")],+ )++ return [+ DefaultInfo(),+ SwiftToolchainInfo(+ architecture = ctx.attrs.architecture,+ compiler = cmd_args(ctx.attrs._swiftc_wrapper[RunInfo]).add(ctx.attrs.swiftc[RunInfo]),+ compiler_flags = ctx.attrs.swiftc_flags,+ mk_swift_comp_db = ctx.attrs.make_swift_comp_db[RunInfo],+ mk_swift_interface = cmd_args(ctx.attrs._swiftc_wrapper[RunInfo]).add(ctx.attrs.make_swift_interface[RunInfo]),+ object_format = SwiftObjectFormat(ctx.attrs.object_format) if ctx.attrs.object_format else SwiftObjectFormat("object"),+ platform_path = ctx.attrs.platform_path,+ prioritize_swift_critical_path = ctx.attrs.prioritize_swift_critical_path,+ provide_swift_debug_info = ctx.attrs.provide_swift_debug_info,+ resource_dir = ctx.attrs.resource_dir,+ sdk_module_path_prefixes = ctx.attrs.sdk_module_path_prefixes,+ sdk_path = ctx.attrs._internal_sdk_path or ctx.attrs.sdk_path,+ sdk_debug_info = sdk_debug_info,+ serialized_diags_to_json = ctx.attrs.serialized_diags_to_json[RunInfo] if ctx.attrs.serialized_diags_to_json else None,+ supports_explicit_module_debug_serialization = ctx.attrs.supports_explicit_module_debug_serialization,+ supports_incremental_file_hashing = ctx.attrs.supports_incremental_file_hashing,+ supports_modularization_dependency_graph = ctx.attrs.supports_modularization_dependency_graph,+ supports_modulemaps_with_hmaps = ctx.attrs.supports_modulemaps_with_hmaps,+ supports_relative_resource_dir = ctx.attrs.supports_relative_resource_dir,+ swift_ide_test_tool = ctx.attrs.swift_ide_test_tool[RunInfo] if ctx.attrs.swift_ide_test_tool else None,+ swift_stdlib_tool = ctx.attrs.swift_stdlib_tool[RunInfo],+ swift_stdlib_tool_flags = ctx.attrs.swift_stdlib_tool_flags,+ swift_experimental_features = ctx.attrs.swift_experimental_features,+ swift_upcoming_features = ctx.attrs.swift_upcoming_features,+ uncompiled_clang_sdk_modules_deps = uncompiled_clang_sdk_modules_deps,+ uncompiled_swift_sdk_modules_deps = uncompiled_swift_sdk_modules_deps,+ enforce_dedupe_eligibility = ctx.attrs.enforce_dedupe_eligibility,+ use_depsfiles = ctx.attrs.use_depsfiles,+ uses_content_based_paths = ctx.attrs.uses_content_based_paths,+ ),+ ]
@@ -0,0 +1,22 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++def swift_toolchain_macro_impl(swift_toolchain_rule = None, **kwargs):+ bitcode = read_root_config("swift", "bitcode")+ if bitcode != None:+ kwargs["object_format"] = "object"+ if bitcode.lower() == "true":+ kwargs["object_format"] = "bc"+ elif bitcode.lower() == "ir":+ kwargs["object_format"] = "ir"+ elif bitcode.lower() == "irgen":+ kwargs["object_format"] = "irgen"+ elif bitcode.lower() in ["embed", "embed-bitcode", "object-embed-bitcode"]:+ kwargs["object_format"] = "object-embed-bitcode"++ swift_toolchain_rule(**kwargs)
@@ -0,0 +1,198 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++#####################################################################+# Providers++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactTSet", # @unused Used as a type+)+load("@prelude//utils:arglike.bzl", "ArgLike")++SwiftObjectFormat = enum(+ "object",+ "bc",+ "ir",+ "irgen",+ "object-embed-bitcode",+)++SwiftToolchainInfo = provider(+ fields = {+ "architecture": provider_field(str),+ "compiler": provider_field(cmd_args),+ "compiler_flags": provider_field(list[ArgLike]),+ "enforce_dedupe_eligibility": provider_field(bool, default = False),+ "mk_swift_comp_db": provider_field(RunInfo),+ "mk_swift_interface": provider_field(cmd_args),+ "object_format": provider_field(SwiftObjectFormat),+ "platform_path": provider_field([Artifact, str, None]),+ # Prioritizes the Swift critical path by preferring swiftmodule emits+ # locally, disabling low-pass gating for swiftmodule and PCM actions,+ # and increasing bulk Swift object-compile weight.+ "prioritize_swift_critical_path": provider_field(bool, default = False),+ "provide_swift_debug_info": provider_field(bool, default = True),+ "resource_dir": provider_field([Artifact, None]),+ "sdk_debug_info": provider_field([ArtifactTSet, None]),+ "sdk_module_path_prefixes": provider_field(dict[str, Artifact]),+ "sdk_path": provider_field([Artifact, str, None]),+ "serialized_diags_to_json": provider_field([RunInfo, None], default = None),+ "supports_explicit_module_debug_serialization": provider_field(bool, default = False),+ "supports_incremental_file_hashing": provider_field(bool, default = False),+ # Whether swiftc supports -emit-modularization-dependency-dot-graph.+ # Only the Pika toolchain does; Xcode's swiftc errors with+ # "unknown argument", so this defaults off.+ "supports_modularization_dependency_graph": provider_field(bool, default = False),+ "supports_modulemaps_with_hmaps": provider_field(bool, default = False),+ "supports_relative_resource_dir": provider_field(bool),+ "swift_experimental_features": provider_field(dict[str, list[str]]), # { "5": [], "6", [] }+ "swift_ide_test_tool": provider_field([RunInfo, None], default = None),+ "swift_stdlib_tool": provider_field(RunInfo),+ "swift_stdlib_tool_flags": provider_field(list[ArgLike]),+ "swift_upcoming_features": provider_field(dict[str, list[str]]), # { "5": [], "6", [] }+ "uncompiled_clang_sdk_modules_deps": provider_field(dict[str, Dependency]),+ "uncompiled_swift_sdk_modules_deps": provider_field(dict[str, Dependency]),+ "use_depsfiles": provider_field(bool, default = False),+ "uses_content_based_paths": provider_field(bool, default = False),+ }+)++# A provider that represents a non-yet-compiled SDK (Swift or Clang) module,+# and doesn't contain any artifacts because Swift toolchain isn't resolved yet.+SdkUncompiledModuleInfo = provider(+ fields = {+ # [Dependency]+ "cxx_deps": provider_field(typing.Any, default = None),+ # [Dependency]+ "deps": provider_field(typing.Any, default = None),+ # A relative prefixed path to a textual swiftinterface/modulemap file within an SDK.+ "input_relative_path": provider_field(typing.Any, default = None),+ # This is mostly needed for the generated Swift module map file.+ "is_framework": provider_field(typing.Any, default = None),+ # If True then represents a swiftinterface, otherwise Clang's modulemap.+ "is_swiftmodule": provider_field(typing.Any, default = None),+ # A real name of a module, without distinguishing suffixes.+ "module_name": provider_field(typing.Any, default = None),+ # Transitive closure filtered to overlay owners and underlyings.+ "overlays_transitive_deps": provider_field(typing.Any, default = None),+ # Partial arguments, required to compile a particular SDK module.+ "partial_cmd": provider_field(typing.Any, default = None),+ # A string of the compiler target triple to use for clang module deps, eg arm64-apple-ios16.4+ "target": provider_field(typing.Any, default = None),+ }+)++WrappedSdkCompiledModuleInfo = provider(+ fields = {+ # A tset of PCM artifacts+ "clang_debug_info": provider_field(typing.Any, default = None),+ # A SwiftCompiledModuleTset of SwiftCompiledModuleInfo of transitive clang deps+ "clang_deps": provider_field(typing.Any, default = None),+ # A tset of swiftmodule artifacts+ "swift_debug_info": provider_field(typing.Any, default = None),+ # A SwiftCompiledModuleTset of SwiftCompiledModuleInfo of transitive swift deps+ "swift_deps": provider_field(typing.Any, default = None),+ }+)++SdkSwiftOverlayInfo = provider(+ fields = {+ "overlays": provider_field(typing.Any, default = None), # {str: [str]} A mapping providing a list of overlay module names for each underlying module+ }+)++SwiftCompiledModuleInfo = provider(+ fields = {+ # Additional flags for the clang importer.+ "clang_importer_args": provider_field(cmd_args | None, default = None),+ # Clang modulemap path, required for generation of swift_module_map. We use+ # cmd_args here to expand SDK relative paths.+ "clang_modulemap_path": provider_field(cmd_args | None, default = None),+ "is_framework": provider_field(bool),+ "is_sdk_module": provider_field(bool),+ # If True then contains a compiled swiftmodule, otherwise Clang's pcm.+ "is_swiftmodule": provider_field(bool),+ # A real name of a module, without distinguishing suffixes.+ "module_name": provider_field(str),+ # Compiled artifact either swiftmodule or pcm.+ "output_artifact": provider_field(Artifact),+ }+)++def clang_module_file_args(module_info: SwiftCompiledModuleInfo) -> cmd_args:+ return cmd_args(+ "-Xcc",+ cmd_args(+ "-fmodule-file=",+ module_info.module_name,+ "=",+ module_info.output_artifact,+ delimiter = "",+ ),+ "-Xcc",+ cmd_args(+ "-fmodule-map-file=",+ module_info.clang_modulemap_path,+ delimiter = "",+ ),+ )++def _add_swiftmodule_search_path(module_info: SwiftCompiledModuleInfo):+ # We need to import the containing folder, not the file itself.+ # We skip SDK modules as those are found via the -sdk flag.+ if module_info.is_swiftmodule and not module_info.is_sdk_module:+ return ["-I", cmd_args(module_info.output_artifact, parent = 1)]++ return []++def _add_clang_module_file_flags(module_info: SwiftCompiledModuleInfo):+ if module_info.is_swiftmodule:+ return []+ else:+ return [clang_module_file_args(module_info)]++def _add_clang_importer_flags(module_info: SwiftCompiledModuleInfo):+ if module_info.is_swiftmodule:+ return []+ else:+ return [module_info.clang_importer_args] if module_info.clang_importer_args else []++def _swift_module_map_struct(module_info: SwiftCompiledModuleInfo):+ if module_info.is_swiftmodule:+ # Swiftmodule files compiled from swiftinterface files embed the paths+ # which are verified during compilation of rdeps, so we need to add+ # the swiftinterface files as hidden inputs.+ module_path = cmd_args(+ module_info.output_artifact,+ delimiter = "",+ )++ return struct(+ isFramework = module_info.is_framework,+ moduleName = module_info.module_name,+ modulePath = module_path,+ )+ else:+ return struct(+ isFramework = module_info.is_framework,+ moduleName = module_info.module_name,+ clangModulePath = module_info.output_artifact,+ clangModuleMapPath = cmd_args(module_info.clang_modulemap_path, delimiter = ""),+ )++SwiftCompiledModuleTset = transitive_set(+ args_projections = {+ "clang_importer_flags": _add_clang_importer_flags, # Additional clang flags required for compilation.+ "clang_module_file_flags": _add_clang_module_file_flags, # Projects pcm modules as cli flags.+ "module_search_path": _add_swiftmodule_search_path,+ },+ json_projections = {+ "swift_module_map": _swift_module_map_struct,+ },+)
@@ -0,0 +1,75 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactTSet", # @unused Used as a type+)+load(":swift_toolchain_types.bzl", "SwiftCompiledModuleTset")++SWIFT_EXTENSION = ".swift"++SWIFTMODULE_EXTENSION = ".swiftmodule"++# Base action categories for Swift compiles. When explicit modules are enabled,+# EXPLICIT_MODULES_CATEGORY_SUFFIX is appended (see swift_compilation.bzl).+SWIFT_COMPILE_CATEGORY = "swift_compile"++SWIFTMODULE_COMPILE_CATEGORY = "swiftmodule_compile"++EXPLICIT_MODULES_CATEGORY_SUFFIX = "_with_explicit_mods"++SwiftCompilationModes = ("wmo", "incremental", "auto")++SwiftMacroPlugin = plugins.kind()++SwiftVersion = ("5", "6")++SwiftDependencyInfo = provider(+ fields = {+ "debug_info_tset": provider_field(ArtifactTSet),+ # Includes modules through exported_deps, used for compilation+ "exported_swiftmodules": provider_field(SwiftCompiledModuleTset),+ # If this target has exported_headers, used to validate non-modular dep exports+ "has_exported_headers": provider_field(bool),+ # Macro deps cannot be mixed with apple_library deps+ "is_macro": provider_field(bool),+ # If this target provides a clang module, used to validate non-modular dep exports+ "is_modular": provider_field(bool),+ # Tset of this target's own `-dump-ast` output directory (see the `[ast]`+ # subtarget) merged with the same tset from all deps.+ "swift_ast_dump_tset": provider_field(ArtifactTSet),+ # Tset of this target's own `.swiftmodule` output merged with the+ # same tsets from all deps.+ "swiftmodule_change_analysis_tset": provider_field(ArtifactTSet),+ }+)++def _swift_framework_implicit_search_paths_args(args: cmd_args):+ return args++FrameworkImplicitSearchPathInfoTSet = transitive_set(+ args_projections = {+ "swift_framework_implicit_search_paths_args": _swift_framework_implicit_search_paths_args,+ },+)++FrameworkImplicitSearchPathInfo = provider(+ fields = {+ "tset": provider_field(typing.Any, default = None), # A tset of FrameworkImplicitSearchPathInfoTSet+ }+)++def get_implicit_framework_search_path_providers(ctx: AnalysisContext, value: [cmd_args, None], deps: list[Dependency]) -> FrameworkImplicitSearchPathInfoTSet:+ deps_infos = [+ d[FrameworkImplicitSearchPathInfo].tset for d in deps if FrameworkImplicitSearchPathInfo in d and d[FrameworkImplicitSearchPathInfo].tset != None+ ]+ if value:+ return ctx.actions.tset(FrameworkImplicitSearchPathInfoTSet, value = value, children = deps_infos)+ else:+ return ctx.actions.tset(FrameworkImplicitSearchPathInfoTSet, children = deps_infos)
@@ -0,0 +1,150 @@+# @noautodeps+load("@prelude//utils:source_listing.bzl", "source_listing")+load(":defs.bzl", "apple_oso_scrubber_target", "bundle_telemetry_logger_target", "swiftmodule_change_analysis_target")++oncall("build_infra")++source_listing()++apple_tools(+ name = "apple-tools",+ adhoc_codesign_tool = None, # @oss-enable+ # @oss-disable[end= ]: adhoc_codesign_tool = "prelude//apple/tools/meta_only/codesign_rust:adhoc-signer",+ assemble_bundle = "prelude//apple/tools/bundling:assemble_bundle",+ bundle_telemetry_logger = bundle_telemetry_logger_target(),+ codesign_manifest_tree_postprocessor = "prelude//apple/tools/codesign_manifest_tree_postprocessor:codesign_manifest_tree_postprocessor",+ dedupe_swift_module_map = ":dedupe_swift_module_map",+ dry_codesign_tool = ":dry_codesign_tool",+ framework_sanitizer = ":framework_sanitizer",+ info_plist_processor = "prelude//apple/tools/info_plist_processor:tool",+ ipa_package_maker = ":ipa_package_maker",+ make_modulemap = ":make_modulemap",+ make_vfsoverlay = ":make_vfsoverlay",+ provisioning_manifest = "prelude//apple/tools/bundling:provisioning_manifest",+ resolve_signing_context = "prelude//apple/tools/bundling:resolve_signing_context",+ selective_debugging_scrubber = apple_oso_scrubber_target(),+ signing_context_tree_postprocessor = "prelude//apple/tools/signing_context_tree_postprocessor:signing_context_tree_postprocessor",+ signing_info = "prelude//apple/tools/bundling:signing_info",+ split_arch_combine_dsym_bundles_tool = ":split_arch_combine_dsym_bundles_tool",+ spm_packager = ":spm_packager",+ static_archive_linker = ":static_archive_linker",+ swiftmodule_change_analysis = swiftmodule_change_analysis_target(),+ visibility = ["PUBLIC"],+ xcframework_maker = ":xcframework_maker",+)++python_binary(+ name = "framework_sanitizer",+ main = "framework_sanitizer.py",+ visibility = ["PUBLIC"],+)++python_binary(+ name = "xcframework_maker",+ main = "xcframework_maker.py",+ visibility = ["PUBLIC"],+)++python_binary(+ name = "dry_codesign_tool",+ main = "dry_codesign_tool.py",+ visibility = ["PUBLIC"],+)++python_binary(+ name = "ipa_package_maker",+ main = "ipa_package_maker.py",+ visibility = ["PUBLIC"],+ deps = [+ "prelude//apple/tools/re_compatibility_utils:re_compatibility_utils",+ ],+)++python_bootstrap_binary(+ name = "dedupe_swift_module_map",+ main = "dedupe_swift_module_map.py",+ visibility = ["PUBLIC"],+)++python_bootstrap_binary(+ name = "make_modulemap",+ main = "make_modulemap.py",+ visibility = ["PUBLIC"],+)++python_bootstrap_binary(+ name = "make_swift_comp_db",+ main = "make_swift_comp_db.py",+ visibility = ["PUBLIC"],+)++python_bootstrap_binary(+ name = "make_swift_interface",+ main = "make_swift_interface.py",+ visibility = ["PUBLIC"],+)++python_bootstrap_binary(+ name = "make_vfsoverlay",+ main = "make_vfsoverlay.py",+ visibility = ["PUBLIC"],+)++python_library(+ name = "plistlib_utils",+ srcs = ["plistlib_utils.py"],+ visibility = ["PUBLIC"],+)++python_binary(+ name = "split_arch_combine_dsym_bundles_tool",+ main = "split_arch_combine_dsym_bundles_tool.py",+ visibility = ["PUBLIC"],+)++python_bootstrap_binary(+ name = "swift_exec",+ has_content_based_path = True,+ main = "swift_exec.py",+ visibility = ["PUBLIC"],+ deps = ["prelude//apple/tools/re_compatibility_utils:bootstrap_re_compatibility_utils"],+)++python_binary(+ name = "static_archive_linker",+ main = "static_archive_linker.py",+ visibility = ["PUBLIC"],+)++python_binary(+ name = "spm_packager",+ main = "spm_packager.py",+ visibility = ["PUBLIC"],+)++export_file(+ name = "empty.c",+ visibility = ["PUBLIC"],+)++# Type checking target for Python tool scripts+python_library(+ name = "scripts-typing",+ srcs = [+ "dedupe_swift_module_map.py",+ "dry_codesign_tool.py",+ "framework_sanitizer.py",+ "ipa_package_maker.py",+ "make_modulemap.py",+ "make_swift_comp_db.py",+ "make_swift_interface.py",+ "make_vfsoverlay.py",+ "plistlib_utils.py",+ "split_arch_combine_dsym_bundles_tool.py",+ "spm_packager.py",+ "static_archive_linker.py",+ "swift_exec.py",+ "xcframework_maker.py",+ ],+ typing = True,+)
@@ -0,0 +1,83 @@+load("@prelude//apple/tools:defs.bzl", "meta_python_test")+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("build_infra")++source_listing()++python_binary(+ name = "assemble_bundle",+ main = "main.py",+ visibility = ["PUBLIC"],+ deps = [+ "prelude//apple/tools/code_signing:lib",+ "prelude//apple/tools/re_compatibility_utils:re_compatibility_utils",+ ":lib",+ ],+)++python_binary(+ name = "provisioning_manifest",+ main = "provisioning_manifest_main.py",+ visibility = ["PUBLIC"],+ deps = [+ ":lib",+ ],+)++python_binary(+ name = "resolve_signing_context",+ main = "resolve_signing_context_main.py",+ visibility = ["PUBLIC"],+ deps = [+ ":lib",+ ],+)++python_binary(+ name = "signing_info",+ main = "signing_info_main.py",+ visibility = ["PUBLIC"],+ deps = [+ ":lib",+ ],+)++python_library(+ name = "scripts-typing",+ srcs = [+ "resolve_signing_context_main.py",+ "signing_info_main.py",+ ],+ typing = True,+ deps = [":lib"],+)++python_library(+ name = "lib",+ srcs = glob(+ [+ "*.py",+ ],+ exclude = [+ "*_test.py",+ "*main.py",+ ],+ ),+ deps = [+ "prelude//apple/tools/code_signing:lib",+ "prelude//apple/tools/re_compatibility_utils:re_compatibility_utils",+ ],+)++meta_python_test(+ name = "bundling_test",+ srcs = glob(["*_test.py"]),+ resources = glob([+ "test_resources/*",+ ]),+ deps = [+ "fbsource//third-party/pypi/setuptools:setuptools",+ ":lib",+ ],+)
@@ -0,0 +1,78 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import json+import os+from dataclasses import dataclass+from io import TextIOBase+from pathlib import Path+from typing import Any, Dict, List, Optional, Union++_METADATA_VERSION = 1+++@dataclass+class _Item:+ path: Path+ digest: str+++@dataclass+class _Metadata:+ version: int+ digests: List[_Item]+++def _object_hook(dict: Dict[str, Any]) -> Union[_Item, _Metadata]:+ if "version" in dict:+ return _Metadata(**dict)+ else:+ dict["path"] = Path(dict.pop("path"))+ return _Item(**dict)+++def parse_action_metadata(data: TextIOBase) -> Optional[Dict[Path, str]]:+ """+ Returns:+ Mapping from project relative path to hash digest for every file present action metadata.+ """+ start_stream_position = data.tell()+ try:+ metadata = json.load(data, object_hook=_object_hook)+ except BaseException:+ data.seek(start_stream_position)+ version = json.load(data)["version"]+ if version != _METADATA_VERSION:+ raise RuntimeError(+ f"Expected metadata version to be `{_METADATA_VERSION}` got `{version}`."+ )+ else:+ raise+ return {item.path: item.digest for item in metadata.digests}+++def action_metadata_if_present(+ environment_variable_key: str,+) -> Optional[Dict[Path, str]]:+ """+ Returns:+ Mapping from project relative path to hash digest for every file present action metadata.+ """+ environment_variable = os.getenv(environment_variable_key)+ if environment_variable is None:+ return None+ path = Path(environment_variable)+ if not path.exists():+ raise RuntimeError(+ "Expected file with action metadata to exist given related environment variable is set."+ )+ else:+ with path.open() as f:+ return parse_action_metadata(f)
@@ -0,0 +1,48 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import importlib.resources+import unittest+from json import JSONDecodeError+from pathlib import Path++from .action_metadata import parse_action_metadata+++class TestActionMetadata(unittest.TestCase):+ def _resource_content(self, filename):+ resources = importlib.resources.files(__package__) / "test_resources"+ return resources / filename++ def test_valid_metadata_is_parsed_successfully(self):+ path = self._resource_content("valid_action_metadata.json")+ with path.open() as file_content:+ result = parse_action_metadata(file_content)+ self.assertEqual(+ result,+ {+ Path("repo/foo.txt"): "foo_digest",+ Path("buck-out/bar.txt"): "bar_digest",+ },+ )++ def test_error_when_invalid_metadata(self):+ path = self._resource_content("the.broken_json")+ with self.assertRaises(JSONDecodeError):+ with path.open() as file_content:+ _ = parse_action_metadata(file_content)++ def test_user_friendly_error_when_metadata_with_newer_version(self):+ path = self._resource_content("newer_version_action_metadata.json")+ with self.assertRaises(Exception) as context:+ with path.open() as file_content:+ _ = parse_action_metadata(file_content)+ self.assertEqual(+ context.exception,+ RuntimeError("Expected metadata version to be `1` got `2`."),+ )
@@ -0,0 +1,277 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import filecmp+import logging+import os+import shutil+from pathlib import Path+from typing import Any, cast, Dict, List, Optional++from .assemble_bundle_types import BundleSpecItem, IncrementalContext+from .incremental_state import IncrementalState, IncrementalStateItem+from .incremental_utils import (+ calculate_incremental_state,+ should_assemble_incrementally,+)++_LOGGER: logging.Logger = logging.getLogger(__name__)+++def assemble_bundle(+ spec: List[BundleSpecItem],+ bundle_path: Path,+ incremental_context: Optional[IncrementalContext],+ check_conflicts: bool,+ versioned_if_macos: bool,+) -> Optional[List[IncrementalStateItem]]:+ incremental_result = None+ if incremental_context:+ if should_assemble_incrementally(spec, incremental_context):+ incremental_result = _assemble_incrementally(+ bundle_path,+ spec,+ incremental_context.metadata,+ cast(IncrementalState, incremental_context.state),+ check_conflicts,+ versioned_if_macos,+ )+ else:+ _assemble_non_incrementally(+ bundle_path, spec, check_conflicts, versioned_if_macos+ )+ incremental_result = calculate_incremental_state(+ spec, incremental_context.metadata+ )+ else:+ _assemble_non_incrementally(+ bundle_path, spec, check_conflicts, versioned_if_macos+ )++ # External tooling (e.g., Xcode) might depend on the timestamp of the bundle+ bundle_path.touch()++ return incremental_result+++def _cleanup_output(incremental: bool, path: Path) -> None:+ if not incremental and path.exists():+ shutil.rmtree(path)+ path.mkdir(parents=True, exist_ok=True)+++def _assemble_non_incrementally(+ bundle_path: Path,+ spec: List[BundleSpecItem],+ check_conflicts: bool,+ versioned_if_macos: bool,+) -> None:+ _LOGGER.info("Assembling bundle non-incrementally.")+ _cleanup_output(incremental=False, path=bundle_path)++ copied_contents: Dict[Path, str] = {}++ def _copy(src: str, dst: Path, **kwargs: Any) -> None:+ if check_conflicts:+ if dst in copied_contents:+ if filecmp.cmp(src, str(dst), shallow=False):+ _LOGGER.info(+ f"Found a conflict for destination `{os.path.relpath(dst, bundle_path)}` but the files are identical. Treating as a non-conflict as this can normally happen for universal builds."+ )+ return++ raise RuntimeError(+ f"Found a conflict for destination `{os.path.relpath(dst, bundle_path)}`: `{src}` conflicts with `{copied_contents[dst]}`"+ )+ shutil.copy2(src, dst, follow_symlinks=False)+ if check_conflicts:+ copied_contents[dst] = src++ symlinks = set()++ for spec_item in spec:+ source_path = spec_item.src+ destination_path = bundle_path / spec_item.dst++ destination_path.parent.mkdir(parents=True, exist_ok=True)+ if spec_item.dst.startswith("Versions/A") and versioned_if_macos:+ parts = Path(spec_item.dst).parts+ if len(parts) <= 2:+ raise RuntimeError(+ "Versioned bundles cannot be created from a single copy directly to Versions/A"+ )+ symlinks.add(parts[2])++ if os.path.isdir(source_path):+ shutil.copytree(+ source_path,+ destination_path,+ symlinks=True,+ dirs_exist_ok=True,+ copy_function=_copy,+ )+ else:+ _copy(source_path, destination_path)++ _create_symlinks(symlinks, bundle_path)+++def _create_symlinks(symlinks: set[str], bundle_path: Path) -> None:+ if symlinks and not Path.exists(bundle_path / "Versions/Current"):+ os.symlink("A", bundle_path / "Versions/Current")+ for dir_to_link in symlinks:+ if not Path.exists(bundle_path / dir_to_link):+ os.symlink("Versions/Current/" + dir_to_link, bundle_path / dir_to_link)+++def _assemble_incrementally(+ bundle_path: Path,+ spec: List[BundleSpecItem],+ action_metadata: Dict[Path, str],+ incremental_state: IncrementalState,+ check_conflicts: bool,+ versioned_if_macos: bool,+) -> List[IncrementalStateItem]:+ _LOGGER.info("Assembling bundle incrementally.")+ _cleanup_output(incremental=True, path=bundle_path)+ _delete_swift_stdlib_files(bundle_path, incremental_state.swift_stdlib_paths)+ paths_to_delete = {+ i.destination_relative_to_bundle for i in incremental_state.items+ }+ old_digests = {+ item.destination_relative_to_bundle: item.digest+ for item in incremental_state.items+ if item.digest is not None+ }+ old_symlink_destinations = {+ item.destination_relative_to_bundle: item.resolved_symlink+ for item in incremental_state.items+ if item.resolved_symlink is not None+ }++ new_incremental_state = calculate_incremental_state(spec, action_metadata)++ if check_conflicts:+ _check_path_conflicts(new_incremental_state)++ # Still need to run filtering even when check_conflicts is set, for removing the conflicts with same files+ new_incremental_state = _filter_conflicting_paths(new_incremental_state)++ new_symlinks = set()+ versioned_subdir = Path("Versions/A")++ for item in new_incremental_state:+ # Added file might not be present in old result, need to check first.+ dst = item.destination_relative_to_bundle+ if dst in paths_to_delete:+ paths_to_delete.remove(dst)+ project_relative_dst = bundle_path / dst+ if item.digest is not None:+ new_digest = item.digest+ old_digest = old_digests.get(dst, None)+ is_changed = new_digest != old_digest+ else:+ assert item.resolved_symlink is not None, (+ "Expected item to represent a symlink when digest is missing"+ )+ new_resolved_symlink = item.resolved_symlink+ old_resolved_symlink = old_symlink_destinations.get(dst, None)+ is_changed = new_resolved_symlink != old_resolved_symlink+ if is_changed:+ project_relative_dst.unlink()+ if is_changed:+ _LOGGER.debug(+ f"Bundle item at path `{dst}` changed, updating with `{item.source}`."+ )+ project_relative_dst.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(item.source, project_relative_dst, follow_symlinks=False)+ if Path(dst).is_relative_to(versioned_subdir):+ symlink = Path(dst).relative_to(versioned_subdir).parts[0]+ new_symlinks.add(symlink)++ if versioned_if_macos:+ _create_symlinks(new_symlinks, bundle_path)++ for path in paths_to_delete:+ (bundle_path / path).unlink()++ _cleanup_empty_redundant_directories(+ bundle_path, incremental_state.items, new_incremental_state+ )++ return new_incremental_state+++def _check_path_conflicts(incremental_state: List[IncrementalStateItem]) -> None:+ """+ Throws an exception if there are multiple items with the same destination path, and those are different files.+ """+ checked = {}+ for item in incremental_state:+ dst = item.destination_relative_to_bundle+ if dst in checked:+ if item.digest != checked[dst].digest:+ raise RuntimeError(+ f"Found a conflict for destination `{dst}`: `{item.source}` conflicts with `{checked[dst].source}`"+ )+ else:+ _LOGGER.info(+ f"Found a conflict for destination `{dst}` but the files are identical. Treating as a non-conflict as this can normally happen for universal builds."+ )+ checked[dst] = item+++def _filter_conflicting_paths(+ incremental_state: List[IncrementalStateItem],+) -> List[IncrementalStateItem]:+ """+ Filter out conflicting paths leaving only the last item from the conflicting items. That practically means that the last item overrides all other conflicting items which makes:+ 1) incremental build deterministic even when there are multiple conflicting destination paths+ 2) bundling result has the same structure as in Buck1 even when there are multiple conflicting destination paths+ WARNING: This logic is tightly coupled with how spec items are sorted in `assemble_bundle` method. Don't change unless you fully understand what is going on here.+ """+ result = {}+ for item in incremental_state:+ dst = item.destination_relative_to_bundle+ # Keep the same ordering of elements as in incremental state.+ # That means we don't just overwrite the item for existing key, but need to delete it first.+ if dst in result:+ result.pop(dst)+ result[dst] = item+ return list(result.values())+++def _delete_swift_stdlib_files(+ bundle_path: Path, swift_stdlib_paths: List[Path]+) -> None:+ for p in swift_stdlib_paths:+ path = bundle_path / p+ if path.is_dir():+ shutil.rmtree(path)+ else:+ path.unlink(missing_ok=True)+++def _cleanup_empty_redundant_directories(+ bundle_path: Path,+ old_state: List[IncrementalStateItem],+ new_state: List[IncrementalStateItem],+) -> None:+ old_directories = {+ p for item in old_state for p in item.destination_relative_to_bundle.parents+ }+ new_directories = {+ p for item in new_state for p in item.destination_relative_to_bundle.parents+ }+ versioned_subdir = Path("Versions/A")+ for redundant_directory in old_directories - new_directories:+ shutil.rmtree(bundle_path / redundant_directory, ignore_errors=True)+ if redundant_directory.parent == versioned_subdir:+ Path.unlink(bundle_path / redundant_directory.name)
@@ -0,0 +1,123 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++from __future__ import annotations++import functools+from dataclasses import dataclass+from pathlib import Path+from typing import Dict, List, Optional++from apple.tools.code_signing.codesign_bundle import CodesignConfiguration++from .incremental_state import IncrementalState+++@functools.total_ordering+@dataclass+class BundleSpecItem:+ src: str+ # Should be bundle relative path, empty string means the root of the bundle+ dst: str+ codesign_on_copy: bool = False+ codesign_entitlements: Optional[str] = None+ codesign_flags_override: Optional[List[str]] = None+ extra_codesign_paths: Optional[List[str]] = None++ def __eq__(self: BundleSpecItem, other: Optional[BundleSpecItem]) -> bool:+ return (+ other is not None+ and self.src == other.src+ and self.dst == other.dst+ and self.codesign_on_copy == other.codesign_on_copy+ and self.codesign_entitlements == other.codesign_entitlements+ and self.codesign_flags_override == other.codesign_flags_override+ and self.extra_codesign_paths == other.extra_codesign_paths+ )++ def __ne__(self: BundleSpecItem, other: BundleSpecItem) -> bool:+ return not self.__eq__(other)++ def __hash__(self: BundleSpecItem) -> int:+ return hash(+ (+ self.src,+ self.dst,+ self.codesign_on_copy,+ self.codesign_entitlements,+ (+ tuple(self.codesign_flags_override)+ if self.codesign_flags_override is not None+ else hash(None)+ ),+ (+ tuple(self.extra_codesign_paths)+ if self.extra_codesign_paths is not None+ else hash(None)+ ),+ )+ )++ def __lt__(self: BundleSpecItem, other: BundleSpecItem) -> bool:+ return (+ self.src < other.src+ or self.dst < other.dst+ or self.codesign_on_copy < other.codesign_on_copy+ or (+ self.codesign_entitlements < other.codesign_entitlements+ if (+ self.codesign_entitlements is not None+ and other.codesign_entitlements is not None+ )+ else (+ self.codesign_entitlements is None+ and other.codesign_entitlements is not None+ )+ )+ or (+ self.codesign_flags_override < other.codesign_flags_override+ if (+ self.codesign_flags_override is not None+ and other.codesign_flags_override is not None+ )+ else (+ self.codesign_flags_override is None+ and other.codesign_flags_override is not None+ )+ )+ or (+ self.extra_codesign_paths < other.extra_codesign_paths+ if (+ self.extra_codesign_paths is not None+ and other.extra_codesign_paths is not None+ )+ else (+ self.extra_codesign_paths is None+ and other.extra_codesign_paths is not None+ )+ )+ )+++@dataclass+class IncrementalContext:+ """+ Additional data you need to bundle incrementally (extra vs when non-incrementally).+ """++ # Maps buck-project relative path to hash digest of the input file.+ metadata: Dict[Path, str]+ # Present when there is a valid incremental state on disk (i.e. previous build produced it).+ state: Optional[IncrementalState]+ codesigned: bool+ codesign_configuration: Optional[CodesignConfiguration]+ codesign_identity: Optional[str]+ codesign_arguments: List[str]+ versioned_if_macos: bool
@@ -0,0 +1,178 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++from __future__ import annotations++import json+from dataclasses import dataclass+from io import TextIOBase+from pathlib import Path+from typing import Any, Dict, List, Optional, Union++from apple.tools.code_signing.codesign_bundle import CodesignConfiguration++_VERSION = 8+++@dataclass+class IncrementalStateItem:+ source: Path+ """+ Path relative to buck project+ """+ destination_relative_to_bundle: Path+ digest: Optional[str]+ """+ Required when the source file is not a symlink+ """+ resolved_symlink: Optional[Path]+ """+ Required when the source file is a symlink+ """+++@dataclass+class CodesignedOnCopy:+ path: Path+ """+ Path relative to bundle root which needs to be codesigned+ """+ entitlements_digest: Optional[str]+ """+ Digest of entitlements used when the given path is codesigned on copy+ """+ codesign_flags_override: Optional[List[str]]+ """+ If present, overrides codesign arguments (which are used for root bundle) when the given path is codesigned on copy+ """+ extra_codesign_paths: Optional[List[str]]+ """+ If present, a list of extra paths to be codesigned on copy+ """++ def __hash__(self: CodesignedOnCopy) -> int:+ return hash(+ (+ self.path,+ self.entitlements_digest,+ (+ tuple(self.codesign_flags_override)+ if self.codesign_flags_override is not None+ else hash(None)+ ),+ (+ tuple(self.extra_codesign_paths)+ if self.extra_codesign_paths is not None+ else hash(None)+ ),+ )+ )+++@dataclass+class IncrementalState:+ """+ Describes a bundle output from a previous run of this bundling script.+ """++ items: List[IncrementalStateItem]+ codesigned: bool+ codesign_configuration: CodesignConfiguration+ codesigned_on_copy: List[CodesignedOnCopy]+ codesign_identity: Optional[str]+ codesign_arguments: List[str]+ swift_stdlib_paths: List[Path]+ versioned_if_macos: bool+ version: int = _VERSION+++class IncrementalStateJSONEncoder(json.JSONEncoder):+ def default(self, o: object) -> object:+ if isinstance(o, IncrementalState):+ return {+ "items": [self.default(i) for i in o.items],+ "codesigned": o.codesigned,+ "codesign_configuration": (+ o.codesign_configuration.value if o.codesign_configuration else None+ ),+ "codesigned_on_copy": [self.default(i) for i in o.codesigned_on_copy],+ "codesign_identity": o.codesign_identity,+ "swift_stdlib_paths": [str(p) for p in o.swift_stdlib_paths],+ "version": o.version,+ "codesign_arguments": o.codesign_arguments,+ "versioned_if_macos": o.versioned_if_macos,+ }+ elif isinstance(o, IncrementalStateItem):+ result = {+ "source": str(o.source),+ "destination_relative_to_bundle": str(o.destination_relative_to_bundle),+ }+ if o.digest is not None:+ result["digest"] = o.digest+ if o.resolved_symlink is not None:+ result["resolved_symlink"] = str(o.resolved_symlink)+ return result+ elif isinstance(o, CodesignedOnCopy):+ result = {}+ result["path"] = str(o.path)+ if o.entitlements_digest is not None:+ result["entitlements_digest"] = str(o.entitlements_digest)+ if o.codesign_flags_override is not None:+ result["codesign_flags_override"] = o.codesign_flags_override+ if o.extra_codesign_paths is not None:+ result["extra_codesign_paths"] = o.extra_codesign_paths+ return result+ else:+ return super().default(o)+++def _object_hook(+ dict: Dict[str, Any],+) -> Union[IncrementalState, IncrementalStateItem, CodesignedOnCopy]:+ if "version" in dict:+ codesign_configuration = dict.pop("codesign_configuration")+ dict["codesign_configuration"] = (+ CodesignConfiguration(codesign_configuration)+ if codesign_configuration+ else None+ )+ dict["swift_stdlib_paths"] = [Path(p) for p in dict.pop("swift_stdlib_paths")]+ return IncrementalState(**dict)+ elif "destination_relative_to_bundle" in dict:+ dict["source"] = Path(dict.pop("source"))+ dict["destination_relative_to_bundle"] = Path(+ dict.pop("destination_relative_to_bundle")+ )+ dict["digest"] = dict.pop("digest", None)+ resolved_symlink = dict.pop("resolved_symlink", None)+ dict["resolved_symlink"] = Path(resolved_symlink) if resolved_symlink else None+ return IncrementalStateItem(**dict)+ else:+ dict["path"] = Path(dict.pop("path"))+ dict["entitlements_digest"] = dict.pop("entitlements_digest", None)+ dict["codesign_flags_override"] = dict.pop("codesign_flags_override", None)+ dict["extra_codesign_paths"] = dict.pop("extra_codesign_paths", None)+ return CodesignedOnCopy(**dict)+++def parse_incremental_state(data: TextIOBase) -> IncrementalState:+ start_stream_position = data.tell()+ try:+ incremental_state = json.load(data, object_hook=_object_hook)+ except BaseException:+ data.seek(start_stream_position)+ version = json.load(data)["version"]+ if version != _VERSION:+ raise RuntimeError(+ f"Expected incremental state version to be `{_VERSION}` got `{version}`."+ )+ else:+ raise+ return incremental_state
@@ -0,0 +1,167 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import importlib.resources+import io+import json+import unittest+from pathlib import Path++from .incremental_state import (+ CodesignedOnCopy,+ IncrementalState,+ IncrementalStateItem,+ IncrementalStateJSONEncoder,+ parse_incremental_state,+)+++class TestIncrementalState(unittest.TestCase):+ def test_state_serialization_and_deserialization(self):+ expected = IncrementalState(+ items=[+ IncrementalStateItem(+ source=Path("repo/foo.txt"),+ destination_relative_to_bundle=Path("foo.txt"),+ digest="foo_digest",+ resolved_symlink=None,+ ),+ IncrementalStateItem(+ source=Path("buck-out/bar.txt"),+ destination_relative_to_bundle=Path("Resources/bar.txt"),+ digest="bar_digest",+ resolved_symlink=None,+ ),+ ],+ codesigned=True,+ codesign_configuration=None,+ codesigned_on_copy=[+ CodesignedOnCopy(+ path=Path("Resources/bar.txt"),+ entitlements_digest=None,+ codesign_flags_override=None,+ extra_codesign_paths=None,+ ),+ CodesignedOnCopy(+ path=Path("Resources/baz.txt"),+ entitlements_digest="abc",+ codesign_flags_override=None,+ extra_codesign_paths=None,+ ),+ CodesignedOnCopy(+ path=Path("Resources/qux.txt"),+ entitlements_digest=None,+ codesign_flags_override=["--deep", "--force"],+ extra_codesign_paths=None,+ ),+ CodesignedOnCopy(+ path=Path("Resources/Parent.framework"),+ entitlements_digest=None,+ codesign_flags_override=None,+ extra_codesign_paths=["Frameworks/Base.framework"],+ ),+ ],+ codesign_identity="Johnny Appleseed",+ codesign_arguments=[+ "--force",+ ],+ swift_stdlib_paths=[Path("Frameworks/libswiftCore.dylib")],+ versioned_if_macos=False,+ )+ json_result = json.dumps(expected, cls=IncrementalStateJSONEncoder)+ result = parse_incremental_state(io.StringIO(json_result))+ self.assertEqual(+ result,+ expected,+ )++ def _resource_content(self, filename):+ resources = importlib.resources.files(__package__) / "test_resources"+ return resources / filename++ def test_valid_state_is_parsed_successfully(self):+ path = self._resource_content("valid_incremental_state.json")+ with path.open() as file_content:+ result = parse_incremental_state(file_content)+ expected = IncrementalState(+ items=[+ IncrementalStateItem(+ source=Path("repo/foo.txt"),+ destination_relative_to_bundle=Path("foo.txt"),+ digest="foo_digest",+ resolved_symlink=None,+ ),+ IncrementalStateItem(+ source=Path("buck-out/bar.txt"),+ destination_relative_to_bundle=Path("Resources/bar.txt"),+ digest="bar_digest",+ resolved_symlink=None,+ ),+ IncrementalStateItem(+ source=Path("buck-out/bar"),+ destination_relative_to_bundle=Path("Resources/bar"),+ digest=None,+ resolved_symlink=Path("bar.txt"),+ ),+ ],+ codesigned=True,+ codesign_configuration=None,+ codesigned_on_copy=[+ CodesignedOnCopy(+ path=Path("Resources/bar.txt"),+ entitlements_digest=None,+ codesign_flags_override=None,+ extra_codesign_paths=None,+ ),+ CodesignedOnCopy(+ path=Path("Resources/baz.txt"),+ entitlements_digest="abc",+ codesign_flags_override=None,+ extra_codesign_paths=None,+ ),+ CodesignedOnCopy(+ path=Path("Resources/qux.txt"),+ entitlements_digest=None,+ codesign_flags_override=["--deep", "--force"],+ extra_codesign_paths=None,+ ),+ CodesignedOnCopy(+ path=Path("Resources/Parent.framework"),+ entitlements_digest=None,+ codesign_flags_override=None,+ extra_codesign_paths=["Frameworks/Base.framework"],+ ),+ ],+ codesign_identity="Johny Appleseed",+ codesign_arguments=[+ "--force",+ "--deep",+ ],+ swift_stdlib_paths=[Path("Frameworks/libswiftCore.dylib")],+ versioned_if_macos=True,+ )+ self.assertEqual(+ result,+ expected,+ )++ def test_error_when_invalid_metadata(self):+ path = self._resource_content("the.broken_json")+ with self.assertRaises(json.JSONDecodeError):+ with path.open() as file_content:+ _ = parse_incremental_state(file_content)++ def test_user_friendly_error_when_metadata_with_newer_version(self):+ path = self._resource_content("newer_version_incremental_state.json")+ with self.assertRaises(Exception) as context:+ with path.open() as file_content:+ _ = parse_incremental_state(file_content)+ self.assertEqual(+ context.exception,+ RuntimeError("Expected incremental state version to be `2` got `3`."),+ )
@@ -0,0 +1,251 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import hashlib+import logging+import os+from pathlib import Path+from typing import Dict, List, Optional, Set, Tuple++from .assemble_bundle_types import BundleSpecItem, IncrementalContext+from .incremental_state import CodesignedOnCopy, IncrementalStateItem++FILES_TO_BE_IGNORED: Set[str] = {+ # Storage of Finder settings, which shouldn't be added when enumerating files from sources+ ".DS_Store",+}+++def should_assemble_incrementally(+ spec: List[BundleSpecItem], incremental_context: IncrementalContext+) -> bool:+ previous_run_state = incremental_context.state+ if previous_run_state is None:+ logging.getLogger(__name__).info(+ "Decided not to assemble incrementally — no incremental state for previous build."+ )+ return False+ if previous_run_state.versioned_if_macos != incremental_context.versioned_if_macos:+ logging.getLogger(__name__).info(+ "Decided not to assemble incrementally — current build and previous build have different versioned_if_macos settings."+ )+ return False++ previously_codesigned = previous_run_state.codesigned+ # If previously bundle was not code signed there should be no problems with code signing+ # currently in incremental mode. Existing binaries could be code signed "on+ # top" if that's needed.+ if not previously_codesigned:+ logging.getLogger(__name__).info(+ "Decided to assemble incrementally — previous build is not codesigned."+ )+ return True+ # For simplicity and correctness purposes instead of stripping code signatures we+ # perform non-incremental run.+ if not incremental_context.codesigned:+ logging.getLogger(__name__).info(+ "Decided not to assemble incrementally — current build is not codesigned, while previous build is codesigned."+ )+ return False+ # If previous identity is different from the current one also perform non-incremental run.+ if previous_run_state.codesign_identity != incremental_context.codesign_identity:+ logging.getLogger(__name__).info(+ "Decided not to assemble incrementally — previous vs current builds have mismatching codesigning identities."+ )+ return False+ # If previous codesign arguments are different from the current ones also perform non-incremental run.+ if previous_run_state.codesign_arguments != incremental_context.codesign_arguments:+ logging.getLogger(__name__).info(+ "Decided not to assemble incrementally — previous vs current builds have mismatching codesigning arguments."+ )+ return False+ # If bundle from previous run was signed in a different configuration vs the current run (e.g. dry code signed while now regular code signing is required) perform non-incremental run.+ if (+ previous_run_state.codesign_configuration+ != incremental_context.codesign_configuration+ ):+ logging.getLogger(__name__).info(+ "Decided not to assemble incrementally — previous vs current builds have mismatching codesigning configurations."+ )+ return False+ # If there is an artifact that was code signed on copy in previous run which is+ # present in current run and not code signed on copy, we should perform+ # non-incremental run for simplicity and correctness reasons.+ current_codesigned_on_copy_items = {+ codesigned_on_copy_item(+ path=Path(i.dst),+ entitlements=(+ Path(i.codesign_entitlements) if i.codesign_entitlements else None+ ),+ incremental_context=incremental_context,+ codesign_flags_override=i.codesign_flags_override,+ extra_codesign_paths=i.extra_codesign_paths,+ )+ for i in spec+ if i.codesign_on_copy+ }++ codesigned_on_copy_paths_from_previous_build_which_are_present_in_current_build = _codesigned_on_copy_paths_from_previous_build_which_are_present_in_current_build(+ previous_run_state.codesigned_on_copy,+ {Path(i.dst) for i in spec},+ )+ codesign_on_copy_paths_are_compatible = codesigned_on_copy_paths_from_previous_build_which_are_present_in_current_build.issubset(+ current_codesigned_on_copy_items+ )+ if not codesign_on_copy_paths_are_compatible:+ logging.getLogger(__name__).info(+ f"Decided not to assemble incrementally — there is at least one artifact `{list(codesigned_on_copy_paths_from_previous_build_which_are_present_in_current_build - current_codesigned_on_copy_items)[0]}` that was code signed on copy in previous build which is present in current run and not code signed on copy (or codesigned but with a different set of entitlements, flags or extra paths.)."+ )+ return codesign_on_copy_paths_are_compatible+++def _codesigned_on_copy_paths_from_previous_build_which_are_present_in_current_build(+ previously_codesigned_on_copy: List[CodesignedOnCopy],+ all_input_files: Set[Path],+) -> Set[CodesignedOnCopy]:+ all_input_files_and_directories = all_input_files | {+ i for file in all_input_files for i in file.parents+ }+ return {+ i+ for i in previously_codesigned_on_copy+ if i.path in all_input_files_and_directories+ }+++def _get_new_digest(action_metadata: Dict[Path, str], path: Path) -> str:+ # A spec source is normally an action input recorded under exactly this+ # path, and this runs once per file in the bundle, so try the lookup before+ # resolving: `Path.resolve()` walks and stats every component of the path.+ digest = action_metadata.get(path)+ if digest is not None:+ return digest++ # While a resource file can be in a symlinked folder, like the `ghi/def` example below,+ # ```+ # project_root+ # ├── abc+ # │ └── def+ # └── ghi -> abc+ # ```+ # In this case, Python would say `ghi/abc` not a symlink. However the `action_metadata` comes+ # with the actual resolved path (`abc/def`). We need to resolve the path then.+ # Given Python doesn't think it's a symlink, the `readlink` API wouldn't work either+ resolved_path = path.resolve()++ cwd = Path.cwd()+ try:+ path_relative_to_cwd = resolved_path.relative_to(cwd)+ except ValueError:+ # Synthesized paths are those generated by the bundling script itself+ # (i.e., not an input to the action).+ #+ # Need to handle the case where synthesized path (usually in a temp dir)+ # cannot be relativized against the cwd+ path_relative_to_cwd = None++ if path_relative_to_cwd and path_relative_to_cwd in action_metadata:+ return action_metadata[path_relative_to_cwd]++ # The bundler synthesizes some files itself (e.g. build info) rather than+ # them being action inputs, so they have no entry in the action metadata.+ hasher = hashlib.sha256()+ with open(resolved_path, "rb") as f:+ for chunk in iter(lambda: f.read(1024 * 1024), b""):+ hasher.update(chunk)+ return hasher.hexdigest()+++def calculate_incremental_state(+ spec: List[BundleSpecItem], action_metadata: Dict[Path, str]+) -> List[IncrementalStateItem]:+ """+ `action_metadata` maps Buck project relative paths to hash digest+ for every input file of the action which executes this script+ """+ result = []+ source_with_destination_files = _source_with_destination_files(spec)+ for src, dst in source_with_destination_files:+ is_symlink = src.is_symlink()+ new_digest = _get_new_digest(action_metadata, src) if not is_symlink else None+ resolved_symlink = Path(os.readlink(src)) if is_symlink else None+ result.append(+ IncrementalStateItem(+ source=src,+ destination_relative_to_bundle=dst,+ digest=new_digest,+ resolved_symlink=resolved_symlink,+ )+ )+ return result+++def _source_with_destination_files(+ spec: List[BundleSpecItem],+) -> List[Tuple[Path, Path]]:+ """+ Returns:+ Ordered mapping from source path to destination path (relative to bundle) for every file+ present in a bundle. Directories that were parts of the spec are split into actual files.+ """+ result = []+ for spec_item in spec:+ file_or_dir = Path(spec_item.src)+ if file_or_dir.is_file():+ if not spec_item.dst:+ raise RuntimeError(+ f'Invalid input bundle spec. File located at {file_or_dir} should not have `""` destination (only directories are allowed to have such value).'+ )+ result.append((file_or_dir, Path(spec_item.dst)))+ elif file_or_dir.is_dir():+ result.extend(+ [+ (file, spec_item.dst / file.relative_to(file_or_dir))+ for file in _list_directory_deterministically(file_or_dir)+ ]+ )+ else:+ raise RuntimeError(+ f"Path {file_or_dir} is not a file and not a dir, don't know how to handle it."+ )++ return [(src, dst) for src, dst in result if src.name not in FILES_TO_BE_IGNORED]+++def _list_directory_deterministically(directory: Path) -> List[Path]:+ result = []+ for current_dir_path, dir_names, file_names in os.walk(directory):+ result += [Path(os.path.join(current_dir_path, f)) for f in sorted(file_names)]+ # Sort in order for walk to be deterministic.+ dir_names.sort()+ return result+++def codesigned_on_copy_item(+ path: Path,+ entitlements: Optional[Path],+ incremental_context: IncrementalContext,+ codesign_flags_override: Optional[List[str]],+ extra_codesign_paths: Optional[List[str]],+) -> CodesignedOnCopy:+ if entitlements is not None:+ digest = incremental_context.metadata.get(entitlements)+ if digest is None:+ raise RuntimeError(+ f"Expected digest for entitlements file path `{entitlements}` to be present in action metadata."+ )+ else:+ digest = None+ return CodesignedOnCopy(+ path=path,+ entitlements_digest=digest,+ codesign_flags_override=codesign_flags_override,+ extra_codesign_paths=extra_codesign_paths,+ )
@@ -0,0 +1,672 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import os+import tempfile+import unittest+from pathlib import Path+from typing import Generator+from unittest.mock import patch++from apple.tools.code_signing.codesign_bundle import CodesignConfiguration++from .assemble_bundle_types import BundleSpecItem+from .incremental_state import CodesignedOnCopy, IncrementalState, IncrementalStateItem+from .incremental_utils import (+ calculate_incremental_state,+ IncrementalContext,+ should_assemble_incrementally,+)++try:+ from contextlib import chdir # pyre-ignore[21], Python 3.11++except ImportError:+ from contextlib import contextmanager++ @contextmanager+ def chdir(path: os.PathLike) -> Generator[None, None, None]:+ cwd = os.getcwd()+ try:+ os.chdir(path)+ yield+ finally:+ os.chdir(cwd)+++class TestIncrementalUtils(unittest.TestCase):+ maxDiff = None++ def test_not_run_incrementally_when_previous_build_not_incremental(self):+ spec = [+ BundleSpecItem(+ src="src/foo",+ dst="foo",+ codesign_on_copy=False,+ )+ ]+ incremental_context = IncrementalContext(+ metadata={Path("foo"): "digest"},+ state=None,+ codesigned=False,+ codesign_configuration=None,+ codesign_identity=None,+ codesign_arguments=[],+ versioned_if_macos=True,+ )+ self.assertFalse(should_assemble_incrementally(spec, incremental_context))++ def test_run_incrementally_when_previous_build_not_codesigned(self):+ spec = [+ BundleSpecItem(+ src="src/foo",+ dst="foo",+ codesign_on_copy=False,+ )+ ]+ incremental_context = IncrementalContext(+ metadata={Path("foo"): "digest"},+ state=IncrementalState(+ items=[+ IncrementalStateItem(+ source=Path("src/foo"),+ destination_relative_to_bundle=Path("foo"),+ digest="digest",+ resolved_symlink=None,+ )+ ],+ codesigned=False,+ codesign_configuration=None,+ codesigned_on_copy=[],+ codesign_identity=None,+ codesign_arguments=[],+ versioned_if_macos=True,+ swift_stdlib_paths=[],+ ),+ codesigned=True,+ codesign_configuration=None,+ codesign_identity=None,+ codesign_arguments=[],+ versioned_if_macos=True,+ )+ self.assertTrue(should_assemble_incrementally(spec, incremental_context))++ def test_not_run_incrementally_when_previous_build_codesigned_and_current_is_not(+ self,+ ):+ spec = [+ BundleSpecItem(+ src="src/foo",+ dst="foo",+ codesign_on_copy=False,+ )+ ]+ incremental_context = IncrementalContext(+ metadata={Path("foo"): "digest"},+ state=IncrementalState(+ items=[+ IncrementalStateItem(+ source=Path("src/foo"),+ destination_relative_to_bundle=Path("foo"),+ digest="digest",+ resolved_symlink=None,+ )+ ],+ codesigned=True,+ codesign_configuration=None,+ codesigned_on_copy=[],+ codesign_identity=None,+ codesign_arguments=[],+ versioned_if_macos=True,+ swift_stdlib_paths=[],+ ),+ codesigned=False,+ codesign_configuration=None,+ codesign_identity=None,+ codesign_arguments=[],+ versioned_if_macos=True,+ )+ self.assertFalse(should_assemble_incrementally(spec, incremental_context))+ # Check that behavior changes when both builds are codesigned+ incremental_context.codesigned = True+ self.assertTrue(should_assemble_incrementally(spec, incremental_context))++ def test_not_run_incrementally_when_previous_build_codesigned_with_different_identity(+ self,+ ):+ spec = [+ BundleSpecItem(+ src="src/foo",+ dst="foo",+ codesign_on_copy=False,+ )+ ]+ incremental_context = IncrementalContext(+ metadata={Path("foo"): "digest"},+ state=IncrementalState(+ items=[+ IncrementalStateItem(+ source=Path("src/foo"),+ destination_relative_to_bundle=Path("foo"),+ digest="digest",+ resolved_symlink=None,+ )+ ],+ codesigned=True,+ codesign_configuration=None,+ codesigned_on_copy=[],+ codesign_identity="old_identity",+ codesign_arguments=[],+ versioned_if_macos=True,+ swift_stdlib_paths=[],+ ),+ codesigned=True,+ codesign_configuration=None,+ codesign_identity="new_identity",+ codesign_arguments=[],+ versioned_if_macos=True,+ )+ self.assertFalse(should_assemble_incrementally(spec, incremental_context))+ # Check that behavior changes when identities are same+ incremental_context.state.codesign_identity = "same_identity"+ incremental_context.codesign_identity = "same_identity"+ self.assertTrue(should_assemble_incrementally(spec, incremental_context))++ def test_run_incrementally_when_codesign_on_copy_paths_match(self):+ spec = [+ BundleSpecItem(+ src="src/foo",+ dst="foo",+ codesign_on_copy=True,+ ),+ BundleSpecItem(+ src="src/bar",+ dst="bar",+ codesign_on_copy=True,+ ),+ BundleSpecItem(+ src="src/baz",+ dst="baz",+ codesign_on_copy=True,+ codesign_entitlements="entitlements.plist",+ ),+ ]+ incremental_context = IncrementalContext(+ metadata={+ Path("src/foo"): "digest",+ Path("src/baz"): "digest2",+ Path("entitlements.plist"): "entitlements_digest",+ },+ state=IncrementalState(+ items=[+ IncrementalStateItem(+ source=Path("src/foo"),+ destination_relative_to_bundle=Path("foo"),+ digest="digest",+ resolved_symlink=None,+ ),+ IncrementalStateItem(+ source=Path("src/baz"),+ destination_relative_to_bundle=Path("baz"),+ digest="digest2",+ resolved_symlink=None,+ ),+ ],+ codesigned=True,+ codesign_configuration=None,+ codesigned_on_copy=[+ CodesignedOnCopy(+ path=Path("foo"),+ entitlements_digest=None,+ codesign_flags_override=None,+ extra_codesign_paths=None,+ ),+ CodesignedOnCopy(+ path=Path("baz"),+ entitlements_digest="entitlements_digest",+ codesign_flags_override=None,+ extra_codesign_paths=None,+ ),+ ],+ codesign_identity="same_identity",+ codesign_arguments=[],+ versioned_if_macos=True,+ swift_stdlib_paths=[],+ ),+ codesigned=True,+ codesign_configuration=None,+ codesign_identity="same_identity",+ codesign_arguments=[],+ versioned_if_macos=True,+ )+ self.assertTrue(should_assemble_incrementally(spec, incremental_context))++ def test_not_run_incrementally_when_codesign_on_copy_paths_mismatch(self):+ spec = [+ BundleSpecItem(+ src="src/foo",+ dst="foo",+ # want it to be not codesigned in new build+ codesign_on_copy=False,+ )+ ]+ incremental_context = IncrementalContext(+ metadata={Path("src/foo"): "digest"},+ state=IncrementalState(+ items=[+ IncrementalStateItem(+ source=Path("src/foo"),+ destination_relative_to_bundle=Path("foo"),+ digest="digest",+ resolved_symlink=None,+ )+ ],+ codesigned=True,+ codesign_configuration=None,+ # but it was codesigned in old build+ codesigned_on_copy=[+ CodesignedOnCopy(+ path=Path("foo"),+ entitlements_digest=None,+ codesign_flags_override=None,+ extra_codesign_paths=None,+ )+ ],+ codesign_identity="same_identity",+ codesign_arguments=[],+ versioned_if_macos=True,+ swift_stdlib_paths=[],+ ),+ codesigned=True,+ codesign_configuration=None,+ codesign_identity="same_identity",+ codesign_arguments=[],+ versioned_if_macos=True,+ )+ self.assertFalse(should_assemble_incrementally(spec, incremental_context))+ spec[0].codesign_on_copy = True+ self.assertTrue(should_assemble_incrementally(spec, incremental_context))++ def test_not_run_incrementally_when_codesign_on_copy_entitlements_mismatch(self):+ spec = [+ BundleSpecItem(+ src="src/foo",+ dst="foo",+ codesign_on_copy=True,+ codesign_entitlements="baz/entitlements.plist",+ )+ ]+ incremental_context = IncrementalContext(+ metadata={+ Path("src/foo"): "digest",+ Path("baz/entitlements.plist"): "new_digest",+ },+ state=IncrementalState(+ items=[+ IncrementalStateItem(+ source=Path("src/foo"),+ destination_relative_to_bundle=Path("foo"),+ digest="digest",+ resolved_symlink=None,+ )+ ],+ codesigned=True,+ codesign_configuration=None,+ codesigned_on_copy=[+ CodesignedOnCopy(+ path=Path("foo"),+ entitlements_digest="old_digest",+ codesign_flags_override=None,+ extra_codesign_paths=None,+ )+ ],+ codesign_identity="same_identity",+ codesign_arguments=[],+ versioned_if_macos=True,+ swift_stdlib_paths=[],+ ),+ codesigned=True,+ codesign_configuration=None,+ codesign_identity="same_identity",+ codesign_arguments=[],+ versioned_if_macos=True,+ )+ self.assertFalse(should_assemble_incrementally(spec, incremental_context))+ incremental_context.metadata[Path("baz/entitlements.plist")] = "old_digest"+ self.assertTrue(should_assemble_incrementally(spec, incremental_context))++ def test_not_run_incrementally_when_codesign_on_copy_flags_mismatch(self):+ spec = [+ BundleSpecItem(+ src="src/foo",+ dst="foo",+ codesign_on_copy=True,+ codesign_flags_override=["--force"],+ )+ ]+ incremental_context = IncrementalContext(+ metadata={+ Path("src/foo"): "digest",+ },+ state=IncrementalState(+ items=[+ IncrementalStateItem(+ source=Path("src/foo"),+ destination_relative_to_bundle=Path("foo"),+ digest="digest",+ resolved_symlink=None,+ )+ ],+ codesigned=True,+ codesign_configuration=None,+ codesigned_on_copy=[+ CodesignedOnCopy(+ path=Path("foo"),+ entitlements_digest=None,+ codesign_flags_override=["--force", "--deep"],+ extra_codesign_paths=None,+ )+ ],+ codesign_identity="same_identity",+ codesign_arguments=[],+ versioned_if_macos=True,+ swift_stdlib_paths=[],+ ),+ codesigned=True,+ codesign_configuration=None,+ codesign_identity="same_identity",+ codesign_arguments=[],+ versioned_if_macos=True,+ )+ self.assertFalse(should_assemble_incrementally(spec, incremental_context))+ incremental_context.state.codesigned_on_copy[0].codesign_flags_override = [+ "--force"+ ]+ self.assertTrue(should_assemble_incrementally(spec, incremental_context))++ def test_not_run_incrementally_when_extra_codesign_paths_mismatch(self):+ extra_codesign_paths_before = ["Frameworks/Base.framework"]+ extra_codesign_paths_after = [+ "Frameworks/Base.framework",+ "Frameworks/Extra.framework",+ ]+ spec = [+ BundleSpecItem(+ src="src/foo",+ dst="foo",+ codesign_on_copy=True,+ extra_codesign_paths=extra_codesign_paths_after,+ )+ ]+ incremental_context = IncrementalContext(+ metadata={+ Path("src/foo"): "digest",+ },+ state=IncrementalState(+ items=[+ IncrementalStateItem(+ source=Path("src/foo"),+ destination_relative_to_bundle=Path("foo"),+ digest="digest",+ resolved_symlink=None,+ )+ ],+ codesigned=True,+ codesign_configuration=None,+ codesigned_on_copy=[+ CodesignedOnCopy(+ path=Path("foo"),+ entitlements_digest=None,+ codesign_flags_override=None,+ extra_codesign_paths=extra_codesign_paths_before,+ )+ ],+ codesign_identity="same_identity",+ codesign_arguments=[],+ versioned_if_macos=True,+ swift_stdlib_paths=[],+ ),+ codesigned=True,+ codesign_configuration=None,+ codesign_identity="same_identity",+ codesign_arguments=[],+ versioned_if_macos=True,+ )+ self.assertFalse(should_assemble_incrementally(spec, incremental_context))+ incremental_context.state.codesigned_on_copy[+ 0+ ].extra_codesign_paths = extra_codesign_paths_after+ self.assertTrue(should_assemble_incrementally(spec, incremental_context))++ def test_not_run_incrementally_when_codesign_arguments_mismatch(self):+ spec = [+ BundleSpecItem(+ src="src/foo",+ dst="foo",+ )+ ]+ incremental_context = IncrementalContext(+ metadata={+ Path("src/foo"): "digest",+ },+ state=IncrementalState(+ items=[+ IncrementalStateItem(+ source=Path("src/foo"),+ destination_relative_to_bundle=Path("foo"),+ digest="digest",+ resolved_symlink=None,+ )+ ],+ codesigned=True,+ codesign_configuration=None,+ codesigned_on_copy=[],+ codesign_identity="same_identity",+ codesign_arguments=["--force"],+ swift_stdlib_paths=[],+ versioned_if_macos=True,+ ),+ codesigned=True,+ codesign_configuration=None,+ codesign_identity="same_identity",+ codesign_arguments=["--force", "--deep"],+ versioned_if_macos=True,+ )+ self.assertFalse(should_assemble_incrementally(spec, incremental_context))+ incremental_context.codesign_arguments = ["--force"]+ self.assertTrue(should_assemble_incrementally(spec, incremental_context))++ def test_not_run_incrementally_when_codesign_configurations_mismatch(self):+ spec = [+ BundleSpecItem(+ src="src/foo",+ dst="foo",+ codesign_on_copy=True,+ )+ ]+ incremental_context = IncrementalContext(+ metadata={Path("src/foo"): "digest"},+ state=IncrementalState(+ items=[+ IncrementalStateItem(+ source=Path("src/foo"),+ destination_relative_to_bundle=Path("foo"),+ digest="digest",+ resolved_symlink=None,+ )+ ],+ codesigned=True,+ # Dry codesigned in old build+ codesign_configuration=CodesignConfiguration.dryRun,+ codesigned_on_copy=[+ CodesignedOnCopy(+ path=Path("foo"),+ entitlements_digest=None,+ codesign_flags_override=None,+ extra_codesign_paths=None,+ )+ ],+ codesign_identity="same_identity",+ codesign_arguments=[],+ versioned_if_macos=True,+ swift_stdlib_paths=[],+ ),+ codesigned=True,+ codesign_configuration=CodesignConfiguration.dryRun,+ codesign_identity="same_identity",+ codesign_arguments=[],+ versioned_if_macos=True,+ )+ # Canary+ self.assertTrue(should_assemble_incrementally(spec, incremental_context))+ # Now we want a regular signing in new build+ incremental_context.codesign_configuration = None+ self.assertFalse(should_assemble_incrementally(spec, incremental_context))++ def test_calculate_incremental_state(self):+ with tempfile.TemporaryDirectory() as project_root, chdir(project_root):+ # project_root+ # ├── foo+ # ├── bar+ # │ ├── baz+ # │ └── qux -> baz+ # ├── abc+ # │ └── def+ # └── ghi -> abc+ Path("foo").write_text("hello")+ bar_path = Path("bar")+ bar_path.mkdir()+ (bar_path / "baz").write_text("world")+ (bar_path / "qux").symlink_to("baz")+ abc_path = Path("abc")+ abc_path.mkdir()+ (abc_path / "def").write_text("yo")+ Path("ghi").symlink_to("abc")++ action_metadata = {+ Path("foo"): "hash(foo)",+ Path("bar/baz"): "hash(baz)",+ Path("abc/def"): "hash(def)",+ }+ spec = [+ BundleSpecItem(+ src="foo",+ dst="foo",+ codesign_on_copy=False,+ ),+ BundleSpecItem(+ src="bar",+ dst="tux",+ codesign_on_copy=True,+ ),+ BundleSpecItem(+ src="ghi",+ dst="ghi",+ codesign_on_copy=True,+ ),+ ]+ state = calculate_incremental_state(spec, action_metadata)+ self.assertEqual(+ state,+ [+ IncrementalStateItem(+ source=Path("foo"),+ destination_relative_to_bundle=Path("foo"),+ digest="hash(foo)",+ resolved_symlink=None,+ ),+ IncrementalStateItem(+ source=Path("bar/baz"),+ destination_relative_to_bundle=Path("tux/baz"),+ digest="hash(baz)",+ resolved_symlink=None,+ ),+ IncrementalStateItem(+ source=Path("bar/qux"),+ destination_relative_to_bundle=Path("tux/qux"),+ digest=None,+ resolved_symlink=Path("baz"),+ ),+ IncrementalStateItem(+ source=Path("ghi/def"),+ destination_relative_to_bundle=Path("ghi/def"),+ digest="hash(def)",+ resolved_symlink=None,+ ),+ ],+ )++ def test_calculate_incremental_state_prefers_action_metadata_to_resolving(+ self,+ ) -> None:+ with tempfile.TemporaryDirectory() as project_root, chdir(project_root):+ Path("foo").write_text("hello")+ action_metadata = {Path("foo"): "hash(foo)"}+ spec = [BundleSpecItem(src="foo", dst="foo")]+ with patch.object(+ Path, "resolve", side_effect=AssertionError("path was resolved")+ ):+ state = calculate_incremental_state(spec, action_metadata)+ self.assertEqual(+ state,+ [+ IncrementalStateItem(+ source=Path("foo"),+ destination_relative_to_bundle=Path("foo"),+ digest="hash(foo)",+ resolved_symlink=None,+ ),+ ],+ )++ def test_calculate_incremental_state_with_ds_store(self) -> None:+ with tempfile.TemporaryDirectory() as project_root, chdir(project_root):+ # project_root+ # ├── foo+ # └── bar+ # ├── baz+ # └── .DS_Store+ Path("foo").write_text("hello")+ bar_path = Path("bar")+ bar_path.mkdir()+ (bar_path / "baz").write_text("world")+ (bar_path / ".DS_Store").touch()++ action_metadata = {+ Path("foo"): "hash(foo)",+ Path("bar/baz"): "hash(baz)",+ }+ spec = [+ BundleSpecItem(+ src="foo",+ dst="foo",+ codesign_on_copy=False,+ ),+ BundleSpecItem(+ src="bar",+ dst="bar",+ codesign_on_copy=True,+ ),+ ]+ state = calculate_incremental_state(spec, action_metadata)+ self.assertEqual(+ state,+ [+ IncrementalStateItem(+ source=Path("foo"),+ destination_relative_to_bundle=Path("foo"),+ digest="hash(foo)",+ resolved_symlink=None,+ ),+ IncrementalStateItem(+ source=Path("bar/baz"),+ destination_relative_to_bundle=Path("bar/baz"),+ digest="hash(baz)",+ resolved_symlink=None,+ ),+ ],+ )
@@ -0,0 +1,62 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++from __future__ import annotations++import logging+import sys+from pathlib import Path+++def configure_logging(+ stderr_level: int,+ file_level: int,+ log_path: Path | None,+) -> None:+ stderr_handler = logging.StreamHandler()+ stderr_handler.setLevel(stderr_level)+ log_format = (+ "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"+ )+ stderr_handler.setFormatter(+ _ColoredLogFormatter(log_format)+ if sys.stderr.isatty()+ else logging.Formatter(log_format)+ )++ handlers: list[logging.Handler] = [stderr_handler]+ if log_path is not None:+ # Declared log outputs must exist even when no messages are emitted, and+ # incremental runs must not retain messages from an earlier invocation.+ log_path.write_text("")+ file_handler = logging.FileHandler(log_path, encoding="utf-8")+ file_handler.setFormatter(logging.Formatter(log_format))+ file_handler.setLevel(file_level)+ handlers.append(file_handler)++ logging.basicConfig(level=logging.DEBUG, handlers=handlers)+++class _ColoredLogFormatter(logging.Formatter):+ _colors: dict[int, str] = {+ logging.DEBUG: "\x1b[m",+ logging.INFO: "\x1b[37m",+ logging.WARNING: "\x1b[33m",+ logging.ERROR: "\x1b[31m",+ logging.CRITICAL: "\x1b[1;31m",+ }+ _reset_color = "\x1b[0m"++ def __init__(self, text_format: str) -> None:+ self.text_format = text_format++ def format(self, record: logging.LogRecord) -> str:+ formatter = logging.Formatter(+ self._colors.get(record.levelno, "") + self.text_format + self._reset_color+ )+ return formatter.format(record)
@@ -0,0 +1,748 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++from __future__ import annotations++import argparse+import cProfile+import json+import logging+import os+import pstats+import subprocess+import tempfile+from pathlib import Path+from typing import List, Optional++from apple.tools.code_signing.codesign_bundle import (+ codesign_bundle,+ CodesignConfiguration,+ CodesignedPath,+ write_empty_codesign_manifest,+)+from apple.tools.code_signing.signing_context_types import (+ AdhocSigningContext,+ selection_profile_context_from_signing_context,+ SigningContextWithProfileSelection,+)+from apple.tools.re_compatibility_utils.writable import make_dir_recursively_writable++from .action_metadata import action_metadata_if_present+from .assemble_bundle import assemble_bundle+from .assemble_bundle_types import BundleSpecItem, IncrementalContext+from .incremental_state import (+ IncrementalState,+ IncrementalStateItem,+ IncrementalStateJSONEncoder,+ parse_incremental_state,+)+from .incremental_utils import codesigned_on_copy_item+from .logging_utils import configure_logging+from .signing_context import (+ add_args_for_bundling_execution,+ add_args_for_signing_context_path,+)+from .signing_context_data import (+ load_signing_context_data_from_file,+ SigningContextData,+)+from .swift_support import run_swift_stdlib_tool, SwiftSupportArguments+++_METADATA_PATH_KEY = "ACTION_METADATA"+++def _args_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description="Tool which assembles the Apple bundle."+ )+ parser.add_argument(+ "--output",+ metavar="</path/to/app.bundle>",+ type=Path,+ required=True,+ help="Absolute path to Apple bundle result.",+ )+ parser.add_argument(+ "--spec",+ metavar="<Spec.json>",+ type=Path,+ required=True,+ help="Path to file with JSON representing the bundle contents. It should contain a dictionary which maps bundle relative destination paths to source paths.",+ )+ parser.add_argument(+ "--codesign-tool",+ metavar="<codesign>",+ type=Path,+ required=False,+ help="Path to code signing utility. If not provided standard `codesign` tool will be used.",+ )+ parser.add_argument(+ "--codesign-manifest",+ metavar="<manifest_file>",+ type=Path,+ required=False,+ help="Path to a file containing codesign invocations.",+ )+ parser.add_argument(+ "--codesign-args",+ type=str,+ default=[],+ required=False,+ action="append",+ help="Add additional args to pass during codesigning. Pass as`--codesign-args=ARG` to ensure correct arg parsing.",+ )+ parser.add_argument(+ "--codesign-configuration",+ required=False,+ type=CodesignConfiguration,+ choices=[e.value for e in CodesignConfiguration],+ help=f"""+ Augments how code signing is run.+ Pass `{CodesignConfiguration.fastAdhoc}` to skip adhoc signing bundles if the executables are already adhoc signed.+ Pass `{CodesignConfiguration.executionBypass}` to skip executing the actual codesigning commands.+ Pass `{CodesignConfiguration.dryRun}` for code signing to be run in dry mode (instead of actual signing only .plist+ files with signing parameters will be generated in the root of each signed bundle).+ """,+ )+ parser.add_argument(+ "--fast-adhoc-signing-probe-enabled",+ action="store_true",+ help="Allow fast-adhoc signing to consult the bundled signature probe tool when it is available.",+ )+ parser.add_argument(+ "--incremental-state",+ metavar="<IncrementalState.json>",+ type=Path,+ required=False,+ help="Required if script is run in incremental mode. Path to file with JSON which describes the contents of bundle built previously.",+ )+ parser.add_argument(+ "--profile-output",+ metavar="<ProfileOutput.txt>",+ type=Path,+ required=False,+ help="Path to the profiling output. If present profiling will be enabled.",+ )+ parser.add_argument(+ "--log-level-stderr",+ choices=["debug", "info", "warning", "error", "critical"],+ type=str,+ required=False,+ default="warning",+ help="Logging level for messages written to stderr.",+ )+ parser.add_argument(+ "--log-level-file",+ choices=["debug", "info", "warning", "error", "critical"],+ type=str,+ required=False,+ default="info",+ help="Logging level for messages written to a log file.",+ )+ parser.add_argument(+ "--binary-destination",+ metavar="<Binary>",+ type=Path,+ required=False,+ help="Required if swift support was requested. Bundle relative destination path to bundle binary.",+ )+ parser.add_argument(+ "--frameworks-destination",+ metavar="<Frameworks>",+ type=Path,+ required=False,+ help="Required if swift support was requested. Bundle relative destination path to frameworks directory.",+ )+ parser.add_argument(+ "--extensionkit-extensions-destination",+ metavar="<ExtensionKitExtensions>",+ type=Path,+ required=False,+ help="Required if swift support was requested. Bundle relative destination path to ExtensionKit Extensions directory.",+ )+ parser.add_argument(+ "--plugins-destination",+ metavar="<Plugins>",+ type=Path,+ required=False,+ help="Required if swift support was requested. Bundle relative destination path to plugins directory.",+ )+ parser.add_argument(+ "--resources-destination",+ metavar="<Resources>",+ type=Path,+ required=False,+ help="Required if swift support was requested. Bundle relative destination path to resources directory.",+ )+ parser.add_argument(+ "--appclips-destination",+ metavar="<AppClips>",+ type=Path,+ required=False,+ help="Required if swift support was requested. Bundle relative destination path to appclips directory.",+ )+ parser.add_argument(+ "--sdk-root",+ metavar="<path/to/SDK>",+ type=Path,+ required=False,+ help="Required if swift support was requested. Path to SDK root.",+ )+ parser.add_argument(+ "--swift-stdlib-command",+ metavar='<"/swift/stdlib/tool --foo bar/qux">',+ type=str,+ required=False,+ help="Swift stdlib command prefix. If present, output bundle will contain needed Swift standard libraries (to support the lack of ABI stability or certain backports usage).",+ )+ parser.add_argument(+ "--check-conflicts",+ action="store_true",+ help="Check there are no path conflicts between different source parts of the bundle if enabled.",+ )+ parser.add_argument(+ "--versioned-if-macos",+ action="store_true",+ help="Create symlinks for versioned macOS bundle",+ )+ parser.add_argument(+ "--include-build-info-file",+ action="store_true",+ help="Include the build info file in the assembled bundle.",+ )+ parser.add_argument(+ "--bundle-telemetry-logger",+ metavar="<path/to/logger>",+ type=Path,+ required=False,+ help="Path to bundle telemetry logger tool. If provided, will be invoked after bundle assembly completes.",+ )++ add_args_for_bundling_execution(parser)+ add_args_for_signing_context_path(parser)++ return parser+++def _get_codesigned_paths_for_spec_item(+ bundle_path: CodesignedPath,+ args: argparse.Namespace,+ item: BundleSpecItem,+ codesign_configuration: Optional[CodesignConfiguration],+) -> List[CodesignedPath]:+ if not item.codesign_on_copy:+ return []++ entitlements = (+ Path(item.codesign_entitlements) if item.codesign_entitlements else None+ )+ flags = (+ item.codesign_flags_override+ if (item.codesign_flags_override is not None)+ else args.codesign_args+ )++ codesigned_paths = []+ extra_file_paths = []++ is_dry_run = codesign_configuration is CodesignConfiguration.dryRun+ extra_codesign_paths = item.extra_codesign_paths or []+ for extra_codesign_path in extra_codesign_paths:+ path = bundle_path.path / item.dst / extra_codesign_path+ if not path.exists():+ raise RuntimeError(+ f"Found non-existing extra path to codesign: {extra_codesign_path} for {item.src}"+ )++ if path.is_file() and is_dry_run:+ # In dry-run mode, non-bundle items should be signed as part of the containing bundle.+ extra_file_paths.append(extra_codesign_path)+ else:+ codesigned_paths.append(+ CodesignedPath(+ path=path,+ entitlements=entitlements,+ flags=flags,+ extra_file_paths=None,+ )+ )++ codesigned_paths.append(+ CodesignedPath(+ path=bundle_path.path / item.dst,+ entitlements=entitlements,+ flags=flags,+ extra_file_paths=extra_file_paths,+ )+ )++ return codesigned_paths+++def _get_codesigned_paths_from_spec(+ bundle_path: CodesignedPath,+ args: argparse.Namespace,+ spec: List[BundleSpecItem],+) -> List[CodesignedPath]:+ codesigned_paths = []+ for item in spec:+ codesigned_paths += _get_codesigned_paths_for_spec_item(+ bundle_path=bundle_path,+ args=args,+ item=item,+ codesign_configuration=args.codesign_configuration,+ )+ return codesigned_paths+++def _load_signing_context(+ args: argparse.Namespace,+ temp_dir: Path,+) -> tuple[AdhocSigningContext | SigningContextWithProfileSelection | None, str | None]:+ if not args.codesign:+ return None, None++ signing_context_data = load_signing_context_data_from_file(+ args.signing_context_path+ )+ _materialize_selected_profile(signing_context_data, temp_dir)+ return signing_context_data.signing_context, signing_context_data.selected_identity+++def _main(spec_temp_dir: str) -> None:+ args_parser = _args_parser()+ args = args_parser.parse_args()++ uname_info = os.uname()+ sysname = uname_info.sysname+ major_release = int(uname_info.release.split(".")[0])++ # macOS 26.0.0 Tahoe no longer supports SHA1 as an option in the codesign tool.+ # Note: This is safe to remove along with the code that adds the digest-algorithm code+ # in apple_bundle_wrapping_rule.bzl once we are migrated to macOS 26.0.+ if (+ "--digest-algorithm=sha1" in args.codesign_args+ and sysname == "Darwin"+ and major_release+ >= 25 # Darwin kernel release 25.0.0 corresponds to macOS 26.0.0 Tahoe+ ):+ args.codesign_args.remove("--digest-algorithm=sha1")++ configure_logging(+ stderr_level=getattr(logging, args.log_level_stderr.upper()),+ file_level=getattr(logging, args.log_level_file.upper()),+ log_path=args.log_file,+ )++ pr = cProfile.Profile()+ profiling_enabled = args.profile_output is not None+ if profiling_enabled:+ pr.enable()++ signing_context, selected_identity_argument = _load_signing_context(+ args,+ Path(spec_temp_dir),+ )++ with args.spec.open(mode="rb") as spec_file:+ spec = json.load(spec_file, object_hook=lambda d: BundleSpecItem(**d))+ spec = _deduplicate_spec(spec)++ incremental_context = _incremental_context(+ incremenatal_state_path=args.incremental_state,+ codesigned=args.codesign,+ codesign_configuration=args.codesign_configuration,+ codesign_identity=selected_identity_argument,+ codesign_arguments=args.codesign_args,+ versioned_if_macos=args.versioned_if_macos,+ )++ if args.include_build_info_file:+ _amend_spec_with_build_uuid(+ spec=spec,+ resources_destination=args.resources_destination,+ tmp_dir=Path(spec_temp_dir),+ )++ incremental_state = assemble_bundle(+ spec=spec,+ bundle_path=args.output,+ incremental_context=incremental_context,+ check_conflicts=args.check_conflicts,+ versioned_if_macos=args.versioned_if_macos,+ )++ swift_support_args = _swift_support_arguments(+ args_parser,+ args,+ )++ if swift_support_args:+ swift_stdlib_paths = run_swift_stdlib_tool(+ bundle_path=args.output,+ args=swift_support_args,+ )+ else:+ swift_stdlib_paths = []++ prepared_entitlements_path: Optional[Path] = None+ telemetry_tmp_dir: Optional[tempfile.TemporaryDirectory[str]] = None++ if args.codesign:+ # Vendored frameworks/bundles could already be pre-signed, in which case,+ # re-signing them requires modifying them. On RE, the umask is such that+ # copied files (when constructing the bundle) are not writable.+ make_dir_recursively_writable(args.output)+ if signing_context is None:+ raise RuntimeError(+ "Expected signing context to be created before bundling is done if codesign is requested."+ )++ bundle_path = CodesignedPath(+ path=args.output,+ entitlements=args.entitlements,+ flags=args.codesign_args,+ extra_file_paths=None,+ )+ codesign_on_copy_paths = _get_codesigned_paths_from_spec(+ bundle_path=bundle_path, spec=spec, args=args+ ) + [+ CodesignedPath(+ path=bundle_path.path / path,+ entitlements=None,+ flags=args.codesign_args,+ extra_file_paths=None,+ )+ for path in swift_stdlib_paths+ ]++ if args.bundle_telemetry_logger:+ telemetry_tmp_dir = tempfile.TemporaryDirectory()+ prepared_entitlements_path = (+ Path(telemetry_tmp_dir.name) / "prepared_entitlements.plist"+ )++ codesign_bundle(+ bundle_path=bundle_path,+ signing_context=signing_context,+ platform=args.platform,+ codesign_on_copy_paths=codesign_on_copy_paths,+ codesign_tool=args.codesign_tool,+ codesign_configuration=args.codesign_configuration,+ fast_adhoc_signing_probe_enabled=args.fast_adhoc_signing_probe_enabled,+ codesign_manifest_path=args.codesign_manifest,+ entitlements_suffixed_key_map=args.entitlements_suffixed_key_map,+ entitlements_removed_keys=args.entitlements_removed_keys,+ entitlements_removed_values_map=args.entitlements_removed_values_map,+ prepared_entitlements_output_path=prepared_entitlements_path,+ )+ elif args.codesign_manifest:+ # Always write the codesign manifest file, even when unsigned+ write_empty_codesign_manifest(+ codesign_manifest_path=args.codesign_manifest,+ bundle_path=args.output,+ )++ if incremental_state:+ if incremental_context is None:+ raise RuntimeError(+ "Expected incremental context to be present when incremental state is non-null."+ )+ _write_incremental_state(+ spec=spec,+ items=incremental_state,+ path=args.incremental_state,+ codesigned=args.codesign,+ codesign_configuration=args.codesign_configuration,+ selected_codesign_identity=selected_identity_argument,+ codesign_arguments=args.codesign_args,+ swift_stdlib_paths=swift_stdlib_paths,+ versioned_if_macos=args.versioned_if_macos,+ incremental_context=incremental_context,+ )++ if profiling_enabled:+ pr.disable()+ with open(args.profile_output, "w") as s:+ sortby = pstats.SortKey.CUMULATIVE+ ps = pstats.Stats(pr, stream=s).sort_stats(sortby)+ ps.print_stats()++ if args.bundle_telemetry_logger:+ selected_profile_path = _get_selected_profile_path(signing_context)+ info_plist_in_bundle = (+ (args.output / args.info_plist_destination)+ if args.info_plist_destination+ else None+ )+ _run_bundle_telemetry_logger(+ logger_path=args.bundle_telemetry_logger,+ bundle_path=args.output,+ info_plist=info_plist_in_bundle,+ entitlements=prepared_entitlements_path,+ selected_provisioning_profile=selected_profile_path,+ )++ if telemetry_tmp_dir is not None:+ telemetry_tmp_dir.cleanup()+++def _materialize_selected_profile(+ signing_context_data: SigningContextData,+ output_dir: Path,+) -> None:+ profile_context = selection_profile_context_from_signing_context(+ signing_context_data.signing_context+ )+ if profile_context is None:+ return+ if signing_context_data.provisioning_profile_data is None:+ raise ValueError("Signing context is missing profile data")++ profile = profile_context.selected_profile_info.profile+ materialized_path = output_dir / profile.file_path.name+ materialized_path.write_bytes(signing_context_data.provisioning_profile_data)+ profile.file_path = materialized_path+++def _get_selected_profile_path(+ signing_context: Optional[object],+) -> Optional[Path]:+ if signing_context is None:+ return None++ signing_context_with_profile: Optional[SigningContextWithProfileSelection] = None+ if isinstance(signing_context, SigningContextWithProfileSelection):+ signing_context_with_profile = signing_context+ if isinstance(signing_context, AdhocSigningContext):+ signing_context_with_profile = signing_context.profile_selection_context++ return (+ signing_context_with_profile.selected_profile_info.profile.file_path+ if signing_context_with_profile+ else None+ )+++def _run_bundle_telemetry_logger(+ logger_path: Path,+ bundle_path: Path,+ info_plist: Optional[Path],+ entitlements: Optional[Path],+ selected_provisioning_profile: Optional[Path],+) -> None:+ cmd: List[str] = [str(logger_path), "--bundle", str(bundle_path)]+ if info_plist:+ cmd.extend(["--info-plist", str(info_plist)])+ if entitlements:+ cmd.extend(["--entitlements", str(entitlements)])+ if selected_provisioning_profile:+ cmd.extend(["--provisioning-profile", str(selected_provisioning_profile)])+ try:+ subprocess.run(cmd, check=False)+ except Exception:+ # Telemetry is best-effort, never fail the build+ logging.getLogger(__name__).debug(+ "Failed to run bundle telemetry logger",+ exc_info=True,+ )+++def _incremental_context(+ incremenatal_state_path: Optional[Path],+ codesigned: bool,+ codesign_configuration: CodesignConfiguration,+ codesign_identity: Optional[str],+ codesign_arguments: List[str],+ versioned_if_macos: bool,+) -> Optional[IncrementalContext]:+ action_metadata = action_metadata_if_present(_METADATA_PATH_KEY)+ if action_metadata is None:+ # Environment variable not set, running in non-incremental mode.+ return None+ # If there is no incremental state or we failed to parse it (maybe because of a format change)+ # do a clean (non-incremental) assemble right now but generate proper state for next run.+ incremental_state = (+ _read_incremental_state(incremenatal_state_path)+ if incremenatal_state_path+ else None+ )+ return IncrementalContext(+ metadata=action_metadata,+ state=incremental_state,+ codesigned=codesigned,+ codesign_configuration=codesign_configuration,+ codesign_identity=codesign_identity,+ codesign_arguments=codesign_arguments,+ versioned_if_macos=versioned_if_macos,+ )+++def _read_incremental_state(path: Path) -> Optional[IncrementalState]:+ logging.getLogger(__name__).info(f"Will read incremental state from `{path}`.")+ if not path.exists():+ logging.getLogger(__name__).warning(+ f"File with incremental state doesn't exist at `{path}`."+ )+ return None+ try:+ with path.open() as f:+ return parse_incremental_state(f)+ except Exception:+ logging.getLogger(__name__).exception("Failed to read incremental state")+ return None+ finally:+ # If something goes wrong and we don't delete the file+ # we probably end up in faulty state where incremental state+ # doesn't match the output. Hence delete it early.+ path.unlink()+++def _swift_support_arguments(+ parser: argparse.ArgumentParser,+ args: argparse.Namespace,+) -> Optional[SwiftSupportArguments]:+ if not args.swift_stdlib_command:+ return None+ if not args.binary_destination:+ parser.error(+ "Expected `--binary-destination` argument to be specified when `--swift-stdlib-command` is present."+ )+ if not args.appclips_destination:+ parser.error(+ "Expected `--appclips-destination` argument to be specified when `--swift-stdlib-command` is present."+ )+ if not args.frameworks_destination:+ parser.error(+ "Expected `--frameworks-destination` argument to be specified when `--swift-stdlib-command` is present."+ )+ if not args.extensionkit_extensions_destination:+ parser.error(+ "Expected `--extensionkit-extensions-destination` argument to be specified when `--swift-stdlib-command` is present."+ )+ if not args.plugins_destination:+ parser.error(+ "Expected `--plugins-destination` argument to be specified when `--swift-stdlib-command` is present."+ )+ if not args.platform:+ parser.error(+ "Expected `--platform` argument to be specified when `--swift-stdlib-command` is present."+ )+ if not args.sdk_root:+ parser.error(+ "Expected `--sdk-root` argument to be specified when `--swift-stdlib-command` is present."+ )+ return SwiftSupportArguments(+ swift_stdlib_command=args.swift_stdlib_command,+ binary_destination=args.binary_destination,+ appclips_destination=args.appclips_destination,+ frameworks_destination=args.frameworks_destination,+ extensionkit_extensions_destination=args.extensionkit_extensions_destination,+ plugins_destination=args.plugins_destination,+ platform=args.platform,+ sdk_root=args.sdk_root,+ )+++def _write_incremental_state(+ spec: List[BundleSpecItem],+ items: List[IncrementalStateItem],+ path: Path,+ codesigned: bool,+ codesign_configuration: CodesignConfiguration,+ selected_codesign_identity: Optional[str],+ codesign_arguments: List[str],+ swift_stdlib_paths: List[Path],+ versioned_if_macos: bool,+ incremental_context: IncrementalContext,+) -> None:+ state = IncrementalState(+ items,+ codesigned=codesigned,+ codesign_configuration=codesign_configuration,+ codesigned_on_copy=[+ codesigned_on_copy_item(+ path=Path(i.dst),+ entitlements=(+ Path(i.codesign_entitlements) if i.codesign_entitlements else None+ ),+ incremental_context=incremental_context,+ codesign_flags_override=i.codesign_flags_override,+ extra_codesign_paths=i.extra_codesign_paths,+ )+ for i in spec+ if i.codesign_on_copy+ ],+ codesign_identity=selected_codesign_identity,+ codesign_arguments=codesign_arguments,+ swift_stdlib_paths=swift_stdlib_paths,+ versioned_if_macos=versioned_if_macos,+ )+ path.touch()+ try:+ with path.open(mode="w") as f:+ json.dump(state, f, cls=IncrementalStateJSONEncoder)+ except Exception:+ path.unlink()+ raise+++def _amend_spec_with_build_uuid(+ spec: List[BundleSpecItem],+ resources_destination: Optional[Path],+ tmp_dir: Path,+) -> None:+ build_id = os.environ.get("BUCK_BUILD_ID")+ if not build_id:+ return++ if resources_destination is None:+ raise RuntimeError(+ "`--resources-destination` is required when `--include-build-info-file` is set."+ )++ # There caveats when the build info would be updated - specifically, it would+ # be updated whenever the action runs. When the action runs is more tricky+ # to precisely specify but practically speaking, if the bundling action does+ # not run due to behing a cache hit, the build uuid would be from the last+ # build that produced the cache value.+ #+ # For example, if you did the following:+ # - `buck build //my:app` (build uuid X)+ # - `buck build //my:app` (build uuid Y)+ #+ # Build Y runs no actions at all (nothing invalidated because synthesized+ # files are not inputs to the action), so `BuildInfo.json` would contain+ # uuid X.+ src = tmp_dir / "BuildInfo.json"+ src.write_text(json.dumps({"build_uuid": build_id}, indent=2))+ dst = str(resources_destination / "BuildInfo.json")++ spec.append(BundleSpecItem(src=str(src), dst=dst))+++def _deduplicate_spec(spec: List[BundleSpecItem]) -> List[BundleSpecItem]:+ # It's possible to have the same spec multiple times as different+ # apple_resource() targets can refer to the _same_ resource file.+ #+ # On RE, we're not allowed to overwrite files, so prevent doing+ # identical file copies.+ #+ # Do not reorder spec items to achieve determinism.+ # Rely on the fact that `dict` preserves key order.+ deduplicated_spec = list(dict.fromkeys(spec))+ # Force same sorting as in Buck1 for `SourcePathWithAppleBundleDestination`+ # WARNING: This logic is tightly coupled with how spec filtering is done in `_filter_conflicting_paths` method during incremental bundling. Don't change unless you fully understand what is going on here.+ deduplicated_spec.sort()+ return deduplicated_spec+++if __name__ == "__main__":+ with tempfile.TemporaryDirectory() as spec_temp_dir:+ _main(spec_temp_dir)
@@ -0,0 +1,85 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++from __future__ import annotations++import argparse+import base64+import json+from pathlib import Path++from apple.tools.code_signing.signing_context_types import (+ selection_profile_context_from_signing_context,+)++from .signing_context_data import load_signing_context_data_from_file+++def _main() -> None:+ parser = argparse.ArgumentParser(+ description="Generate a provisioning manifest from a signing context.",+ )+ parser.add_argument(+ "--output",+ required=True,+ type=Path,+ help="Path to the output JSON file.",+ )+ parser.add_argument(+ "--signing-context-path",+ type=Path,+ required=True,+ help="Path to the precomputed signing context JSON.",+ )++ args = parser.parse_args()+ signing_context_data = load_signing_context_data_from_file(+ args.signing_context_path+ )+ selection_profile_context = selection_profile_context_from_signing_context(+ signing_context_data.signing_context+ )++ with open(args.output, "w") as output_file:+ signing_context_json_obj = {+ "version": 1,+ }++ if signing_context_data.selected_identity:+ # Ad hoc and Developer ID signing use the human-readable identity;+ # profile-based signing uses the certificate fingerprint.+ signing_context_json_obj["codesign_identity"] = (+ signing_context_data.selected_identity+ )++ if selection_profile_context:+ selected_profile_info = selection_profile_context.selected_profile_info+ profile_metadata = selected_profile_info.profile+ profile_data = signing_context_data.provisioning_profile_data+ if profile_data is None:+ raise ValueError("Signing context is missing profile data")++ signing_context_json_obj["provisioning_profile"] = {+ "uuid": profile_metadata.uuid,+ "identity": {+ "fingerprint": selected_profile_info.identity.fingerprint,+ "subject_common_name": selected_profile_info.identity.subject_common_name,+ },+ "file_name": profile_metadata.file_path.name,+ "file_data_base64": base64.b64encode(profile_data).decode(),+ }++ json.dump(+ signing_context_json_obj,+ output_file,+ indent=4,+ )+++if __name__ == "__main__":+ _main()
@@ -0,0 +1,75 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import argparse+import logging+from pathlib import Path++from .logging_utils import configure_logging+from .signing_context import (+ add_args_for_signing_context,+ signing_context_and_selected_identity_from_args,+)+from .signing_context_data import write_signing_context_data_to_file+++def _args_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description="Tool which resolves signing context and caches it for downstream bundling and signing_context tools.",+ )+ parser.add_argument(+ "--output",+ required=True,+ type=Path,+ help="Path to the output JSON file containing the signing context.",+ )+ parser.add_argument(+ "--log-level-stderr",+ choices=["debug", "info", "warning", "error", "critical"],+ type=str,+ required=False,+ default="warning",+ help="Logging level for messages written to stderr.",+ )+ parser.add_argument(+ "--log-level-file",+ choices=["debug", "info", "warning", "error", "critical"],+ type=str,+ required=False,+ default="info",+ help="Logging level for messages written to a log file.",+ )++ add_args_for_signing_context(parser)++ return parser+++def _main() -> None:+ parser = _args_parser()+ args = parser.parse_args()++ configure_logging(+ stderr_level=getattr(logging, args.log_level_stderr.upper()),+ file_level=getattr(logging, args.log_level_file.upper()),+ log_path=args.log_file,+ )++ signing_context, selected_identity = (+ signing_context_and_selected_identity_from_args(args)+ )++ write_signing_context_data_to_file(+ path=args.output,+ signing_context=signing_context,+ selected_identity=selected_identity,+ )+++if __name__ == "__main__":+ _main()
@@ -0,0 +1,261 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++from __future__ import annotations++import argparse+import json+import shlex+from pathlib import Path++from apple.tools.code_signing.apple_platform import ApplePlatform+from apple.tools.code_signing.codesign_bundle import (+ signing_context_with_profile_selection,+)+from apple.tools.code_signing.list_codesign_identities import (+ AdHocListCodesignIdentities,+ ListCodesignIdentities,+)+from apple.tools.code_signing.signing_context_types import (+ AdhocSigningContext,+ SigningContextWithProfileSelection,+)+++def add_args_for_signing_context_path(parser: argparse.ArgumentParser) -> None:+ parser.add_argument(+ "--signing-context-path",+ metavar="<SigningContext.json>",+ type=Path,+ required=True,+ help="Path to the precomputed signing context JSON.",+ )+++def add_args_for_bundling_execution(parser: argparse.ArgumentParser) -> None:+ _add_common_execution_args(parser)+++def _add_common_execution_args(parser: argparse.ArgumentParser) -> None:+ parser.add_argument(+ "--codesign",+ action="store_true",+ help="Should the final bundle be codesigned.",+ )+ parser.add_argument(+ "--entitlements",+ metavar="<Entitlements.plist>",+ type=Path,+ required=False,+ help="Path to file with entitlements to be used during code signing. If it's not provided the minimal entitlements are going to be generated.",+ )+ parser.add_argument(+ "--entitlements-suffixed-key-map",+ type=json.loads,+ required=False,+ default={},+ help="JSON map of entitlement key to suffix to append to its values.",+ )+ parser.add_argument(+ "--entitlements-removed-keys",+ type=json.loads,+ required=False,+ default=[],+ help="JSON list of entitlement keys to remove from the entitlements.",+ )+ parser.add_argument(+ "--entitlements-removed-values-map",+ type=json.loads,+ required=False,+ default={},+ help="JSON map of entitlement keys to list of values to remove from that key.",+ )+ parser.add_argument(+ "--info-plist-source",+ metavar="</prepared/Info.plist>",+ type=Path,+ required=False,+ help="Path to Info.plist source file which is used only to make code signing decisions (to be bundled `Info.plist` should be present in spec parameter). Required if code signing is requested.",+ )+ parser.add_argument(+ "--info-plist-destination",+ metavar="<Info.plist>",+ type=Path,+ required=False,+ help="Required if code signing is requested. Bundle relative destination path to Info.plist file if it is present in bundle.",+ )+ parser.add_argument(+ "--platform",+ metavar="<apple platform>",+ type=ApplePlatform,+ required=False,+ help="Required if code signing or Swift support is requested. Apple platform for which the bundle is built.",+ )+ parser.add_argument(+ "--log-file",+ type=Path,+ required=False,+ help="Path to a log file. If present logging will be directed to this file in addition to stderr.",+ )+++def add_args_for_signing_context_selection(+ parser: argparse.ArgumentParser,+) -> None:+ parser.add_argument(+ "--ad-hoc",+ action="store_true",+ help="Perform ad-hoc signing if set.",+ )+ parser.add_argument(+ "--ad-hoc-codesign-identity",+ metavar="<identity>",+ type=str,+ required=False,+ help="Codesign identity to use when ad-hoc signing is performed. Should be present when selection of provisioining profile is requested for ad-hoc signing.",+ )+ parser.add_argument(+ "--codesign-identities-command",+ metavar='<"/signing/identities --available">',+ type=str,+ required=False,+ help="Command listing available code signing identities. If it's not provided `security` utility is assumed to be available and is used.",+ )+ parser.add_argument(+ "--profiles-dir",+ metavar="</provisioning/profiles/directory>",+ type=Path,+ required=False,+ action="append",+ help="Required if non-ad-hoc code signing is requested. Path to directory with provisioning profile files. Can be specified multiple times.",+ )+ parser.add_argument(+ "--embed-provisioning-profile-when-signing-ad-hoc",+ action="store_true",+ help="Perform selection of provisioining profile and embed it into final bundle when ad-hoc signing if set.",+ )+ parser.add_argument(+ "--fast-provisioning-profile-parsing",+ action="store_true",+ help="Uses experimental faster provisioning profile parsing.",+ )+ parser.add_argument(+ "--strict-provisioning-profile-search",+ action="store_true",+ required=False,+ help="Fail code signing if more than one matching profile found.",+ )+ parser.add_argument(+ "--provisioning-profile-filter",+ metavar="<regex>",+ type=str,+ required=False,+ help="Regex to disambiguate multiple matching profiles, evaluated against provisioning profile filename.",+ )+ parser.add_argument(+ "--verify-entitlements",+ action="store_true",+ help="Verify that the entitlements match the provisioning profile.",+ )+ parser.add_argument(+ "--no-check-certificates",+ action="store_true",+ required=False,+ help="Skip the check on code signing identities when selecting provisioning profile.",+ )+++def add_args_for_signing_context(parser: argparse.ArgumentParser) -> None:+ _add_common_execution_args(parser)+ add_args_for_signing_context_selection(parser)+++def signing_context_and_selected_identity_from_args(+ args: argparse.Namespace,+) -> tuple[AdhocSigningContext | SigningContextWithProfileSelection | None, str | None]:+ if args.codesign:+ if not args.info_plist_source:+ raise RuntimeError(+ "Paths to Info.plist source file should be set when code signing is required."+ )+ if not args.info_plist_destination:+ raise RuntimeError(+ "Info.plist destination path should be set when code signing is required."+ )+ if not args.platform:+ raise RuntimeError(+ "Apple platform should be set when code signing is required."+ )+ list_codesign_identities = (+ ListCodesignIdentities.override(+ shlex.split(args.codesign_identities_command)+ )+ if args.codesign_identities_command+ else ListCodesignIdentities.default()+ )+ if args.ad_hoc:+ if args.embed_provisioning_profile_when_signing_ad_hoc:+ if not args.profiles_dir:+ raise RuntimeError(+ "Path to directory with provisioning profile files should be set when selection of provisioining profile is enabled for ad-hoc code signing."+ )+ if not args.ad_hoc_codesign_identity:+ raise RuntimeError(+ "Code signing identity should be set when selection of provisioining profile is enabled for ad-hoc code signing."+ )+ profile_selection_context = signing_context_with_profile_selection(+ info_plist_source=args.info_plist_source,+ info_plist_destination=args.info_plist_destination,+ provisioning_profiles_dirs=args.profiles_dir,+ entitlements_path=args.entitlements,+ platform=args.platform,+ list_codesign_identities=AdHocListCodesignIdentities(+ original=list_codesign_identities,+ subject_common_name=args.ad_hoc_codesign_identity,+ ),+ log_file_path=args.log_file,+ should_use_fast_provisioning_profile_parsing=args.fast_provisioning_profile_parsing,+ strict_provisioning_profile_search=args.strict_provisioning_profile_search,+ provisioning_profile_filter=args.provisioning_profile_filter,+ should_verify_entitlements=args.verify_entitlements,+ no_check_certificates=args.no_check_certificates,+ )+ else:+ profile_selection_context = None+ signing_context = AdhocSigningContext(+ codesign_identity=args.ad_hoc_codesign_identity,+ profile_selection_context=profile_selection_context,+ )+ selected_identity_argument = args.ad_hoc_codesign_identity+ else:+ if not args.profiles_dir:+ raise RuntimeError(+ "Path to directory with provisioning profile files should be set when signing is not ad-hoc."+ )+ signing_context = signing_context_with_profile_selection(+ info_plist_source=args.info_plist_source,+ info_plist_destination=args.info_plist_destination,+ provisioning_profiles_dirs=args.profiles_dir,+ entitlements_path=args.entitlements,+ platform=args.platform,+ list_codesign_identities=list_codesign_identities,+ log_file_path=args.log_file,+ should_use_fast_provisioning_profile_parsing=args.fast_provisioning_profile_parsing,+ strict_provisioning_profile_search=args.strict_provisioning_profile_search,+ provisioning_profile_filter=args.provisioning_profile_filter,+ should_verify_entitlements=args.verify_entitlements,+ no_check_certificates=args.no_check_certificates,+ )+ selected_identity_argument = (+ signing_context.selected_profile_info.identity.fingerprint+ )+ else:+ signing_context = None+ selected_identity_argument = None++ return signing_context, selected_identity_argument
@@ -0,0 +1,157 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++from __future__ import annotations++import base64+import binascii+import json+from dataclasses import dataclass+from pathlib import Path++from apple.tools.code_signing.serialization import (+ expect_dict,+ expect_keys,+ expect_optional_str,+ expect_str,+)+from apple.tools.code_signing.signing_context_types import (+ AdhocSigningContext,+ selection_profile_context_from_signing_context,+ SigningContextWithProfileSelection,+)++_VERSION = 1++SigningContext = AdhocSigningContext | SigningContextWithProfileSelection+++@dataclass(frozen=True)+class SigningContextData:+ signing_context: SigningContext | None+ selected_identity: str | None+ provisioning_profile_data: bytes | None+++def serialize_signing_context_data(+ signing_context: SigningContext | None,+ selected_identity: str | None,+) -> dict[str, object]:+ profile_context = selection_profile_context_from_signing_context(signing_context)+ profile_data = (+ profile_context.selected_profile_info.profile.file_path.read_bytes()+ if profile_context is not None+ else None+ )+ return {+ "version": _VERSION,+ "selected_identity": selected_identity,+ "signing_context": _serialize_signing_context(signing_context),+ "provisioning_profile_data_base64": (+ base64.b64encode(profile_data).decode()+ if profile_data is not None+ else None+ ),+ }+++def _serialize_signing_context(+ signing_context: SigningContext | None,+) -> dict[str, object] | None:+ if signing_context is None:+ return None+ if isinstance(signing_context, SigningContextWithProfileSelection):+ return {"kind": "distribution", "distribution": signing_context.to_dict()}+ if isinstance(signing_context, AdhocSigningContext):+ return {"kind": "adhoc", "adhoc": signing_context.to_dict()}+ raise ValueError(f"Unexpected signing context type: {type(signing_context)}")+++def deserialize_signing_context_data(value: object) -> SigningContextData:+ data = expect_dict(value, "SigningContextData")+ expect_keys(+ data,+ "SigningContextData",+ frozenset(+ {+ "version",+ "selected_identity",+ "signing_context",+ "provisioning_profile_data_base64",+ }+ ),+ )+ version = data["version"]+ if type(version) is not int or version != _VERSION:+ raise ValueError(f"Expected signing context version {_VERSION}, got {version}")++ signing_context = _deserialize_signing_context(data["signing_context"])+ profile_data = _decode_profile_data(data["provisioning_profile_data_base64"])+ profile_context = selection_profile_context_from_signing_context(signing_context)+ if (profile_context is None) != (profile_data is None):+ raise ValueError(+ "provisioning_profile_data_base64 must be present exactly when a "+ "provisioning profile is selected"+ )++ return SigningContextData(+ signing_context=signing_context,+ selected_identity=expect_optional_str(+ data["selected_identity"], "SigningContextData.selected_identity"+ ),+ provisioning_profile_data=profile_data,+ )+++def _deserialize_signing_context(value: object) -> SigningContext | None:+ if value is None:+ return None+ data = expect_dict(value, "SigningContextData.signing_context")+ kind = expect_str(data.get("kind"), "SigningContextData.signing_context.kind")+ if kind == "distribution":+ expect_keys(+ data,+ "SigningContextData.signing_context",+ frozenset({"kind", "distribution"}),+ )+ return SigningContextWithProfileSelection.from_dict(data["distribution"])+ if kind == "adhoc":+ expect_keys(+ data,+ "SigningContextData.signing_context",+ frozenset({"kind", "adhoc"}),+ )+ return AdhocSigningContext.from_dict(data["adhoc"])+ raise ValueError(f"Unknown signing context kind: {kind}")+++def _decode_profile_data(value: object) -> bytes | None:+ encoded = expect_optional_str(+ value, "SigningContextData.provisioning_profile_data_base64"+ )+ if encoded is None:+ return None+ try:+ return base64.b64decode(encoded, validate=True)+ except binascii.Error as error:+ raise ValueError("Invalid provisioning profile base64 data") from error+++def write_signing_context_data_to_file(+ path: Path,+ signing_context: SigningContext | None,+ selected_identity: str | None,+) -> None:+ data = serialize_signing_context_data(signing_context, selected_identity)+ with path.open("w") as output:+ json.dump(data, output, indent=4)+++def load_signing_context_data_from_file(path: Path) -> SigningContextData:+ with path.open() as source:+ return deserialize_signing_context_data(json.load(source))
@@ -0,0 +1,219 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import datetime+import json+import unittest+from pathlib import Path+from tempfile import TemporaryDirectory++from apple.tools.code_signing.identity import CodeSigningIdentity+from apple.tools.code_signing.info_plist_metadata import InfoPlistMetadata+from apple.tools.code_signing.provisioning_profile_metadata import (+ ProvisioningProfileMetadata,+)+from apple.tools.code_signing.provisioning_profile_selection import (+ SelectedProvisioningProfileInfo,+)+from apple.tools.code_signing.signing_context_types import (+ AdhocSigningContext,+ SigningContextWithProfileSelection,+)++from .signing_context_data import (+ deserialize_signing_context_data,+ serialize_signing_context_data,+)+++class TestSigningContextData(unittest.TestCase):+ def setUp(self) -> None:+ self.temp_dir = TemporaryDirectory()+ self.profile_path = Path(self.temp_dir.name) / "profile.mobileprovision"+ self.profile_path.write_bytes(b"profile data")++ def tearDown(self) -> None:+ self.temp_dir.cleanup()++ def test_null_context(self):+ data = serialize_signing_context_data(None, None)+ context_data = deserialize_signing_context_data(data)+ self.assertIsNone(context_data.signing_context)+ self.assertIsNone(context_data.selected_identity)+ self.assertIsNone(context_data.provisioning_profile_data)++ def test_adhoc_without_profile(self):+ ctx = AdhocSigningContext(codesign_identity="-", profile_selection_context=None)+ data = serialize_signing_context_data(ctx, "-")+ json_str = json.dumps(data)+ loaded = json.loads(json_str)+ context_data = deserialize_signing_context_data(loaded)+ ctx2 = context_data.signing_context+ self.assertEqual(context_data.selected_identity, "-")+ self.assertIsNone(context_data.provisioning_profile_data)+ assert isinstance(ctx2, AdhocSigningContext)+ self.assertEqual(ctx2.codesign_identity, "-")+ self.assertIsNone(ctx2.profile_selection_context)++ def test_distribution_context(self):+ expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)+ creation = datetime.datetime(2024, 1, 1, 12, 0, 0)+ profile = ProvisioningProfileMetadata(+ file_path=self.profile_path,+ uuid="UUID-1234",+ expiration_date=expiration,+ platforms=frozenset(["iOS"]),+ developer_certificate_fingerprints=frozenset(+ ["ABCDEF1234567890ABCDEF1234567890ABCDEF12"]+ ),+ entitlements={"application-identifier": "TEAM.com.test.app"},+ creation_date=creation,+ provisions_all_devices=False,+ provisioned_devices=["device1"],+ )+ identity = CodeSigningIdentity(+ fingerprint="ABCDEF1234567890ABCDEF1234567890ABCDEF12",+ subject_common_name="Apple Development: Test",+ )+ selected_info = SelectedProvisioningProfileInfo(+ profile=profile, identity=identity+ )+ info_plist_metadata = InfoPlistMetadata(+ bundle_id="com.test.app", bundle_type="APPL", is_watchos_app=False+ )+ ctx = SigningContextWithProfileSelection(+ info_plist_source=Path("/tmp/Info.plist"),+ info_plist_destination=Path("Info.plist"),+ info_plist_metadata=info_plist_metadata,+ selected_profile_info=selected_info,+ )+ data = serialize_signing_context_data(ctx, identity.fingerprint)+ json_str = json.dumps(data)+ loaded = json.loads(json_str)+ context_data = deserialize_signing_context_data(loaded)+ ctx2 = context_data.signing_context+ assert isinstance(ctx2, SigningContextWithProfileSelection)+ self.assertEqual(context_data.selected_identity, identity.fingerprint)+ self.assertEqual(context_data.provisioning_profile_data, b"profile data")+ self.assertEqual(ctx2.info_plist_source, Path("/tmp/Info.plist"))+ self.assertEqual(ctx2.info_plist_destination, Path("Info.plist"))+ self.assertEqual(ctx2.info_plist_metadata.bundle_id, "com.test.app")+ self.assertEqual(ctx2.selected_profile_info.profile.uuid, "UUID-1234")+ self.assertEqual(+ ctx2.selected_profile_info.profile.file_path,+ self.profile_path,+ )+ self.assertEqual(+ ctx2.selected_profile_info.identity.fingerprint, identity.fingerprint+ )+ self.assertEqual(+ ctx2.selected_profile_info.profile.provisions_all_devices, False+ )+ self.assertEqual(+ ctx2.selected_profile_info.profile.provisioned_devices, ["device1"]+ )++ def test_adhoc_with_profile(self):+ expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)+ profile = ProvisioningProfileMetadata(+ file_path=self.profile_path,+ uuid="UUID-5678",+ expiration_date=expiration,+ platforms=frozenset(["iOS"]),+ developer_certificate_fingerprints=frozenset(+ ["AAAABBBBCCCCDDDDEEEEFFFF0000111122223333"]+ ),+ entitlements={},+ creation_date=None,+ provisions_all_devices=True,+ provisioned_devices=None,+ )+ identity = CodeSigningIdentity(+ fingerprint="AAAABBBBCCCCDDDDEEEEFFFF0000111122223333",+ subject_common_name="Apple Development: Adhoc",+ )+ selected_info = SelectedProvisioningProfileInfo(+ profile=profile, identity=identity+ )+ info_plist_metadata = InfoPlistMetadata(+ bundle_id="com.test.app", bundle_type="APPL", is_watchos_app=False+ )+ distribution_ctx = SigningContextWithProfileSelection(+ info_plist_source=Path("/tmp/Info.plist"),+ info_plist_destination=Path("Info.plist"),+ info_plist_metadata=info_plist_metadata,+ selected_profile_info=selected_info,+ )+ adhoc_ctx = AdhocSigningContext(+ codesign_identity="Apple Development: Adhoc",+ profile_selection_context=distribution_ctx,+ )+ data = serialize_signing_context_data(adhoc_ctx, "Apple Development: Adhoc")+ json_str = json.dumps(data)+ loaded = json.loads(json_str)+ context_data = deserialize_signing_context_data(loaded)+ ctx2 = context_data.signing_context+ assert isinstance(ctx2, AdhocSigningContext)+ self.assertEqual(ctx2.codesign_identity, "Apple Development: Adhoc")+ assert ctx2.profile_selection_context is not None+ self.assertEqual(+ ctx2.profile_selection_context.selected_profile_info.profile.uuid,+ "UUID-5678",+ )+ self.assertEqual(context_data.selected_identity, "Apple Development: Adhoc")+ self.assertEqual(context_data.provisioning_profile_data, b"profile data")++ def test_version_mismatch_raises(self):+ bad_data = {+ "version": 999,+ "selected_identity": None,+ "signing_context": None,+ "provisioning_profile_data_base64": None,+ }+ with self.assertRaises(ValueError) as cm:+ deserialize_signing_context_data(bad_data)++ msg = str(cm.exception)+ self.assertIn("Expected signing context version", msg)+ self.assertIn("999", msg)++ bad_data_old = {+ "version": 2,+ "selected_identity": "-",+ "signing_context": {+ "kind": "adhoc",+ "adhoc": {"codesign_identity": "-", "profile_selection_context": None},+ },+ "provisioning_profile_data_base64": None,+ }+ with self.assertRaises(ValueError):+ deserialize_signing_context_data(bad_data_old)++ def test_profile_context_requires_profile_data(self):+ profile = ProvisioningProfileMetadata(+ file_path=self.profile_path,+ uuid="UUID",+ expiration_date=datetime.datetime(2025, 1, 1),+ platforms=frozenset(["iOS"]),+ developer_certificate_fingerprints=frozenset(["ABC"]),+ entitlements={},+ )+ context = SigningContextWithProfileSelection(+ info_plist_source=Path("/tmp/Info.plist"),+ info_plist_destination=Path("Info.plist"),+ info_plist_metadata=InfoPlistMetadata("com.test", "APPL", False),+ selected_profile_info=SelectedProvisioningProfileInfo(+ profile=profile,+ identity=CodeSigningIdentity("ABC", "Developer"),+ ),+ )+ data = serialize_signing_context_data(context, "ABC")+ data["provisioning_profile_data_base64"] = None++ with self.assertRaisesRegex(ValueError, "must be present exactly"):+ deserialize_signing_context_data(data)
@@ -0,0 +1,77 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.+++from __future__ import annotations++from pathlib import Path+from typing import Any++from apple.tools.code_signing.signing_context_types import (+ AdhocSigningContext,+ selection_profile_context_from_signing_context,+ SigningContextWithProfileSelection,+)++from .signing_context_data import load_signing_context_data_from_file+++def build_signing_info(+ signing_context: AdhocSigningContext | SigningContextWithProfileSelection | None,+ selected_identity: str | None,+) -> dict[str, Any]:+ if signing_context is None:+ return {}++ if isinstance(signing_context, AdhocSigningContext):+ codesign_type = "adhoc"+ elif isinstance(signing_context, SigningContextWithProfileSelection):+ codesign_type = "distribution"+ else:+ raise RuntimeError(f"Unexpected signing context type: {type(signing_context)}")++ signing_info: dict[str, Any] = {+ "codesign_type": codesign_type,+ }++ if selected_identity:+ signing_info["codesign_identity"] = selected_identity++ selection_profile_context = selection_profile_context_from_signing_context(+ signing_context+ )++ if selection_profile_context:+ selected_profile_info = selection_profile_context.selected_profile_info+ profile_metadata = selected_profile_info.profile+ if profile_metadata.provisioned_devices is not None:+ provisioned_devices = "list"+ elif profile_metadata.provisions_all_devices:+ provisioned_devices = "all"+ else:+ provisioned_devices = "none"++ signing_info["provisioning_profile"] = {+ "uuid": profile_metadata.uuid,+ "file_name": profile_metadata.file_path.name,+ "provisioned_devices": provisioned_devices,+ }+ signing_info["signing_certificate"] = {+ "fingerprint": selected_profile_info.identity.fingerprint,+ "subject_common_name": selected_profile_info.identity.subject_common_name,+ }++ return signing_info+++def build_signing_info_from_file(path: Path) -> dict[str, Any]:+ signing_context_data = load_signing_context_data_from_file(path)+ return build_signing_info(+ signing_context_data.signing_context,+ signing_context_data.selected_identity,+ )
@@ -0,0 +1,44 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import argparse+import json+from pathlib import Path++from .signing_info import build_signing_info_from_file+++def _main() -> None:+ parser = argparse.ArgumentParser(+ description="Tool which outputs signing-info JSON from a precomputed signing context. "+ "This is cheap (no profile directory scan, no security tool) and allows the "+ "[signing-info] subtarget to be built without running bundling.",+ )+ parser.add_argument(+ "--signing-context-path",+ type=Path,+ required=True,+ help="Path to precomputed signing context JSON.",+ )+ parser.add_argument(+ "--output",+ type=Path,+ required=True,+ help="Path to the output signing-info JSON file.",+ )++ args = parser.parse_args()++ signing_info = build_signing_info_from_file(args.signing_context_path)++ with open(args.output, "w") as f:+ json.dump(signing_info, f, indent=4)+++if __name__ == "__main__":+ _main()
@@ -0,0 +1,130 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import datetime+import unittest+from pathlib import Path++from apple.tools.code_signing.identity import CodeSigningIdentity+from apple.tools.code_signing.info_plist_metadata import InfoPlistMetadata+from apple.tools.code_signing.provisioning_profile_metadata import (+ ProvisioningProfileMetadata,+)+from apple.tools.code_signing.provisioning_profile_selection import (+ SelectedProvisioningProfileInfo,+)+from apple.tools.code_signing.signing_context_types import (+ AdhocSigningContext,+ SigningContextWithProfileSelection,+)++from .signing_info import build_signing_info+++class TestSigningInfo(unittest.TestCase):+ def test_no_signing_context(self):+ info = build_signing_info(None, None)+ self.assertEqual(info, {})++ def test_adhoc_without_profile(self):+ ctx = AdhocSigningContext(codesign_identity="-", profile_selection_context=None)+ info = build_signing_info(ctx, "-")+ self.assertEqual(info["codesign_type"], "adhoc")+ self.assertEqual(info["codesign_identity"], "-")+ self.assertNotIn("provisioning_profile", info)++ def test_distribution_with_devices_list(self):+ expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)+ profile = ProvisioningProfileMetadata(+ file_path=Path("/tmp/my.mobileprovision"),+ uuid="UUID-123",+ expiration_date=expiration,+ platforms=frozenset(["iOS"]),+ developer_certificate_fingerprints=frozenset(["ABC"]),+ entitlements={},+ creation_date=None,+ provisions_all_devices=False,+ provisioned_devices=["dev1", "dev2"],+ )+ identity = CodeSigningIdentity(+ fingerprint="ABC", subject_common_name="Apple Dev"+ )+ selected = SelectedProvisioningProfileInfo(profile=profile, identity=identity)+ metadata = InfoPlistMetadata(+ bundle_id="com.test", bundle_type="APPL", is_watchos_app=False+ )+ ctx = SigningContextWithProfileSelection(+ info_plist_source=Path("/tmp/Info.plist"),+ info_plist_destination=Path("Info.plist"),+ info_plist_metadata=metadata,+ selected_profile_info=selected,+ )+ info = build_signing_info(ctx, "ABC")+ self.assertEqual(info["codesign_type"], "distribution")+ self.assertEqual(info["codesign_identity"], "ABC")+ self.assertEqual(info["provisioning_profile"]["uuid"], "UUID-123")+ self.assertEqual(+ info["provisioning_profile"]["file_name"], "my.mobileprovision"+ )+ self.assertEqual(info["provisioning_profile"]["provisioned_devices"], "list")+ self.assertEqual(info["signing_certificate"]["fingerprint"], "ABC")++ def test_provisioned_devices_all_and_none(self):+ expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)++ profile_all = ProvisioningProfileMetadata(+ file_path=Path("/tmp/all.mobileprovision"),+ uuid="UUID-ALL",+ expiration_date=expiration,+ platforms=frozenset(["iOS"]),+ developer_certificate_fingerprints=frozenset(["ABC"]),+ entitlements={},+ creation_date=None,+ provisions_all_devices=True,+ provisioned_devices=None,+ )+ identity = CodeSigningIdentity(fingerprint="ABC", subject_common_name="Dev")+ selected_all = SelectedProvisioningProfileInfo(+ profile=profile_all, identity=identity+ )+ metadata = InfoPlistMetadata(+ bundle_id="com.test", bundle_type="APPL", is_watchos_app=False+ )+ ctx_all = SigningContextWithProfileSelection(+ info_plist_source=Path("/tmp/Info.plist"),+ info_plist_destination=Path("Info.plist"),+ info_plist_metadata=metadata,+ selected_profile_info=selected_all,+ )+ info_all = build_signing_info(ctx_all, "ABC")+ self.assertEqual(info_all["provisioning_profile"]["provisioned_devices"], "all")++ profile_none = ProvisioningProfileMetadata(+ file_path=Path("/tmp/none.mobileprovision"),+ uuid="UUID-NONE",+ expiration_date=expiration,+ platforms=frozenset(["iOS"]),+ developer_certificate_fingerprints=frozenset(["ABC"]),+ entitlements={},+ creation_date=None,+ provisions_all_devices=False,+ provisioned_devices=None,+ )+ selected_none = SelectedProvisioningProfileInfo(+ profile=profile_none, identity=identity+ )+ ctx_none = SigningContextWithProfileSelection(+ info_plist_source=Path("/tmp/Info.plist"),+ info_plist_destination=Path("Info.plist"),+ info_plist_metadata=metadata,+ selected_profile_info=selected_none,+ )+ info_none = build_signing_info(ctx_none, "ABC")+ self.assertEqual(+ info_none["provisioning_profile"]["provisioned_devices"], "none"+ )
@@ -0,0 +1,85 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import logging+import os+import shlex+import shutil+import subprocess+import tempfile+from dataclasses import dataclass+from pathlib import Path+from typing import List, Union++_LOGGER: logging.Logger = logging.getLogger(__name__)+++@dataclass+class SwiftSupportArguments:+ swift_stdlib_command: str+ binary_destination: Path+ appclips_destination: Path+ frameworks_destination: Path+ extensionkit_extensions_destination: Path+ plugins_destination: Path+ platform: str+ sdk_root: Path+++def run_swift_stdlib_tool(bundle_path: Path, args: SwiftSupportArguments) -> List[Path]:+ # TODO(T181556849) when incremental bundling is on, binary, frameworks and plugins are not changed, signing identity is unchanged skip this step.+ bundle_relative_output_paths = []+ with tempfile.TemporaryDirectory() as tmp_dir:+ # When signing, swift-stdlib-tool needs a proper PATH environment variable.+ # Assume the current environment has it already.+ env = os.environ.copy()+ # xcrun doesn't like relative paths+ env["SDKROOT"] = os.path.abspath(args.sdk_root)+ cmd = _execution_command(bundle_path, args, tmp_dir)+ _LOGGER.info(+ f"Running Swift stdlib tool with command: `{cmd}` and environment `{env}`."+ )+ result = subprocess.run(cmd, env=env)+ result.check_returncode()+ outputs = sorted(os.listdir(tmp_dir))+ frameworks_path = bundle_path / args.frameworks_destination+ if outputs:+ frameworks_path.mkdir(exist_ok=True)+ for output in outputs:+ shutil.move(os.path.join(tmp_dir, output), frameworks_path)+ bundle_relative_output_paths = [+ args.frameworks_destination / o for o in outputs+ ]+ return bundle_relative_output_paths+++def _execution_command(+ bundle_path: Path,+ args: SwiftSupportArguments,+ tmp_dir: str,+) -> List[Union[str, Path]]:+ return shlex.split(args.swift_stdlib_command) + [+ "--copy",+ "--strip-bitcode",+ "--scan-executable",+ bundle_path / args.binary_destination,+ "--scan-executable",+ bundle_path / args.appclips_destination,+ "--scan-folder",+ bundle_path / args.frameworks_destination,+ "--scan-folder",+ bundle_path / args.extensionkit_extensions_destination,+ "--scan-folder",+ bundle_path / args.plugins_destination,+ "--destination",+ tmp_dir,+ "--platform",+ args.platform,+ ]
@@ -0,0 +1,6 @@+{+ "version": 2,+ "data": {+ "something": []+ }+}
@@ -0,0 +1,6 @@+{+ "version": 7,+ "data": {+ "something": []+ }+}
@@ -0,0 +1,2 @@+{+ "version":
@@ -0,0 +1,13 @@+{+ "version": 1,+ "digests": [+ {+ "path": "repo/foo.txt",+ "digest": "foo_digest"+ },+ {+ "path": "buck-out/bar.txt",+ "digest": "bar_digest"+ }+ ]+}
@@ -0,0 +1,48 @@+{+ "items": [+ {+ "source": "repo/foo.txt",+ "destination_relative_to_bundle": "foo.txt",+ "digest": "foo_digest"+ },+ {+ "source": "buck-out/bar.txt",+ "destination_relative_to_bundle": "Resources/bar.txt",+ "digest": "bar_digest"+ },+ {+ "source": "buck-out/bar",+ "destination_relative_to_bundle": "Resources/bar",+ "resolved_symlink": "bar.txt"+ }+ ],+ "codesign_configuration": null,+ "codesigned": true,+ "codesigned_on_copy": [+ {+ "path": "Resources/bar.txt"+ },+ {+ "path": "Resources/baz.txt",+ "entitlements_digest": "abc"+ },+ {+ "path": "Resources/qux.txt",+ "codesign_flags_override": ["--deep", "--force"]+ },+ {+ "path": "Resources/Parent.framework",+ "extra_codesign_paths": ["Frameworks/Base.framework"]+ }+ ],+ "codesign_identity": "Johny Appleseed",+ "codesign_arguments": [+ "--force",+ "--deep"+ ],+ "versioned_if_macos": true,+ "swift_stdlib_paths": [+ "Frameworks/libswiftCore.dylib"+ ],+ "version": 8+}
@@ -0,0 +1,89 @@+load("@prelude//apple/tools:defs.bzl", "meta_python_test")+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("build_infra")++source_listing()++configured_alias(+ name = "dummy_binary_for_signing_configured",+ actual = ":dummy_binary_for_signing",+ platform = "config//platform/macos:base",+)++platform(+ name = "dummy_binary_for_signing_platform",+ constraint_values = [+ "config//cpu/constraints:arm64",+ ],+ deps = [+ "config//platform/macos:base",+ ],+)++cxx_binary(+ name = "dummy_binary_for_signing",+ srcs = ["dummy_binary_for_signing.c"],+ default_target_platform = ":dummy_binary_for_signing_platform",+)++python_library(+ name = "apple_platform_lib",+ srcs = ["apple_platform.py"],+ visibility = ["PUBLIC"],+)++python_library(+ name = "serialization",+ srcs = ["serialization.py"],+ typing = True,+ visibility = ["PUBLIC"],+)++python_library(+ name = "lib",+ srcs = glob(+ [+ "*.py",+ ],+ exclude = [+ "*_test.py",+ "main.py",+ "apple_platform.py",+ "serialization.py",+ ],+ ),+ resources = [":dummy_binary_for_signing_configured"],+ visibility = ["PUBLIC"],+ deps = [+ "prelude//apple/tools:plistlib_utils",+ "prelude//apple/tools/info_plist_processor:process",+ # @oss-disable[end= ]: "prelude//apple/tools/meta_only:codesign_diagnostics_text_lib",+ # @oss-disable[end= ]: "prelude//apple/tools/meta_only/codesign_rust:check_adhoc_signature_lib",+ # @oss-disable[end= ]: "prelude//apple/tools/meta_only/entitlements_mismatch:check_entitlements_lib",+ ":apple_platform_lib",+ ":serialization",+ ],+)++meta_python_test(+ name = "tests",+ srcs = glob(["*_test.py"]),+ resources = glob([+ "test_resources/*",+ ]),+ deps = [+ "fbsource//third-party/pypi/setuptools:setuptools",+ ":lib",+ ],+)++python_binary(+ name = "codesign_bundle",+ main = "main.py",+ visibility = ["PUBLIC"],+ deps = [+ "fbsource//third-party/pypi/typed-argument-parser:typed-argument-parser",+ ":lib",+ ],+)
@@ -0,0 +1,74 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++from __future__ import annotations++import re+from dataclasses import dataclass+from enum import Enum+from typing import Any, Dict, Optional+++@dataclass+class AppId:+ team_id: str+ bundle_id: str++ class _ReGroupName(str, Enum):+ team_id = "team_id"+ bundle_id = "bundle_id"++ _re_string: str = "^(?P<{team_id}>[A-Z0-9]{{10}})\\.(?P<{bundle_id}>.+)$".format(+ team_id=_ReGroupName.team_id.value,+ bundle_id=_ReGroupName.bundle_id.value,+ )+ _re_pattern: re.Pattern[str] = re.compile(_re_string)++ # Takes a application identifier and splits it into Team ID and bundle ID.+ # Prefix is always a ten-character alphanumeric sequence. Bundle ID may be a fully-qualified name or a wildcard ending in *.+ @classmethod+ def from_string(cls, string: str) -> AppId:+ match = re.match(cls._re_pattern, string)+ if not match:+ raise RuntimeError(+ "Malformed app ID string: '{}'. "+ "We expected a prefix of a ten-character alphanumeric sequence and a Bundle ID which may be a fully-qualified name or a wildcard ending in '*'.".format(+ string+ )+ )+ return AppId(+ match.group(cls._ReGroupName.team_id.value),+ match.group(cls._ReGroupName.bundle_id.value),+ )++ # Returns the App ID if it can be inferred from keys in the entitlement. Otherwise, it returns `None`.+ @staticmethod+ def infer_from_entitlements(entitlements: Dict[str, Any]) -> Optional[AppId]:+ try:+ keychain_access_groups = entitlements.get("keychain-access-groups")+ if keychain_access_groups:+ app_id_string = keychain_access_groups[0]+ return AppId.from_string(app_id_string)++ application_identifier = entitlements.get("application-identifier")+ if application_identifier:+ return AppId.from_string(application_identifier)++ team_identifier = entitlements.get("com.apple.developer.team-identifier")+ bundle_id = entitlements.get("CFBundleIdentifier")+ if team_identifier and bundle_id:+ app_id_string = f"{team_identifier}.{bundle_id}"+ return AppId.from_string(app_id_string)++ return None+ except Exception as e:+ raise RuntimeError(+ "Error when parsing the entitlements for the app ID: {}".format(e)+ )
@@ -0,0 +1,64 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import importlib.resources+import plistlib+import unittest++from .app_id import AppId+++class TestAppId(unittest.TestCase):+ def test_string_parsing(self):+ result = AppId.from_string("ABCDE12345.com.example.TestApp")+ expected = AppId("ABCDE12345", "com.example.TestApp")+ self.assertEqual(expected, result)++ result = AppId.from_string("ABCDE12345.*")+ expected = AppId("ABCDE12345", "*")+ self.assertEqual(expected, result)++ with self.assertRaisesRegex(+ RuntimeError,+ "Malformed app ID string: 'invalid.'. We expected a prefix of a ten-character alphanumeric sequence and a Bundle ID which may be a fully-qualified name or a wildcard ending in '*'.",+ ):+ _ = AppId.from_string("invalid.")++ def test_entitlements_parsing(self):+ expected = AppId("ABCDE12345", "com.example.TestApp")+ test_plist_files = [+ "test_resources/test1.plist",+ "test_resources/test2.plist",+ "test_resources/test3.plist",+ ]++ package = importlib.resources.files(__package__)+ for file in test_plist_files:+ with (package / file).open("rb") as f:+ entitlements = plistlib.load(f)+ result = AppId.infer_from_entitlements(entitlements)+ self.assertEqual(expected, result)++ invalid_file = b"""<?xml version="1.0" encoding="UTF-8"?>+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+ <plist version="1.0">+ <dict>+ <key>keychain-access-groups</key>+ <array>+ <string>com.facebook.CommonTestHost</string>+ </array>p+ </dict>+ </plist>"""++ invalid_entitlement = plistlib.loads(invalid_file)+ with self.assertRaisesRegex(+ RuntimeError,+ "Error when parsing the entitlements for the app ID: Malformed app ID string: 'com.facebook.CommonTestHost'. "+ "We expected a prefix of a ten-character alphanumeric sequence and a Bundle ID which may be a fully-qualified name or a wildcard ending in '*'.",+ ):+ AppId.infer_from_entitlements(invalid_entitlement)
@@ -0,0 +1,50 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++from enum import Enum+from typing import Optional+++class ApplePlatform(str, Enum):+ macos = "macosx"+ ios_device = "iphoneos"+ ios_simulator = "iphonesimulator"+ watch_device = "watchos"+ watch_simulator = "watchsimulator"+ tv_device = "appletvos"+ tv_simulator = "appletvsimulator"+ mac_catalyst = "maccatalyst"+ driver_kit = "driverkit"++ def is_desktop(self) -> bool:+ return self == ApplePlatform.macos or self == ApplePlatform.mac_catalyst++ def provisioning_profile_name(self) -> Optional[str]:+ """+ Returns:+ The platform name as it could be found inside provisioning profiles and used to match them.+ Not all platforms use provisioning profiles, those will return `None`.+ """+ if self == ApplePlatform.ios_device or self == ApplePlatform.watch_device:+ return "iOS"+ elif self == ApplePlatform.tv_device:+ return "tvOS"+ else:+ return None++ def embedded_provisioning_profile_path(self) -> str:+ """+ Returns:+ The name of the provisioning profile in the final application bundle.+ """+ if self.is_desktop():+ return "Contents/embedded.provisionprofile"+ else:+ return "embedded.mobileprovision"
@@ -0,0 +1,914 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import asyncio+import importlib.resources+import json+import logging+import os+import shutil+import subprocess+import sys+import tempfile+import uuid+from contextlib import ExitStack+from dataclasses import dataclass+from enum import Enum+from pathlib import Path+from typing import Any, cast, Dict, List, Optional, Union++from apple.tools.plistlib_utils import detect_format_and_load++# @oss-disable[end= ]: from ..meta_only.codesign_diagnostics_text import (+ # @oss-disable[end= ]: CodesignDiagnosticsText,+# @oss-disable[end= ]: )+# @oss-disable[end= ]: from ..meta_only.entitlements_mismatch.check_entitlements import (+ # @oss-disable[end= ]: verify_entitlements,+# @oss-disable[end= ]: )+from .apple_platform import ApplePlatform+from .codesign_command_factory import (+ DefaultCodesignCommandFactory,+ DryRunCodesignCommandFactory,+ generate_codesign_manifest,+ ICodesignCommandFactory,+ ManifestCodesignCommandFactory,+)++from .codesign_diagnostics_text import CodesignDiagnosticsText # @oss-enable+from .fast_adhoc import is_fast_adhoc_codesign_allowed, should_skip_adhoc_signing_path+from .identity import CodeSigningIdentity+from .info_plist_metadata import InfoPlistMetadata+from .list_codesign_identities import IListCodesignIdentities+from .prepare_code_signing_entitlements import (+ postprocess_entitlements,+ prepare_code_signing_entitlements,+)+from .prepare_info_plist import prepare_info_plist+from .provisioning_profile_diagnostics import (+ interpret_provisioning_profile_diagnostics,+ IProvisioningProfileDiagnostics,+)+from .provisioning_profile_metadata import ProvisioningProfileMetadata+from .provisioning_profile_selection import (+ CodeSignProvisioningError,+ select_best_provisioning_profile_core,+ SelectedProvisioningProfileInfo,+)+from .read_provisioning_profile_command_factory import (+ DefaultReadProvisioningProfileCommandFactory,+ IReadProvisioningProfileCommandFactory,+)+from .signing_context_types import (+ AdhocSigningContext,+ selection_profile_context_from_signing_context,+ SigningContextWithProfileSelection,+)++_default_read_provisioning_profile_command_factory = (+ DefaultReadProvisioningProfileCommandFactory()+)++_LOGGER: logging.Logger = logging.getLogger(__name__)+++@dataclass+class CodesignedPath:+ path: Path+ """+ Path relative to bundle root which needs to be codesigned+ """+ entitlements: Optional[Path]+ """+ Path to entitlements to be used when codesigning, relative to buck project+ """+ flags: List[str]+ """+ Flags to be passed to codesign command when codesigning this particular path+ """+ extra_file_paths: Optional[List[Path]]+ """+ Extra paths to be codesign. Applicable to dry-run codesigning only.+ """+++def _verify_entitlements(+ entitlements_path: Optional[Path],+ profile_path: Path,+ platform: ApplePlatform,+) -> None:+ result = verify_entitlements(+ entitlements_path,+ profile_path,+ platform=platform,+ )+ if result == 1:+ sys.exit(1)+++def _log_codesign_identities(+ list_codesign_identities: IListCodesignIdentities,+ identities: List[CodeSigningIdentity],+) -> None:+ if len(identities) == 0:+ _LOGGER.warning("ZERO codesign identities available")+ _LOGGER.warning(+ f"Identities were retrieved by command: {list_codesign_identities.raw_command()}"+ )+ else:+ _LOGGER.info("Listing available codesign identities")+ for identity in identities:+ _LOGGER.info(+ f" Subject Common Name: {identity.subject_common_name}, Fingerprint: {identity.fingerprint}"+ )+++def _read_profiles_from_dir(+ profiles_dir: Path,+ should_use_fast_provisioning_profile_parsing: bool,+) -> List[ProvisioningProfileMetadata]:+ read_provisioning_profile_command_factory = (+ _default_read_provisioning_profile_command_factory+ )+ if should_use_fast_provisioning_profile_parsing:+ return asyncio.run(+ _fast_read_provisioning_profiles_async(+ profiles_dir,+ read_provisioning_profile_command_factory,+ )+ )+ else:+ return _read_provisioning_profiles(+ profiles_dir,+ read_provisioning_profile_command_factory,+ )+++def _try_select_from_profiles_dir(+ profiles_dir: Path,+ info_plist_metadata: InfoPlistMetadata,+ identities: List[CodeSigningIdentity],+ entitlements: Optional[Dict[str, Any]],+ platform: ApplePlatform,+ should_use_fast_provisioning_profile_parsing: bool,+ strict_provisioning_profile_search: bool,+ provisioning_profile_filter: Optional[str],+ no_check_certificates: bool,+) -> tuple[+ Optional[SelectedProvisioningProfileInfo],+ Optional[List[ProvisioningProfileMetadata]],+ Optional[List[IProvisioningProfileDiagnostics]],+]:+ provisioning_profiles = _read_profiles_from_dir(+ profiles_dir,+ should_use_fast_provisioning_profile_parsing,+ )+ if not provisioning_profiles:+ return None, None, None+ selected_profile_info, mismatches = select_best_provisioning_profile_core(+ info_plist_metadata,+ identities,+ provisioning_profiles,+ entitlements,+ platform,+ strict_provisioning_profile_search,+ provisioning_profile_filter,+ no_check_certificates,+ )+ return selected_profile_info, provisioning_profiles, mismatches+++def _select_best_provisioning_profile(+ info_plist_metadata: InfoPlistMetadata,+ provisioning_profiles_dirs: List[Path],+ entitlements_path: Optional[Path],+ platform: ApplePlatform,+ list_codesign_identities: IListCodesignIdentities,+ should_use_fast_provisioning_profile_parsing: bool,+ strict_provisioning_profile_search: bool,+ provisioning_profile_filter: Optional[str],+ no_check_certificates: bool = False,+ log_file_path: Optional[Path] = None,+) -> SelectedProvisioningProfileInfo:+ if no_check_certificates:+ identities = []+ _LOGGER.info(+ "no_check_certificates is set to True, so we will ignore codesign identities"+ )+ else:+ identities = list_codesign_identities.list_codesign_identities()+ _log_codesign_identities(list_codesign_identities, identities)+ _LOGGER.info(+ f"Fast provisioning profile parsing enabled: {should_use_fast_provisioning_profile_parsing}"+ )+ entitlements = _read_entitlements_file(entitlements_path)++ # Try each profiles directory in order, returning as soon as a match is found+ all_mismatches: List[IProvisioningProfileDiagnostics] = []+ has_profiles = False+ for profiles_dir in provisioning_profiles_dirs:+ selected_profile_info, profiles, mismatches = _try_select_from_profiles_dir(+ profiles_dir=profiles_dir,+ info_plist_metadata=info_plist_metadata,+ identities=identities,+ entitlements=entitlements,+ platform=platform,+ should_use_fast_provisioning_profile_parsing=should_use_fast_provisioning_profile_parsing,+ strict_provisioning_profile_search=strict_provisioning_profile_search,+ provisioning_profile_filter=provisioning_profile_filter,+ no_check_certificates=no_check_certificates,+ )+ if selected_profile_info is not None:+ return selected_profile_info+ if profiles is not None:+ has_profiles = True+ if mismatches:+ all_mismatches.extend(mismatches)+ _LOGGER.info(+ f"No matching profile found in '{profiles_dir}', trying next source"+ )++ # No profile found in any directory — generate diagnostics+ if not has_profiles:+ dirs_msg = ", ".join(f"'{d}'" for d in provisioning_profiles_dirs)+ raise CodeSignProvisioningError(+ f"\n\nFailed to find any provisioning profiles. Please make sure to install required provisioning profiles and make sure they are located at {dirs_msg}.\n\n"+ + CodesignDiagnosticsText.NO_PROFILES_REMEDIATION+ )++ if not all_mismatches:+ dirs_msg = ", ".join(f"`{d}`" for d in provisioning_profiles_dirs)+ raise RuntimeError(+ f"Expected diagnostics information for at least one mismatching provisioning profile when {dirs_msg} directories are not empty."+ )+ raise CodeSignProvisioningError(+ interpret_provisioning_profile_diagnostics(+ diagnostics=all_mismatches,+ bundle_id=info_plist_metadata.bundle_id,+ provisioning_profiles_dirs=provisioning_profiles_dirs,+ identities=identities,+ log_file_path=log_file_path,+ )+ )+++def signing_context_with_profile_selection(+ info_plist_source: Path,+ info_plist_destination: Path,+ provisioning_profiles_dirs: List[Path],+ entitlements_path: Optional[Path],+ platform: ApplePlatform,+ list_codesign_identities: IListCodesignIdentities,+ log_file_path: Optional[Path] = None,+ should_use_fast_provisioning_profile_parsing: bool = False,+ strict_provisioning_profile_search: bool = False,+ provisioning_profile_filter: Optional[str] = None,+ no_check_certificates: bool = False,+ should_verify_entitlements: bool = False,+) -> SigningContextWithProfileSelection:+ with open(info_plist_source, mode="rb") as info_plist_file:+ info_plist_metadata = InfoPlistMetadata.from_file(info_plist_file)+ selected_profile_info = _select_best_provisioning_profile(+ info_plist_metadata=info_plist_metadata,+ provisioning_profiles_dirs=provisioning_profiles_dirs,+ entitlements_path=entitlements_path,+ platform=platform,+ list_codesign_identities=list_codesign_identities,+ log_file_path=log_file_path,+ should_use_fast_provisioning_profile_parsing=should_use_fast_provisioning_profile_parsing,+ strict_provisioning_profile_search=strict_provisioning_profile_search,+ provisioning_profile_filter=provisioning_profile_filter,+ no_check_certificates=no_check_certificates,+ )++ profile_path = selected_profile_info.profile.file_path+ # @oss-disable[end= ]: if should_verify_entitlements:+ # @oss-disable[end= ]: _verify_entitlements(entitlements_path, profile_path, platform)++ return SigningContextWithProfileSelection(+ info_plist_source,+ info_plist_destination,+ info_plist_metadata,+ selected_profile_info,+ )+++# IMPORTANT: This enum is a part of incremental API, amend carefully.+class CodesignConfiguration(str, Enum):+ fastAdhoc = "fast-adhoc"+ executionBypass = "execution-bypass"+ dryRun = "dry-run"+++def write_empty_codesign_manifest(codesign_manifest_path: Path, bundle_path: Path):+ with open(codesign_manifest_path, "w") as codesign_manifest_file:+ codesign_manifest = generate_codesign_manifest(+ bundle_path, codesign_invocations=[]+ )+ json.dump(codesign_manifest, codesign_manifest_file, indent=4)+++def _postprocess_entitlements_if_needed_for_adhoc_signed_bundle(+ bundle_path: CodesignedPath,+ tmp_dir: str,+ entitlements_suffixed_key_map: Optional[Dict[str, str]] = None,+ entitlements_removed_keys: Optional[List[str]] = None,+ entitlements_removed_values_map: Optional[Dict[str, List[str]]] = None,+) -> CodesignedPath:+ if bundle_path.entitlements:+ fd, postprocessed_path = tempfile.mkstemp(dir=tmp_dir)+ os.close(fd)+ shutil.copy2(bundle_path.entitlements, postprocessed_path)+ postprocess_entitlements(+ postprocessed_path,+ entitlements_suffixed_key_map=entitlements_suffixed_key_map,+ entitlements_removed_keys=entitlements_removed_keys,+ entitlements_removed_values_map=entitlements_removed_values_map,+ )+ return CodesignedPath(+ path=bundle_path.path,+ entitlements=Path(postprocessed_path),+ flags=bundle_path.flags,+ extra_file_paths=bundle_path.extra_file_paths,+ )+ return bundle_path+++def codesign_bundle(+ bundle_path: CodesignedPath,+ signing_context: Union[AdhocSigningContext, SigningContextWithProfileSelection],+ platform: ApplePlatform,+ codesign_on_copy_paths: List[CodesignedPath],+ codesign_tool: Optional[Path] = None,+ codesign_configuration: Optional[CodesignConfiguration] = None,+ fast_adhoc_signing_probe_enabled: bool = False,+ codesign_manifest_path: Optional[Path] = None,+ entitlements_suffixed_key_map: Optional[Dict[str, str]] = None,+ entitlements_removed_keys: Optional[List[str]] = None,+ entitlements_removed_values_map: Optional[Dict[str, List[str]]] = None,+ prepared_entitlements_output_path: Optional[Path] = None,+) -> None:+ codesign_on_copy_paths = sorted(+ codesign_on_copy_paths,+ key=lambda codesigned_path: codesigned_path.path,+ # Paths must be signed inside out (i.e., deepest first)+ reverse=True,+ )++ with tempfile.TemporaryDirectory() as tmp_dir:+ selection_profile_context = selection_profile_context_from_signing_context(+ signing_context+ )+ if selection_profile_context:+ bundle_path_with_prepared_entitlements = (+ _prepare_entitlements_and_info_plist(+ bundle_path=bundle_path,+ platform=platform,+ signing_context=selection_profile_context,+ tmp_dir=tmp_dir,+ entitlements_suffixed_key_map=entitlements_suffixed_key_map,+ entitlements_removed_keys=entitlements_removed_keys,+ entitlements_removed_values_map=entitlements_removed_values_map,+ )+ )+ selected_identity = selection_profile_context.selected_profile_info.identity+ else:+ if not isinstance(signing_context, AdhocSigningContext):+ raise AssertionError(+ f"Expected `AdhocSigningContext`, got `{type(signing_context)}` instead."+ )+ if signing_context.profile_selection_context:+ raise AssertionError(+ "Expected no profile selection context in `AdhocSigningContext` when `selection_profile_context` is `None`."+ )+ bundle_path_with_prepared_entitlements = (+ _postprocess_entitlements_if_needed_for_adhoc_signed_bundle(+ bundle_path,+ tmp_dir,+ entitlements_suffixed_key_map,+ entitlements_removed_keys,+ entitlements_removed_values_map,+ )+ )+ selected_identity = signing_context.identity()++ if codesign_configuration is CodesignConfiguration.dryRun:+ if codesign_tool is None:+ raise RuntimeError(+ "Expected codesign tool not to be the default one when dry run codesigning is requested."+ )+ manifest_codesign_factory = ManifestCodesignCommandFactory(+ DryRunCodesignCommandFactory(+ codesign_tool,+ selected_identity.subject_common_name,+ )+ )+ _dry_codesign_everything(+ root=bundle_path_with_prepared_entitlements,+ codesign_on_copy_paths=codesign_on_copy_paths,+ identity=selected_identity,+ tmp_dir=tmp_dir,+ codesign_command_factory=manifest_codesign_factory,+ platform=platform,+ )+ else:+ fast_adhoc_signing_enabled = (+ codesign_configuration is CodesignConfiguration.fastAdhoc+ and is_fast_adhoc_codesign_allowed(fast_adhoc_signing_probe_enabled)+ )+ codesign_execution_bypass_enabled = (+ codesign_configuration is CodesignConfiguration.executionBypass+ )+ underlying_codesign_factory = (+ DefaultCodesignCommandFactory(codesign_tool)+ if (not codesign_execution_bypass_enabled)+ else None+ )+ manifest_codesign_factory = ManifestCodesignCommandFactory(+ underlying_codesign_factory+ )+ _codesign_everything(+ root=bundle_path_with_prepared_entitlements,+ codesign_on_copy_paths=codesign_on_copy_paths,+ identity_fingerprint=selected_identity.fingerprint,+ tmp_dir=tmp_dir,+ codesign_command_factory=manifest_codesign_factory,+ platform=platform,+ fast_adhoc_signing=fast_adhoc_signing_enabled,+ )++ if codesign_manifest_path:+ with open(codesign_manifest_path, "w") as codesign_manifest_file:+ codesign_manifest = (+ manifest_codesign_factory.generate_codesign_manifest(+ bundle_path.path+ )+ )+ json.dump(codesign_manifest, codesign_manifest_file, indent=4)++ if (+ prepared_entitlements_output_path+ and bundle_path_with_prepared_entitlements.entitlements+ ):+ shutil.copy2(+ bundle_path_with_prepared_entitlements.entitlements,+ prepared_entitlements_output_path,+ )+++def _prepare_entitlements_and_info_plist(+ bundle_path: CodesignedPath,+ platform: ApplePlatform,+ signing_context: SigningContextWithProfileSelection,+ tmp_dir: str,+ entitlements_suffixed_key_map: Optional[Dict[str, str]] = None,+ entitlements_removed_keys: Optional[List[str]] = None,+ entitlements_removed_values_map: Optional[Dict[str, List[str]]] = None,+) -> CodesignedPath:+ info_plist_metadata = signing_context.info_plist_metadata+ selected_profile = signing_context.selected_profile_info.profile+ prepared_entitlements_path = prepare_code_signing_entitlements(+ bundle_path.entitlements,+ info_plist_metadata.bundle_id,+ selected_profile,+ tmp_dir,+ entitlements_suffixed_key_map=entitlements_suffixed_key_map,+ entitlements_removed_keys=entitlements_removed_keys,+ entitlements_removed_values_map=entitlements_removed_values_map,+ )+ prepared_info_plist_path = prepare_info_plist(+ signing_context.info_plist_source,+ info_plist_metadata,+ selected_profile,+ tmp_dir,+ )+ os.replace(+ prepared_info_plist_path,+ bundle_path.path / signing_context.info_plist_destination,+ )+ shutil.copy2(+ selected_profile.file_path,+ bundle_path.path / platform.embedded_provisioning_profile_path(),+ )+ return CodesignedPath(+ path=bundle_path.path,+ entitlements=prepared_entitlements_path,+ flags=bundle_path.flags,+ extra_file_paths=None,+ )+++async def _fast_read_provisioning_profiles_async(+ dirpath: Path,+ read_provisioning_profile_command_factory: IReadProvisioningProfileCommandFactory,+) -> List[ProvisioningProfileMetadata]:+ tasks = []+ for f in os.listdir(dirpath):+ if f.endswith(".mobileprovision") or f.endswith(".provisionprofile"):+ filepath = dirpath / f+ tasks.append(+ _provisioning_profile_from_file_path_async(+ filepath,+ read_provisioning_profile_command_factory,+ should_use_fast_provisioning_profile_parsing=True,+ )+ )+ results = await asyncio.gather(*tasks)+ return cast(List[ProvisioningProfileMetadata], results)+++async def _provisioning_profile_from_file_path_async(+ path: Path,+ read_provisioning_profile_command_factory: IReadProvisioningProfileCommandFactory,+ should_use_fast_provisioning_profile_parsing: bool,+) -> ProvisioningProfileMetadata:+ loop = asyncio.get_running_loop()+ return await loop.run_in_executor(+ None,+ _provisioning_profile_from_file_path,+ path,+ read_provisioning_profile_command_factory,+ should_use_fast_provisioning_profile_parsing,+ )+++def _read_provisioning_profiles(+ dirpath: Path,+ read_provisioning_profile_command_factory: IReadProvisioningProfileCommandFactory,+) -> List[ProvisioningProfileMetadata]:+ return [+ _provisioning_profile_from_file_path(+ dirpath / f,+ read_provisioning_profile_command_factory,+ should_use_fast_provisioning_profile_parsing=False,+ )+ for f in os.listdir(dirpath)+ if (f.endswith(".mobileprovision") or f.endswith(".provisionprofile"))+ ]+++def read_provisioning_profile_using_plist_marker(path: Path) -> Optional[bytes]:+ # Provisioning profiles have a plist embedded in them that we can extract directly.+ # This is much faster than calling an external command like openssl.+ with open(path, "rb") as f:+ content = f.read()+ start_index = content.find(b"<plist")+ end_index = content.find(b"</plist>", start_index) + len(b"</plist>")+ if start_index >= 0 and end_index >= 0:+ return content[start_index:end_index]+ return None+++def _provisioning_profile_from_file_path(+ path: Path,+ read_provisioning_profile_command_factory: IReadProvisioningProfileCommandFactory,+ should_use_fast_provisioning_profile_parsing: bool,+) -> ProvisioningProfileMetadata:+ if should_use_fast_provisioning_profile_parsing:+ plist_data = read_provisioning_profile_using_plist_marker(path)+ if plist_data is not None:+ return ProvisioningProfileMetadata.from_provisioning_profile_file_content(+ path, plist_data+ )+ else:+ _LOGGER.warning(+ f"Failed to find plist in provisioning profile at {path}. Falling back to slow parsing."+ )++ # Fallback to slow parsing if fast parsing is disabled or fails+ return _provisioning_profile_from_file_path_using_factory(+ path, read_provisioning_profile_command_factory+ )+++def _provisioning_profile_from_file_path_using_factory(+ path: Path,+ read_provisioning_profile_command_factory: IReadProvisioningProfileCommandFactory,+) -> ProvisioningProfileMetadata:+ output: bytes = subprocess.check_output(+ read_provisioning_profile_command_factory.read_provisioning_profile_command(+ path+ ),+ stderr=subprocess.DEVNULL,+ )+ return ProvisioningProfileMetadata.from_provisioning_profile_file_content(+ path, output+ )+++def _read_entitlements_file(path: Optional[Path]) -> Optional[Dict[str, Any]]:+ if not path:+ return None+ with open(path, mode="rb") as f:+ return detect_format_and_load(f)+++def _dry_codesign_everything(+ root: CodesignedPath,+ codesign_on_copy_paths: List[CodesignedPath],+ identity: CodeSigningIdentity,+ tmp_dir: str,+ codesign_command_factory: ICodesignCommandFactory,+ platform: ApplePlatform,+) -> None:+ codesign_on_copy_directory_paths = [+ p for p in codesign_on_copy_paths if p.path.is_dir()+ ]++ # First sign codesign-on-copy directory paths+ _codesign_paths(+ paths=codesign_on_copy_directory_paths,+ identity_fingerprint=identity.fingerprint,+ tmp_dir=tmp_dir,+ codesign_command_factory=codesign_command_factory,+ platform=platform,+ )++ # Dry codesigning creates a .plist inside every directory it signs.+ # That approach doesn't work for files so those files are written into .plist for root bundle.+ codesign_on_copy_file_paths = [+ p.path.relative_to(root.path)+ for p in codesign_on_copy_paths+ if p.path.is_file()+ ]++ if root.extra_file_paths:+ raise RuntimeError(+ f"Root path contains extra file paths: `{root.extra_file_paths}`"+ )++ root_with_extra_paths = CodesignedPath(+ path=root.path,+ entitlements=root.entitlements,+ flags=root.flags,+ extra_file_paths=codesign_on_copy_file_paths,+ )++ # Lastly sign whole bundle+ _codesign_paths(+ paths=[root_with_extra_paths],+ identity_fingerprint=identity.fingerprint,+ tmp_dir=tmp_dir,+ codesign_command_factory=codesign_command_factory,+ platform=platform,+ )+++def _codesign_everything(+ root: CodesignedPath,+ codesign_on_copy_paths: List[CodesignedPath],+ identity_fingerprint: str,+ tmp_dir: str,+ codesign_command_factory: ICodesignCommandFactory,+ platform: ApplePlatform,+ fast_adhoc_signing: bool,+) -> None:+ # First sign codesign-on-copy paths+ codesign_on_copy_filtered_paths = _filter_out_fast_adhoc_paths(+ paths=codesign_on_copy_paths,+ identity_fingerprint=identity_fingerprint,+ platform=platform,+ fast_adhoc_signing=fast_adhoc_signing,+ )+ # If we have > 1 paths to sign (including root bundle), access keychain first to avoid user playing whack-a-mole+ # with permission grant dialog windows.+ if codesign_on_copy_filtered_paths:+ obtain_keychain_permissions(+ identity_fingerprint, tmp_dir, codesign_command_factory+ )+ _codesign_paths(+ codesign_on_copy_filtered_paths,+ identity_fingerprint,+ tmp_dir,+ codesign_command_factory,+ platform,+ )+ # Lastly sign whole bundle+ root_filtered_paths = _filter_out_fast_adhoc_paths(+ paths=[root],+ identity_fingerprint=identity_fingerprint,+ platform=platform,+ fast_adhoc_signing=fast_adhoc_signing,+ )+ _codesign_paths(+ root_filtered_paths,+ identity_fingerprint,+ tmp_dir,+ codesign_command_factory,+ platform,+ )+++@dataclass+class ParallelProcess:+ process: subprocess.Popen[bytes]+ stdout_path: Optional[str]+ stderr_path: str++ def check_result(self) -> None:+ if self.process.returncode == 0:+ return+ with ExitStack() as stack:+ command = f"\ncommand:\n{self.process.args}\n"+ stderr = stack.enter_context(open(self.stderr_path, encoding="utf8"))+ stderr_string = f"\nstderr:\n{stderr.read()}\n"+ stdout = (+ stack.enter_context(open(self.stdout_path, encoding="utf8"))+ if self.stdout_path+ else None+ )+ stdout_string = f"\nstdout:\n{stdout.read()}\n" if stdout else ""+ raise RuntimeError(f"{command}{stdout_string}{stderr_string}")+++def _spawn_process(+ command: List[Union[str, Path]],+ tmp_dir: str,+ stack: ExitStack,+ pipe_stdout: bool = False,+) -> ParallelProcess:+ if pipe_stdout:+ stdout_path = None+ stdout = subprocess.PIPE+ else:+ stdout_path = os.path.join(tmp_dir, uuid.uuid4().hex)+ stdout = stack.enter_context(open(stdout_path, "w"))+ stderr_path = os.path.join(tmp_dir, uuid.uuid4().hex)+ stderr = stack.enter_context(open(stderr_path, "w"))+ _LOGGER.info(f"Executing command: {command}")+ process = subprocess.Popen(command, stdout=stdout, stderr=stderr)+ return ParallelProcess(+ process,+ stdout_path,+ stderr_path,+ )+++def _spawn_codesign_process(+ path: CodesignedPath,+ identity_fingerprint: str,+ tmp_dir: str,+ codesign_command_factory: ICodesignCommandFactory,+ stack: ExitStack,+) -> ParallelProcess:+ command = codesign_command_factory.codesign_command(+ path.path,+ identity_fingerprint,+ path.entitlements,+ path.flags,+ path.extra_file_paths,+ )+ return _spawn_process(command=command, tmp_dir=tmp_dir, stack=stack)+++def _codesign_paths_serially(+ paths: List[CodesignedPath],+ identity_fingerprint: str,+ tmp_dir: str,+ codesign_command_factory: ICodesignCommandFactory,+ platform: ApplePlatform,+) -> None:+ with ExitStack() as stack:+ for path in paths:+ p = _spawn_codesign_process(+ path=path,+ identity_fingerprint=identity_fingerprint,+ tmp_dir=tmp_dir,+ codesign_command_factory=codesign_command_factory,+ stack=stack,+ )+ p.process.wait()+ p.check_result()+++def _codesign_paths_in_parallel(+ paths: List[CodesignedPath],+ identity_fingerprint: str,+ tmp_dir: str,+ codesign_command_factory: ICodesignCommandFactory,+ platform: ApplePlatform,+) -> None:+ """Codesigns several paths in parallel."""+ processes: List[ParallelProcess] = []+ with ExitStack() as stack:+ for path in paths:+ process = _spawn_codesign_process(+ path=path,+ identity_fingerprint=identity_fingerprint,+ tmp_dir=tmp_dir,+ codesign_command_factory=codesign_command_factory,+ stack=stack,+ )+ processes.append(process)+ for p in processes:+ p.process.wait()+ for p in processes:+ p.check_result()+++def _can_codesign_paths_in_parallel(codesigned_paths: List[CodesignedPath]) -> bool:+ # To enable parallel signing, there must be no nesting of any codesigned paths,+ # as codesigning must be performed "inside out" - deeper items signed first,+ # as parent items need to seal the contained items as part of their signature.+ #+ # To detect nesting, we reverse sort all paths and only need to check+ # neighboring elements. For example, imagine the following elements:+ # `a/b/c`+ # `a/b`+ # `b`+ # `c`+ #+ # For each element, check if the element is a prefix of the previous element.+ # In the example above, checking if `a/b` is a prefix of `a/b/c` means its+ # unsafe to codesign in parallel.+ paths = sorted([str(path.path) for path in codesigned_paths], reverse=True)+ for index, current_path in enumerate(paths):+ if index == 0:+ continue+ previous_path = paths[index - 1]+ if previous_path.startswith(current_path):+ _LOGGER.warning(+ f"Found overlapping codesigned paths: {previous_path}, {current_path}"+ )+ return False+ return True+++def _codesign_paths(+ paths: List[CodesignedPath],+ identity_fingerprint: str,+ tmp_dir: str,+ codesign_command_factory: ICodesignCommandFactory,+ platform: ApplePlatform,+) -> None:+ can_codesign_in_parallel = _can_codesign_paths_in_parallel(paths)+ signing_function = (+ _codesign_paths_in_parallel+ if can_codesign_in_parallel+ else _codesign_paths_serially+ )+ signing_function(+ paths=paths,+ identity_fingerprint=identity_fingerprint,+ tmp_dir=tmp_dir,+ codesign_command_factory=codesign_command_factory,+ platform=platform,+ )+++def _filter_out_fast_adhoc_paths(+ paths: List[CodesignedPath],+ identity_fingerprint: str,+ platform: ApplePlatform,+ fast_adhoc_signing: bool,+) -> List[CodesignedPath]:+ if not fast_adhoc_signing:+ return paths+ # TODO(T149863217): Make skip checks run in parallel, they're usually fast (~15ms)+ # but if we have many of them (e.g., 30+ frameworks), it can add about ~0.5s.'+ return [+ p+ for p in paths+ if not should_skip_adhoc_signing_path(+ p.path,+ identity_fingerprint,+ p.entitlements,+ platform,+ )+ ]+++def obtain_keychain_permissions(+ identity_fingerprint: str,+ tmp_dir: str,+ codesign_command_factory: ICodesignCommandFactory,+) -> None:+ with (+ ExitStack() as stack,+ importlib.resources.path(+ __package__, "dummy_binary_for_signing"+ ) as dummy_binary_path,+ ):+ # Copy the binary to avoid races vs other bundling actions+ dummy_binary_copied = os.path.join(tmp_dir, "dummy_binary_for_signing")+ shutil.copyfile(dummy_binary_path, dummy_binary_copied, follow_symlinks=True)+ p = _spawn_codesign_process(+ path=CodesignedPath(+ path=Path(dummy_binary_copied),+ entitlements=None,+ flags=["--timestamp=none"],+ extra_file_paths=None,+ ),+ identity_fingerprint=identity_fingerprint,+ tmp_dir=tmp_dir,+ codesign_command_factory=codesign_command_factory,+ stack=stack,+ )+ p.process.wait()+ p.check_result()
@@ -0,0 +1,172 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import base64+import dataclasses+from abc import ABCMeta, abstractmethod+from pathlib import Path+from typing import Any, Dict, List, Optional, Union+++@dataclasses.dataclass+class CodesignInvocation:+ path: Path+ identity_fingerprint: str+ entitlements: Optional[Path]+ codesign_args: List[str]+ extra_file_paths: Optional[List[Path]]++ def as_json(self, base_path: Path) -> Optional[Dict[str, Any]]:+ if not self.path.is_relative_to(base_path):+ # The dummy binary to be signed is not part of the bundle,+ # so it can be ignored+ return None++ invocation = {+ "path": str(self.path.relative_to(base_path)),+ "identity_fingerprint": self.identity_fingerprint,+ "codesign_args": self.codesign_args,+ }+ if self.entitlements:+ with open(self.entitlements, "rb") as entitlements_file:+ # We cannot rely on the presence of the entitlements file by+ # any consumers of the manifest because the file might not+ # be materialized or might be a temp file prepared by the+ # bundling script.+ entitlements_bytes = base64.b64encode(entitlements_file.read())+ invocation["entitlements"] = entitlements_bytes.decode("utf-8")+ if self.extra_file_paths:+ invocation["extra_file_paths"] = [+ str(extra_path) for extra_path in self.extra_file_paths+ ]+ return invocation+++def generate_codesign_manifest(+ base_path: Path, codesign_invocations: list[CodesignInvocation]+) -> Dict[str, Any]:+ json_invocations = [+ invocation.as_json(base_path) for invocation in codesign_invocations+ ]+ valid_json_invocations = list(filter(lambda x: x is not None, json_invocations))+ return {+ "bundle_name": base_path.name,+ "invocations": valid_json_invocations,+ }+++class ICodesignCommandFactory(metaclass=ABCMeta):+ @abstractmethod+ def codesign_command(+ self,+ path: Path,+ identity_fingerprint: str,+ entitlements: Optional[Path],+ codesign_args: List[str],+ extra_file_paths: Optional[List[Path]],+ ) -> List[Union[str, Path]]:+ raise NotImplementedError+++class ManifestCodesignCommandFactory(ICodesignCommandFactory):+ def __init__(self, underlying: Optional[ICodesignCommandFactory]):+ self.underlying = underlying+ self.invocations = []++ def codesign_command(+ self,+ path: Path,+ identity_fingerprint: str,+ entitlements: Optional[Path],+ codesign_args: List[str],+ extra_file_paths: Optional[List[Path]],+ ) -> List[Union[str, Path]]:+ self.invocations.append(+ CodesignInvocation(+ path=path,+ identity_fingerprint=identity_fingerprint,+ entitlements=entitlements,+ codesign_args=codesign_args,+ extra_file_paths=extra_file_paths,+ )+ )+ if self.underlying:+ return self.underlying.codesign_command(+ path=path,+ identity_fingerprint=identity_fingerprint,+ entitlements=entitlements,+ codesign_args=codesign_args,+ extra_file_paths=extra_file_paths,+ )+ return ["/usr/bin/true"]++ def generate_codesign_manifest(self, base_path: Path) -> Dict[str, Any]:+ return generate_codesign_manifest(base_path, self.invocations)+++class DefaultCodesignCommandFactory(ICodesignCommandFactory):+ codesign_tool: Path+ _command_args: List[str] = ["--force", "--sign"]++ def __init__(self, codesign_tool: Optional[Path]) -> None:+ self.codesign_tool = codesign_tool or Path("codesign")++ def codesign_command(+ self,+ path: Path,+ identity_fingerprint: str,+ entitlements: Optional[Path],+ codesign_args: List[str],+ extra_file_paths: Optional[List[Path]],+ ) -> List[Union[str, Path]]:+ if extra_file_paths:+ raise RuntimeError(+ f"Extra codesign paths unsupported for non-dry signing (path: `{path}`, extra paths: `{extra_file_paths}`)"+ )+ entitlements_args = ["--entitlements", entitlements] if entitlements else []+ return (+ [self.codesign_tool]+ + DefaultCodesignCommandFactory._command_args+ + [identity_fingerprint]+ + codesign_args+ + entitlements_args+ + [path]+ )+++class DryRunCodesignCommandFactory(ICodesignCommandFactory):+ codesign_tool: Path+ subject_common_name: str++ def __init__(self, codesign_tool: Path, subject_common_name: str) -> None:+ self.codesign_tool = codesign_tool+ self.subject_common_name = subject_common_name++ def codesign_command(+ self,+ path: Path,+ identity_fingerprint: str,+ entitlements: Optional[Path],+ codesign_args: List[str],+ extra_file_paths: Optional[List[Path]],+ ) -> List[Union[str, Path]]:+ args = [+ path,+ "--identity",+ identity_fingerprint,+ "--subject-common-name",+ self.subject_common_name,+ ]+ if entitlements:+ args += ["--entitlements", entitlements] if entitlements else []+ if extra_file_paths:+ args += ["--extra-paths-to-sign"]+ args += extra_file_paths+ return [self.codesign_tool] + args
@@ -0,0 +1,26 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.+++class CodesignDiagnosticsText:+ """Generic remediation text for codesigning diagnostic messages.++ In Meta builds, this class is replaced by the Meta-specific version from+ meta_only/codesign_diagnostics_text.py via @oss-disable/@oss-enable.+ """++ CERT_REMEDIATION: str = "Check that your signing certificate is installed in your keychain and has not expired. Re-download from the Apple Developer Portal if needed."+ ENTITLEMENTS_REMEDIATION: str = "Download and install the latest provisioning profile with the correct entitlements from the Apple Developer Portal."+ PLATFORM_LINK: str = (+ "you would need to download and install it from the Apple Developer Portal"+ )+ PROFILES_DOWNLOAD: str = (+ "Download the latest provisioning profiles from the Apple Developer Portal."+ )+ DEVICE_LINK: str = ""+ NO_PROFILES_REMEDIATION: str = "Download and install the required provisioning profiles from the Apple Developer Portal.\n"
@@ -0,0 +1,13 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is dual-licensed under either the MIT license found in the+ * LICENSE-MIT file in the root directory of this source tree or the Apache+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory+ * of this source tree. You may select, at your option, one of the+ * above-listed licenses.+ */++int main() {+ return 0;+}
@@ -0,0 +1,202 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import logging+import os+import plistlib+import subprocess+import sys+from pathlib import Path+from typing import List, Optional, Tuple, Union++# @oss-disable[end= ]: from ..meta_only.codesign_rust.check_adhoc_signature import (+ # @oss-disable[end= ]: read_signature_info,+# @oss-disable[end= ]: )+from .apple_platform import ApplePlatform++_LOGGER: logging.Logger = logging.getLogger(__name__)+++def _find_executable_for_signed_path(path: Path, platform: ApplePlatform) -> Path:+ extension = path.suffix+ if extension not in [".app", ".appex", ".framework"]:+ return path++ contents_subdir = "Contents/MacOS" if platform.is_desktop() else ""+ contents_dir = path / contents_subdir++ # Read binary name from Info.plist+ info_plist_path = path / (+ "Contents/Info.plist" if platform.is_desktop() else "Info.plist"+ )+ with open(info_plist_path, "rb") as file:+ plist = plistlib.load(file)+ executable_name = plist["CFBundleExecutable"]++ return contents_dir / executable_name+++def _logged_subprocess_run(+ name: str, why: str, args: List[Union[str, Path]]+) -> subprocess.CompletedProcess[str]:+ _LOGGER.info(f" Calling {name} to {why}: `{args}`")+ result = subprocess.run(+ args,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ encoding="utf-8",+ )++ _LOGGER.info(f" {name} exit code: {result.returncode}")+ if result.stdout:+ _LOGGER.info(f" {name} stdout:")+ _LOGGER.info(+ "\n" + "\n".join([f" {line}" for line in result.stdout.split("\n")])+ )+ if result.stderr:+ _LOGGER.info(f" {name} stderr:")+ _LOGGER.info(+ "\n" + "\n".join([f" {line}" for line in result.stderr.split("\n")])+ )++ return result+++def is_fast_adhoc_codesign_allowed(probe_enabled: bool) -> bool:+ if sys.platform == "darwin":+ # Xcode's active-developer-dir symlink is /var/db/xcode_select_link on+ # older macOS and /var/select/developer_dir on Sonoma+/Xcode 15+.+ if not os.path.exists("/var/db/xcode_select_link") and not os.path.exists(+ "/var/select/developer_dir"+ ):+ _LOGGER.info(+ "Developer tools do not exist, cannot use `otool`, fast adhoc signing not allowed"+ )+ return False+ return True+ # @oss-disable[end= ]: if probe_enabled:+ # @oss-disable[end= ]: return True+ _LOGGER.info(f"Running on {sys.platform}, fast adhoc signing not allowed")+ return False+++def _read_signature_info_macos(+ path: Path,+ platform: ApplePlatform,+ check_entitlements: bool,+) -> Optional[Tuple[bool, bool]]:+ """Reads adhoc/entitlements info via `/usr/bin/codesign` and `/usr/bin/otool`.++ The entitlements probe runs only when `check_entitlements=True` and the path+ is adhoc-signed; a non-adhoc path is never skipped, so its entitlements are+ never inspected and we return early to avoid a wasted `otool` subprocess.+ """+ codesign_args: List[Union[str, Path]] = ["codesign", "-d", "-v", path]+ codesign_result = _logged_subprocess_run(+ "codesign", "check pre-existing signature", codesign_args+ )++ # Anything that's _already_ adhoc signed can be skipped.+ # On ARM64 systems, the linker will already codesign using adhoc,+ # so performing the signing twice is unnecessary.+ is_adhoc = "Signature=adhoc" in codesign_result.stderr++ if not is_adhoc:+ return (False, False)++ has_entitlements_section = False+ if check_entitlements:+ # Adhoc entitlements do not require postprocessing, so we just need to check existence+ binary_path = _find_executable_for_signed_path(path, platform)+ otool_arg: List[Union[str, Path]] = [+ "/usr/bin/otool",+ "-s",+ "__TEXT",+ "__entitlements",+ binary_path,+ ]+ otool_result = _logged_subprocess_run(+ "otool", "check entitlements presence in binary", otool_arg+ )+ has_entitlements_section = (+ "Contents of (__TEXT,__entitlements) section" in otool_result.stdout+ )++ return (is_adhoc, has_entitlements_section)+++def _read_signature_info(+ path: Path,+ platform: ApplePlatform,+ check_entitlements: bool,+) -> Optional[Tuple[bool, bool]]:+ """Platform-dispatching read of signature info.++ Returns None on unsupported platforms; should_skip_adhoc_signing_path+ treats None as "could not verify, do not skip".+ """+ if sys.platform == "darwin":+ return _read_signature_info_macos(path, platform, check_entitlements)+ # @oss-disable[end= ]: elif sys.platform == "linux":+ # @oss-disable[end= ]: binary = _find_executable_for_signed_path(path, platform)+ # @oss-disable[end= ]: return read_signature_info(binary, check_entitlements)+ return None+++def should_skip_adhoc_signing_path(+ path: Path,+ identity_fingerprint: str,+ entitlements_path: Optional[Path],+ platform: ApplePlatform,+) -> bool:+ logging.getLogger(__name__).info(+ f"Checking if should skip adhoc signing path `{path}` with identity `{identity_fingerprint}` and entitlements `{entitlements_path}` for platform `{platform}`"+ )++ if identity_fingerprint != "-":+ # Non-adhoc environments _always_ code sign+ _LOGGER.info(" Requested non-adhoc signing, not adhoc skipping signing")+ return False++ if "libclang_rt" in str(path):+ # Sanitizer runtime dylibs require re-signing, even though they're already pre-signed.+ # Otherwise, `codesign` fails to sign the top-level bundle (as the adhoc pre-signed+ # sanitizer dylibs have been signed within a different context).+ return False++ info = _read_signature_info(+ path, platform, check_entitlements=entitlements_path is not None+ )++ if info is None:+ _LOGGER.info(" Could not read signature info, not skipping adhoc signing")+ return False++ is_adhoc, has_entitlements_section = info+ if not is_adhoc:+ _LOGGER.info(" Path is not adhoc signed, not skipping adhoc signing")+ return False++ # The entitlements file can be ignored under adhoc signing because:+ #+ # - Frameworks/dylibs do not need entitlements (they operate under the entitlements of their loading binary)+ # - Apps (+ app extensions) have binaries which embed the entitlements via __entitlements section at link time+ #+ # Note that certain features require non-adhoc signing (e.g., app groups) while other features like keychain+ # and "Sign in with Apple" just need the entitlements present in the binary (which it will per the above).+ if entitlements_path and not has_entitlements_section:+ binary_path = _find_executable_for_signed_path(path, platform)+ _LOGGER.info(+ f" Binary path `{binary_path}` does not contain entitlements, not skipping adhoc signing"+ )+ return False++ _LOGGER.info(f" All checks passed for `{path}`, skipping adhoc signing")+ return True
@@ -0,0 +1,69 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++from __future__ import annotations++import re+from dataclasses import dataclass+from enum import Enum+from typing import List++from .serialization import expect_dict, expect_keys, expect_str+++@dataclass+class CodeSigningIdentity:+ fingerprint: str+ subject_common_name: str++ class _ReGroupName(str, Enum):+ fingerprint = "fingerprint"+ subject_common_name = "subject_common_name"++ _re_string: str = '(?P<{fingerprint}>[A-F0-9]{{40}}) "(?P<{subject_common_name}>.+)"(?!.*CSSMERR_.+)'.format(+ fingerprint=_ReGroupName.fingerprint.value,+ subject_common_name=_ReGroupName.subject_common_name.value,+ )++ _pattern: re.Pattern[str] = re.compile(_re_string)++ @classmethod+ def parse_security_stdout(cls, text: str) -> List[CodeSigningIdentity]:+ return [+ CodeSigningIdentity(+ match.group(cls._ReGroupName.fingerprint.value),+ match.group(cls._ReGroupName.subject_common_name.value),+ )+ for match in re.finditer(cls._pattern, text)+ ]++ def to_dict(self) -> dict[str, str]:+ return {+ "fingerprint": self.fingerprint,+ "subject_common_name": self.subject_common_name,+ }++ @staticmethod+ def from_dict(value: object) -> CodeSigningIdentity:+ data = expect_dict(value, "CodeSigningIdentity")+ expect_keys(+ data,+ "CodeSigningIdentity",+ frozenset({"fingerprint", "subject_common_name"}),+ )+ return CodeSigningIdentity(+ fingerprint=expect_str(+ data["fingerprint"], "CodeSigningIdentity.fingerprint"+ ),+ subject_common_name=expect_str(+ data["subject_common_name"],+ "CodeSigningIdentity.subject_common_name",+ ),+ )
@@ -0,0 +1,47 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import unittest++from .identity import CodeSigningIdentity+++class TestParse(unittest.TestCase):+ def test_multiple_certificates_are_parsed(self):+ text = r"""+ 1) 5C5E14F66E6B3C2697107764C9D728EE5AB393B9 "Apple Development: Johnny Appleseed (B4H6M5LP3J)"+ 2) 3348E051F7E7E1ED509D2D620567BAF796210C36 "iPhone Developer: Johnny Appleseed (B4H6M5LP3J)"+ 2 valid identities found+"""+ expected = [+ CodeSigningIdentity(+ "5C5E14F66E6B3C2697107764C9D728EE5AB393B9",+ "Apple Development: Johnny Appleseed (B4H6M5LP3J)",+ ),+ CodeSigningIdentity(+ "3348E051F7E7E1ED509D2D620567BAF796210C36",+ "iPhone Developer: Johnny Appleseed (B4H6M5LP3J)",+ ),+ ]+ result = CodeSigningIdentity.parse_security_stdout(text)+ self.assertEqual(expected, result)++ def test_expired_certificates_are_ignored(self):+ text = r"""+ 1) 5C5E14F66E6B3C2697107764C9D728EE5AB393B9 "Apple Development: Johnny Appleseed (B4H6M5LP3J)"+ 2) 3348E051F7E7E1ED509D2D620567BAF796210C36 "iPhone Developer: Johnny Appleseed (B4H6M5LP3J)" (CSSMERR_TP_CERT_EXPIRED)+ 2 valid identities found+"""+ expected = [+ CodeSigningIdentity(+ "5C5E14F66E6B3C2697107764C9D728EE5AB393B9",+ "Apple Development: Johnny Appleseed (B4H6M5LP3J)",+ ),+ ]+ result = CodeSigningIdentity.parse_security_stdout(text)+ self.assertEqual(expected, result)
@@ -0,0 +1,65 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++from __future__ import annotations++from dataclasses import dataclass+from typing import IO, Optional++from apple.tools.plistlib_utils import detect_format_and_load++from .serialization import (+ expect_bool,+ expect_dict,+ expect_keys,+ expect_optional_str,+ expect_str,+)+++@dataclass+class InfoPlistMetadata:+ bundle_id: str+ bundle_type: Optional[str]+ is_watchos_app: bool++ @staticmethod+ def from_file(info_plist_file: IO[bytes]) -> InfoPlistMetadata:+ root = detect_format_and_load(info_plist_file)+ return InfoPlistMetadata(+ root["CFBundleIdentifier"],+ root.get("CFBundlePackageType"),+ root.get("WKApplication", False),+ )++ def to_dict(self) -> dict[str, object]:+ return {+ "bundle_id": self.bundle_id,+ "bundle_type": self.bundle_type,+ "is_watchos_app": self.is_watchos_app,+ }++ @staticmethod+ def from_dict(value: object) -> InfoPlistMetadata:+ data = expect_dict(value, "InfoPlistMetadata")+ expect_keys(+ data,+ "InfoPlistMetadata",+ frozenset({"bundle_id", "bundle_type", "is_watchos_app"}),+ )+ return InfoPlistMetadata(+ bundle_id=expect_str(data["bundle_id"], "InfoPlistMetadata.bundle_id"),+ bundle_type=expect_optional_str(+ data["bundle_type"], "InfoPlistMetadata.bundle_type"+ ),+ is_watchos_app=expect_bool(+ data["is_watchos_app"], "InfoPlistMetadata.is_watchos_app"+ ),+ )
@@ -0,0 +1,68 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import io+import unittest++from .info_plist_metadata import InfoPlistMetadata+++class TestParse(unittest.TestCase):+ def test_canary(self):+ plist = io.BytesIO(+ b"""<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleIdentifier</key>+ <string>com.company.application</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>WKApplication</key>+ <false/>+</dict>+</plist>+"""+ )+ expected = InfoPlistMetadata("com.company.application", "APPL", False)+ result = InfoPlistMetadata.from_file(plist)+ self.assertEqual(expected, result)++ def test_not_watch_application_by_default(self):+ plist = io.BytesIO(+ b"""<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleIdentifier</key>+ <string>com.company.application</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+</dict>+</plist>+"""+ )+ expected = InfoPlistMetadata("com.company.application", "APPL", False)+ result = InfoPlistMetadata.from_file(plist)+ self.assertEqual(expected, result)++ def test_package_type_can_be_omitted(self):+ plist = io.BytesIO(+ b"""<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleIdentifier</key>+ <string>com.company.application</string>+</dict>+</plist>+"""+ )+ expected = InfoPlistMetadata("com.company.application", None, False)+ result = InfoPlistMetadata.from_file(plist)+ self.assertEqual(expected, result)
@@ -0,0 +1,85 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++from __future__ import annotations++import subprocess+from abc import ABCMeta, abstractmethod+from typing import List++from .identity import CodeSigningIdentity+++class IListCodesignIdentities(metaclass=ABCMeta):+ @abstractmethod+ def list_codesign_identities(self) -> List[CodeSigningIdentity]:+ raise NotImplementedError++ @abstractmethod+ def raw_command(self) -> str:+ raise NotImplementedError+++class ListCodesignIdentities(IListCodesignIdentities):+ _default_command = ["security", "find-identity", "-v", "-p", "codesigning"]++ def __init__(self, command: List[str]) -> None:+ self.command = command++ @classmethod+ def default(cls) -> IListCodesignIdentities:+ return cls(cls._default_command)++ @classmethod+ def override(cls, command: List[str]) -> IListCodesignIdentities:+ return cls(command)++ def list_codesign_identities(self) -> List[CodeSigningIdentity]:+ return _list_identities(self.command)++ def raw_command(self) -> str:+ return " ".join(self.command)+++def _list_identities(+ command: List[str],+) -> List[CodeSigningIdentity]:+ output = subprocess.check_output(+ command,+ encoding="utf-8",+ )+ return CodeSigningIdentity.parse_security_stdout(output)+++class AdHocListCodesignIdentities(IListCodesignIdentities):+ def __init__(+ self, original: IListCodesignIdentities, subject_common_name: str+ ) -> None:+ self.original = original+ self.subject_common_name = subject_common_name++ def list_codesign_identities(self) -> List[CodeSigningIdentity]:+ unfiltered_identities = self.original.list_codesign_identities()+ identity = next(+ (+ i+ for i in unfiltered_identities+ if i.subject_common_name == self.subject_common_name+ ),+ None,+ )+ if not identity:+ raise RuntimeError(+ f"No identity found with subject common name `{self.subject_common_name}`"+ )+ return [identity]++ def raw_command(self) -> str:+ return self.original.raw_command()
@@ -0,0 +1,215 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import pathlib+import sys+from typing import List, Optional++from tap import Tap++from .apple_platform import ApplePlatform+from .codesign_bundle import (+ AdhocSigningContext,+ codesign_bundle,+ CodesignedPath,+ signing_context_with_profile_selection,+)+from .list_codesign_identities import ListCodesignIdentities+from .provisioning_profile_selection import CodeSignProvisioningError+++class Arguments(Tap):+ """+ Tool which code signs the Apple bundle. `Info.plist` file is amended as a part of it.+ """++ # pyre-fixme[13]: Attribute `bundle_path` is never initialized.+ bundle_path: pathlib.Path+ # pyre-fixme[13]: Attribute `info_plist` is never initialized.+ info_plist: pathlib.Path+ entitlements: Optional[pathlib.Path] = None+ profiles_dir: Optional[pathlib.Path] = None+ ad_hoc: bool = False+ ad_hoc_codesign_identity: Optional[str] = None+ # pyre-fixme[13]: Attribute `platform` is never initialized.+ platform: ApplePlatform+ codesign_on_copy: Optional[List[pathlib.Path]] = None+ fast_provisioning_profile_parsing: bool = False+ strict_provisioning_profile_search: bool = False+ provisioning_profile_filter: Optional[str] = None+ only_select_provisioning_profile: bool = False+ no_check_certificates: bool = False++ def configure(self) -> None:+ """+ Configure the arguments.+ """+ self.add_argument(+ "--bundle-path",+ metavar="</path/to/app.bundle>",+ type=pathlib.Path,+ required=True,+ help="Absolute path to Apple bundle result.",+ )+ self.add_argument(+ "--info-plist",+ metavar="<Info.plist>",+ type=pathlib.Path,+ required=True,+ help="Bundle relative destination path to Info.plist file if it is present in bundle.",+ )+ self.add_argument(+ "--entitlements",+ metavar="<Entitlements.plist>",+ type=pathlib.Path,+ required=False,+ help="Path to file with entitlements to be used during code signing. If it's not provided the minimal entitlements are going to be generated.",+ )+ self.add_argument(+ "--profiles-dir",+ metavar="</provisioning/profiles/directory>",+ type=pathlib.Path,+ required=False,+ action="append",+ help="Path to directory with provisioning profile files. Required if code signing is not ad-hoc. Can be specified multiple times.",+ )+ self.add_argument(+ "--ad-hoc",+ action="store_true",+ required=False,+ help="Perform ad-hoc signing if set.",+ )+ self.add_argument(+ "--ad-hoc-codesign-identity",+ metavar="<identity>",+ type=str,+ required=False,+ help="Codesign identity to use when ad-hoc signing is performed.",+ )+ self.add_argument(+ "--platform",+ metavar="<apple platform>",+ type=ApplePlatform,+ required=True,+ help="Apple platform for which the bundle was built.",+ )+ self.add_argument(+ "--codesign-on-copy",+ metavar="<codesign/this/path>",+ type=pathlib.Path,+ action="append",+ required=False,+ help="Bundle relative path that should be codesigned prior to result bundle.",+ )+ self.add_argument(+ "--fast-provisioning-profile-parsing",+ action="store_true",+ required=False,+ help="Uses experimental faster provisioning profile parsing.",+ )+ self.add_argument(+ "--strict-provisioning-profile-search",+ action="store_true",+ required=False,+ help="Fail code signing if more than one matching profile found.",+ )+ self.add_argument(+ "--provisioning-profile-filter",+ metavar="<regex>",+ type=str,+ required=False,+ help="Regex to disambiguate multiple matching profiles, evaluated against provisioning profile filename.",+ )+ self.add_argument(+ "--only-select-provisioning-profile",+ action="store_true",+ required=False,+ help="Skip codesigning and just output the path to the selected provisioning profile to stdout.",+ )+ self.add_argument(+ "--no-check-certificates",+ action="store_true",+ required=False,+ help="Skip the check on code signing identities when selecting provisioning profile.",+ )+++# Add emoji to beginning of actionable error message so it stands out more.+def decorate_error_message(message: str) -> str:+ return " ".join(["❗️", message])+++def _main() -> None:+ args = Arguments().parse_args()+ try:+ if args.ad_hoc:+ if args.only_select_provisioning_profile:+ print(+ "No provisioning profile is selected for ad-hoc signing.",+ file=sys.stderr,+ )+ exit(1)+ signing_context = AdhocSigningContext(+ codesign_identity=args.ad_hoc_codesign_identity+ )+ else:+ assert args.profiles_dir, (+ "Path to directory with provisioning profile files should be set when signing is not ad-hoc."+ )+ signing_context = signing_context_with_profile_selection(+ info_plist_source=args.bundle_path / args.info_plist,+ info_plist_destination=args.info_plist,+ provisioning_profiles_dirs=args.profiles_dir,+ entitlements_path=args.entitlements,+ list_codesign_identities=ListCodesignIdentities.default(),+ platform=args.platform,+ should_use_fast_provisioning_profile_parsing=args.fast_provisioning_profile_parsing,+ strict_provisioning_profile_search=args.strict_provisioning_profile_search,+ provisioning_profile_filter=args.provisioning_profile_filter,+ no_check_certificates=args.no_check_certificates,+ )++ if args.only_select_provisioning_profile:+ print(signing_context.selected_profile_info.profile.file_path)+ return++ bundle_path = CodesignedPath(+ path=args.bundle_path,+ entitlements=args.entitlements,+ flags=[],+ extra_file_paths=None,+ )+ codesign_on_copy_paths = (+ [+ CodesignedPath(+ path=bundle_path.path / path,+ entitlements=None,+ flags=[],+ extra_file_paths=None,+ )+ for path in args.codesign_on_copy+ ]+ if args.codesign_on_copy+ else []+ )++ codesign_bundle(+ bundle_path=bundle_path,+ signing_context=signing_context,+ platform=args.platform,+ codesign_on_copy_paths=codesign_on_copy_paths,+ )+ except CodeSignProvisioningError as e:+ print(decorate_error_message(str(e)), file=sys.stderr)+ exit(1)+++if __name__ == "__main__":+ _main()
@@ -0,0 +1,104 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import copy+import os+import plistlib+import tempfile+from pathlib import Path+from typing import Dict, List, Optional++from apple.tools.info_plist_processor.process import process as process_info_plist++from .provisioning_profile_metadata import ProvisioningProfileMetadata+++def postprocess_entitlements(+ output_path: str,+ entitlements_suffixed_key_map: Optional[Dict[str, str]] = None,+ entitlements_removed_keys: Optional[List[str]] = None,+ entitlements_removed_values_map: Optional[Dict[str, List[str]]] = None,+) -> None:+ if (+ not entitlements_suffixed_key_map+ and not entitlements_removed_keys+ and not entitlements_removed_values_map+ ):+ return++ with open(output_path, "rb") as f:+ entitlements = plistlib.load(f)+ original = copy.deepcopy(entitlements)++ if entitlements_removed_keys:+ for key in entitlements_removed_keys:+ entitlements.pop(key, None)++ if entitlements_removed_values_map:+ for key, values_to_remove in entitlements_removed_values_map.items():+ if key in entitlements:+ current = entitlements[key]+ if isinstance(current, list):+ entitlements[key] = [+ v for v in current if v not in values_to_remove+ ]+ elif isinstance(current, dict):+ for v in values_to_remove:+ current.pop(v, None)++ if entitlements_suffixed_key_map:+ for key, suffix in entitlements_suffixed_key_map.items():+ if key in entitlements:+ value = entitlements[key]+ if isinstance(value, str):+ entitlements[key] = value + suffix+ elif isinstance(value, list):+ entitlements[key] = [v + suffix for v in value]++ if entitlements != original:+ with open(output_path, "wb") as f:+ plistlib.dump(entitlements, f, fmt=plistlib.FMT_XML)+++# Buck v1 corresponding code is in `ProvisioningProfileCopyStep::execute` in `ProvisioningProfileCopyStep.java`+def prepare_code_signing_entitlements(+ entitlements_path: Optional[Path],+ bundle_id: str,+ profile: ProvisioningProfileMetadata,+ tmp_dir: str,+ entitlements_suffixed_key_map: Optional[Dict[str, str]] = None,+ entitlements_removed_keys: Optional[List[str]] = None,+ entitlements_removed_values_map: Optional[Dict[str, List[str]]] = None,+) -> Path:+ fd, output_path = tempfile.mkstemp(dir=tmp_dir)+ with os.fdopen(fd, mode="wb") as output:+ if entitlements_path:+ with open(entitlements_path, "rb") as entitlements_file:+ process_info_plist(+ input_file=entitlements_file,+ output_file=output,+ additional_keys=profile.get_mergeable_entitlements(),+ output_format=plistlib.FMT_XML,+ )+ else:+ app_id = profile.get_app_id().team_id + "." + bundle_id+ entitlements = profile.get_mergeable_entitlements()+ entitlements["application-identifier"] = app_id+ entitlements["keychain-access-groups"] = [app_id]+ plistlib.dump(entitlements, output, fmt=plistlib.FMT_XML)++ postprocess_entitlements(+ output_path,+ entitlements_suffixed_key_map=entitlements_suffixed_key_map,+ entitlements_removed_keys=entitlements_removed_keys,+ entitlements_removed_values_map=entitlements_removed_values_map,+ )++ return Path(output_path)
@@ -0,0 +1,437 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import os+import plistlib+import tempfile+import unittest+from datetime import datetime+from pathlib import Path++from .prepare_code_signing_entitlements import prepare_code_signing_entitlements+from .provisioning_profile_metadata import ProvisioningProfileMetadata+++class Test(unittest.TestCase):+ def test_minimal_entitlements_generated_based_on_provisioning_profile(self):+ with tempfile.TemporaryDirectory() as tmp_dir:+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {},+ {+ "application-identifier": "ABCDEFGHIJ.*",+ "com.apple.developer.aps-environment": "development",+ },+ )+ result = prepare_code_signing_entitlements(+ None, "com.company.application", profile, tmp_dir+ )+ with open(result, mode="rb") as result_file:+ self.assertEqual(+ plistlib.load(result_file),+ {+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ "com.apple.developer.aps-environment": "development",+ "keychain-access-groups": [+ "ABCDEFGHIJ.com.company.application"+ ],+ },+ )++ def test_suffix_applied_to_auto_generated_entitlements(self):+ with tempfile.TemporaryDirectory() as tmp_dir:+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {},+ {+ "application-identifier": "ABCDEFGHIJ.*",+ "com.apple.developer.aps-environment": "development",+ },+ )+ result = prepare_code_signing_entitlements(+ None,+ "com.company.application",+ profile,+ tmp_dir,+ entitlements_suffixed_key_map={"keychain-access-groups": ".suffix"},+ )+ with open(result, mode="rb") as result_file:+ self.assertEqual(+ plistlib.load(result_file),+ {+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ "com.apple.developer.aps-environment": "development",+ "keychain-access-groups": [+ "ABCDEFGHIJ.com.company.application.suffix"+ ],+ },+ )++ def test_suffix_applied_to_user_provided_entitlements(self):+ with tempfile.TemporaryDirectory() as tmp_dir:+ entitlements = {+ "foo": "bar",+ "keychain-access-groups": ["group1", "group2"],+ }+ entitlements_path = os.path.join(tmp_dir, "Entitlements.plist")+ with open(entitlements_path, mode="wb") as entitlements_file:+ plistlib.dump(entitlements, entitlements_file, fmt=plistlib.FMT_XML)+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {},+ {+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ "com.apple.developer.aps-environment": "development",+ "should.be.ignored": "dummy",+ },+ )+ result = prepare_code_signing_entitlements(+ entitlements_path,+ "com.company.application",+ profile,+ tmp_dir,+ entitlements_suffixed_key_map={"keychain-access-groups": ".mysuffix"},+ )+ with open(result, "rb") as result_file:+ self.assertEqual(+ plistlib.load(result_file),+ {+ "foo": "bar",+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ "com.apple.developer.aps-environment": "development",+ "keychain-access-groups": [+ "group1.mysuffix",+ "group2.mysuffix",+ ],+ },+ )++ def test_no_modification_when_suffix_is_none(self):+ with tempfile.TemporaryDirectory() as tmp_dir:+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {},+ {+ "application-identifier": "ABCDEFGHIJ.*",+ "com.apple.developer.aps-environment": "development",+ },+ )+ result = prepare_code_signing_entitlements(+ None,+ "com.company.application",+ profile,+ tmp_dir,+ entitlements_suffixed_key_map={},+ )+ with open(result, mode="rb") as result_file:+ self.assertEqual(+ plistlib.load(result_file),+ {+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ "com.apple.developer.aps-environment": "development",+ "keychain-access-groups": [+ "ABCDEFGHIJ.com.company.application"+ ],+ },+ )++ def test_no_modification_when_keychain_access_groups_absent(self):+ with tempfile.TemporaryDirectory() as tmp_dir:+ entitlements = {"foo": "bar"}+ entitlements_path = os.path.join(tmp_dir, "Entitlements.plist")+ with open(entitlements_path, mode="wb") as entitlements_file:+ plistlib.dump(entitlements, entitlements_file, fmt=plistlib.FMT_XML)+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {},+ {+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ },+ )+ result = prepare_code_signing_entitlements(+ entitlements_path,+ "com.company.application",+ profile,+ tmp_dir,+ entitlements_suffixed_key_map={"keychain-access-groups": ".suffix"},+ )+ with open(result, "rb") as result_file:+ self.assertEqual(+ plistlib.load(result_file),+ {+ "foo": "bar",+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ },+ )++ def test_suffix_applied_to_string_entitlement_value(self):+ with tempfile.TemporaryDirectory() as tmp_dir:+ entitlements = {+ "com.apple.developer.ubiquity-kvstore-identifier": "ABCDEFGHIJ.com.company.application",+ }+ entitlements_path = os.path.join(tmp_dir, "Entitlements.plist")+ with open(entitlements_path, mode="wb") as entitlements_file:+ plistlib.dump(entitlements, entitlements_file, fmt=plistlib.FMT_XML)+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {},+ {+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ },+ )+ result = prepare_code_signing_entitlements(+ entitlements_path,+ "com.company.application",+ profile,+ tmp_dir,+ entitlements_suffixed_key_map={+ "com.apple.developer.ubiquity-kvstore-identifier": ".mysuffix"+ },+ )+ with open(result, "rb") as result_file:+ self.assertEqual(+ plistlib.load(result_file),+ {+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ "com.apple.developer.ubiquity-kvstore-identifier": "ABCDEFGHIJ.com.company.application.mysuffix",+ },+ )++ def test_removed_keys_removes_existing_keys(self):+ with tempfile.TemporaryDirectory() as tmp_dir:+ entitlements = {+ "foo": "bar",+ "keychain-access-groups": ["group1", "group2"],+ "com.apple.developer.icloud-services": ["CloudDocuments"],+ }+ entitlements_path = os.path.join(tmp_dir, "Entitlements.plist")+ with open(entitlements_path, mode="wb") as entitlements_file:+ plistlib.dump(entitlements, entitlements_file, fmt=plistlib.FMT_XML)+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {},+ {+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ },+ )+ result = prepare_code_signing_entitlements(+ entitlements_path,+ "com.company.application",+ profile,+ tmp_dir,+ entitlements_removed_keys=["com.apple.developer.icloud-services"],+ )+ with open(result, "rb") as result_file:+ self.assertEqual(+ plistlib.load(result_file),+ {+ "foo": "bar",+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ "keychain-access-groups": ["group1", "group2"],+ },+ )++ def test_removed_keys_no_modification_when_key_absent(self):+ with tempfile.TemporaryDirectory() as tmp_dir:+ entitlements = {+ "foo": "bar",+ }+ entitlements_path = os.path.join(tmp_dir, "Entitlements.plist")+ with open(entitlements_path, mode="wb") as entitlements_file:+ plistlib.dump(entitlements, entitlements_file, fmt=plistlib.FMT_XML)+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {},+ {+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ },+ )+ result = prepare_code_signing_entitlements(+ entitlements_path,+ "com.company.application",+ profile,+ tmp_dir,+ entitlements_removed_keys=["nonexistent-key"],+ )+ with open(result, "rb") as result_file:+ self.assertEqual(+ plistlib.load(result_file),+ {+ "foo": "bar",+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ },+ )++ def test_entitlements_enriched_by_profile(self):+ with tempfile.TemporaryDirectory() as tmp_dir:+ entitlements = {"foo": "bar"}+ entitlements_path = os.path.join(tmp_dir, "Entitlements.plist")+ with open(entitlements_path, mode="wb") as entitlements_file:+ plistlib.dump(entitlements, entitlements_file, fmt=plistlib.FMT_XML)+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {},+ {+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ "com.apple.developer.aps-environment": "development",+ "should.be.ignored": "dummy",+ },+ )+ result = prepare_code_signing_entitlements(+ entitlements_path, "com.company.application", profile, tmp_dir+ )+ with open(result, "rb") as result_file:+ self.assertEqual(+ plistlib.load(result_file),+ {+ "foo": "bar",+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ "com.apple.developer.aps-environment": "development",+ },+ )++ def _assert_prepared_entitlements(+ self, input_entitlements, expected, profile_entitlements=None, **kwargs+ ):+ if profile_entitlements is None:+ profile_entitlements = {+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ }+ with tempfile.TemporaryDirectory() as tmp_dir:+ if input_entitlements is not None:+ entitlements_path = os.path.join(tmp_dir, "Entitlements.plist")+ with open(entitlements_path, mode="wb") as f:+ plistlib.dump(input_entitlements, f, fmt=plistlib.FMT_XML)+ else:+ entitlements_path = None+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {},+ profile_entitlements,+ )+ result = prepare_code_signing_entitlements(+ entitlements_path,+ "com.company.application",+ profile,+ tmp_dir,+ **kwargs,+ )+ with open(result, "rb") as f:+ self.assertEqual(plistlib.load(f), expected)++ def test_removed_values_map_removes_from_list(self):+ self._assert_prepared_entitlements(+ input_entitlements={+ "foo": "bar",+ "keychain-access-groups": ["group1", "group2", "group3"],+ },+ expected={+ "foo": "bar",+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ "keychain-access-groups": ["group2"],+ },+ entitlements_removed_values_map={+ "keychain-access-groups": ["group1", "group3"]+ },+ )++ def test_removed_values_map_removes_from_dict(self):+ self._assert_prepared_entitlements(+ input_entitlements={+ "foo": "bar",+ "com.apple.developer.icloud-container-environment": {+ "Production": True,+ "Development": True,+ "Staging": True,+ },+ },+ expected={+ "foo": "bar",+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ "com.apple.developer.icloud-container-environment": {+ "Production": True,+ },+ },+ entitlements_removed_values_map={+ "com.apple.developer.icloud-container-environment": [+ "Development",+ "Staging",+ ]+ },+ )++ def test_removed_values_map_no_modification_when_key_absent(self):+ self._assert_prepared_entitlements(+ input_entitlements={"foo": "bar"},+ expected={+ "foo": "bar",+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ },+ entitlements_removed_values_map={"nonexistent-key": ["value1"]},+ )++ def test_removed_values_map_no_modification_when_value_absent(self):+ self._assert_prepared_entitlements(+ input_entitlements={+ "foo": "bar",+ "keychain-access-groups": ["group1", "group2"],+ },+ expected={+ "foo": "bar",+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ "keychain-access-groups": ["group1", "group2"],+ },+ entitlements_removed_values_map={+ "keychain-access-groups": ["nonexistent-value"]+ },+ )++ def test_removed_values_map_empty_map(self):+ self._assert_prepared_entitlements(+ input_entitlements=None,+ expected={+ "application-identifier": "ABCDEFGHIJ.com.company.application",+ "com.apple.developer.aps-environment": "development",+ "keychain-access-groups": ["ABCDEFGHIJ.com.company.application"],+ },+ profile_entitlements={+ "application-identifier": "ABCDEFGHIJ.*",+ "com.apple.developer.aps-environment": "development",+ },+ entitlements_removed_values_map={},+ )
@@ -0,0 +1,51 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import os+import tempfile+from pathlib import Path+from typing import Any, Dict++from apple.tools.info_plist_processor.process import process as process_info_plist++from .info_plist_metadata import InfoPlistMetadata+from .provisioning_profile_metadata import ProvisioningProfileMetadata+++# Buck v1 corresponding code is in `ProvisioningProfileCopyStep::execute` in `ProvisioningProfileCopyStep.java`+def prepare_info_plist(+ info_plist: Path,+ info_plist_metadata: InfoPlistMetadata,+ profile: ProvisioningProfileMetadata,+ tmp_dir: str,+) -> Path:+ fd, output_path = tempfile.mkstemp(dir=tmp_dir)+ with open(info_plist, "rb") as input, os.fdopen(fd, mode="wb") as output:+ additional_keys = _additional_keys(info_plist_metadata, profile)+ process_info_plist(+ input_file=input, output_file=output, additional_keys=additional_keys+ )+ return Path(output_path)+++# Equivalent Buck v1 code is in `ProvisioningProfileCopyStep.java` in `ProvisioningProfileCopyStep::getInfoPlistAdditionalKeys` method.+def _additional_keys(+ info_plist_metadata: InfoPlistMetadata, profile: ProvisioningProfileMetadata+) -> Dict[str, Any]:+ result = {}+ # Restrict additional keys based on bundle type. Skip additional keys for watchOS bundles (property keys whitelist).+ if (+ info_plist_metadata.bundle_type == "APPL"+ and not info_plist_metadata.is_watchos_app+ ):+ # Construct AppID using the Provisioning Profile info (app prefix)+ app_id = profile.get_app_id().team_id + "." + info_plist_metadata.bundle_id+ result["ApplicationIdentifier"] = app_id+ return result
@@ -0,0 +1,75 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import os+import plistlib+import tempfile+import unittest+from datetime import datetime+from pathlib import Path++from .info_plist_metadata import InfoPlistMetadata+from .prepare_info_plist import prepare_info_plist+from .provisioning_profile_metadata import ProvisioningProfileMetadata+++class Test(unittest.TestCase):+ def test_app_id_set_for_non_watchos_apps(self):+ with tempfile.TemporaryDirectory() as tmp_dir:+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {},+ {+ "application-identifier": "ABCDEFGHIJ.*",+ },+ )+ info_plist = {+ "CFBundleIdentifier": "com.facebook.test",+ "CFBundlePackageType": "APPL",+ }+ info_plist_path, info_plist_metadata = _write_info_plist(+ info_plist, tmp_dir, "Info.plist"+ )+ result = prepare_info_plist(+ info_plist_path, info_plist_metadata, profile, tmp_dir+ )+ with open(result, "rb") as result_file:+ self.assertEqual(+ plistlib.load(result_file),+ {+ "CFBundleIdentifier": "com.facebook.test",+ "CFBundlePackageType": "APPL",+ "ApplicationIdentifier": "ABCDEFGHIJ.com.facebook.test",+ },+ )+ # Same but for watchOS Info.plist+ info_plist = {+ "CFBundleIdentifier": "com.facebook.test",+ "CFBundlePackageType": "APPL",+ "WKApplication": True,+ }+ info_plist_path, info_plist_metadata = _write_info_plist(+ info_plist, tmp_dir, "Info.plist"+ )+ result = prepare_info_plist(+ info_plist_path, info_plist_metadata, profile, tmp_dir+ )+ with open(result, "rb") as result_file:+ self.assertNotIn("ApplicationIdentifier", plistlib.load(result_file))+++def _write_info_plist(plist, tmp_dir, name):+ path = os.path.join(tmp_dir, "Info.plist")+ with open(path, mode="wb") as file:+ plistlib.dump(plist, file, fmt=plistlib.FMT_XML)+ with open(path, mode="rb") as file:+ metadata = InfoPlistMetadata.from_file(file)+ return (path, metadata)
@@ -0,0 +1,259 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++from abc import ABCMeta, abstractmethod+from pathlib import Path+from typing import List, Optional, Type, TypeVar++# Remediation text for diagnostic messages. Meta builds import from+# meta_only/codesign_diagnostics_text.py (arc ios-certs doctor + internal links);+# OSS builds use the generic Apple Developer Portal defaults from+# codesign_diagnostics_text.py in this directory.+# @oss-disable[end= ]: from ..meta_only.codesign_diagnostics_text import (+ # @oss-disable[end= ]: CodesignDiagnosticsText,+# @oss-disable[end= ]: )+from .apple_platform import ApplePlatform+from .identity import CodeSigningIdentity+from .provisioning_profile_metadata import ProvisioningProfileMetadata+from .codesign_diagnostics_text import CodesignDiagnosticsText # @oss-enable+++class IProvisioningProfileDiagnostics(metaclass=ABCMeta):+ profile: ProvisioningProfileMetadata++ def __init__(self, profile: ProvisioningProfileMetadata) -> None:+ self.profile = profile++ @abstractmethod+ def log_message(self) -> str:+ raise NotImplementedError+++class TeamIdMismatch(IProvisioningProfileDiagnostics):+ team_id: str+ team_id_constraint: str++ def __init__(+ self,+ profile: ProvisioningProfileMetadata,+ team_id: str,+ team_id_constraint: str,+ ) -> None:+ super().__init__(profile)+ self.team_id = team_id+ self.team_id_constraint = team_id_constraint++ def log_message(self) -> str:+ return f"Profile team ID `{self.team_id}` is not matching constraint `{self.team_id_constraint}`"+++class BundleIdMismatch(IProvisioningProfileDiagnostics):+ bundle_id: str+ bundle_id_constraint: str++ def __init__(+ self,+ profile: ProvisioningProfileMetadata,+ bundle_id: str,+ bundle_id_constraint: str,+ ) -> None:+ super().__init__(profile)+ self.bundle_id = bundle_id+ self.bundle_id_constraint = bundle_id_constraint++ def log_message(self) -> str:+ return f"Bundle ID `{self.bundle_id}` is not matching constraint `{self.bundle_id_constraint}`"+++class ProfileExpired(IProvisioningProfileDiagnostics):+ bundle_id_match_length: int++ def __init__(+ self,+ profile: ProvisioningProfileMetadata,+ bundle_id_match_length: int,+ ) -> None:+ super().__init__(profile)+ self.bundle_id_match_length = bundle_id_match_length++ def log_message(self) -> str:+ return "Provisioning profile expired."+++class UnsupportedPlatform(IProvisioningProfileDiagnostics):+ bundle_id_match_length: int+ platform_constraint: str++ def __init__(+ self,+ profile: ProvisioningProfileMetadata,+ bundle_id_match_length: int,+ platform_constraint: ApplePlatform,+ ) -> None:+ super().__init__(profile)+ self.bundle_id_match_length = bundle_id_match_length+ self.platform_constraint = platform_constraint++ def log_message(self) -> str:+ supported_profile_platforms = ", ".join(self.profile.platforms)+ return f"Requested platform `{self.platform_constraint}` is not in provisioning profile's supported platforms `{supported_profile_platforms}`."+++class EntitlementsMismatch(IProvisioningProfileDiagnostics):+ bundle_id_match_length: int+ mismatched_key: str+ mismatched_value: str++ def __init__(+ self,+ profile: ProvisioningProfileMetadata,+ bundle_id_match_length: int,+ mismatched_key: str,+ mismatched_value: str,+ ) -> None:+ super().__init__(profile)+ self.bundle_id_match_length = bundle_id_match_length+ self.mismatched_key = mismatched_key+ self.mismatched_value = mismatched_value++ def log_message(self) -> str:+ return f"Expected entitlement item key `{self.mismatched_key}` with value `{self.mismatched_value}` not found in provisioning profile."+++class DeveloperCertificateMismatch(IProvisioningProfileDiagnostics):+ bundle_id_match_length: int++ def __init__(+ self,+ profile: ProvisioningProfileMetadata,+ bundle_id_match_length: int,+ ) -> None:+ super().__init__(profile)+ self.bundle_id_match_length = bundle_id_match_length++ def log_message(self) -> str:+ certificate_fingerprints = ", ".join(+ self.profile.developer_certificate_fingerprints+ )+ return f"Expected identity fingerprint not found in profile's certificate fingerprints `{certificate_fingerprints}`."+++_T = TypeVar("T")+++def interpret_provisioning_profile_diagnostics(+ diagnostics: List[IProvisioningProfileDiagnostics],+ bundle_id: str,+ provisioning_profiles_dirs: List[Path],+ identities: List[CodeSigningIdentity],+ log_file_path: Optional[Path] = None,+) -> str:+ if not diagnostics:+ raise RuntimeError(+ "Expected diagnostics information for at least one mismatching provisioning profile."+ )+ if not provisioning_profiles_dirs:+ raise RuntimeError("Expected at least one provisioning profiles directory.")++ dirs_msg = ", ".join(f"`{d}`" for d in provisioning_profiles_dirs)+ header = f"Failed to find provisioning profile in directories {dirs_msg} that is suitable for code signing. Here is the best guess for how to fix it:\n\n⚠️ "+ footer = CodesignDiagnosticsText.DEVICE_LINK+ if log_file_path:+ non_bundle_id_mismatches = [+ f"`{mismatch.profile.file_path.name}`: {mismatch.log_message()}"+ for mismatch in diagnostics+ if not isinstance(mismatch, BundleIdMismatch)+ ]+ if non_bundle_id_mismatches:+ provisioning_profile_errors = "\n\n".join(non_bundle_id_mismatches)+ footer += f" Mismatched profiles:\n\n{provisioning_profile_errors}\n"+ else:+ footer += f" All mismatches were due to Bundle ID `{bundle_id}` not matching any provisioning profile.\n"+ footer += (+ f" Full list of mismatched profiles can be found at `{log_file_path}`.\n"+ )+ else:+ provisioning_profile_errors = "\n\n".join(+ [+ f"`{mismatch.profile.file_path.name}`: {mismatch.log_message()}"+ for mismatch in diagnostics+ ]+ )+ footer += f" Full list of mismatched profiles:{provisioning_profile_errors}\n"++ def find_mismatch(class_type: Type[_T]) -> Optional[_T]:+ return next(+ iter(+ sorted(+ filter(lambda d: isinstance(d, class_type), diagnostics),+ key=lambda d: d.bundle_id_match_length,+ reverse=True,+ )+ ),+ None,+ )++ if mismatch := find_mismatch(DeveloperCertificateMismatch):+ identities_description = (+ "WARNING: NO SIGNING IDENTITIES FOUND!"+ if len(identities) == 0+ else f"List of signing identities: `{identities}`."+ )+ return "\n".join(+ [+ header,+ f"The provisioning profile `{mismatch.profile.file_path.name}` satisfies all constraints, but no matching certificates were found in your keychain. ",+ identities_description,+ CodesignDiagnosticsText.CERT_REMEDIATION,+ footer,+ ]+ )++ if mismatch := find_mismatch(EntitlementsMismatch):+ return "".join(+ [+ header,+ f"The provisioning profile `{mismatch.profile.file_path.name}` is the best match, but it doesn't contain all the needed entitlements. ",+ f"Expected entitlement item with key `{mismatch.mismatched_key}` and value `{mismatch.mismatched_value}` is missing. ",+ f"Usually that means the application entitlements were changed recently, provisioning profile was updated and you need to download & install the latest version of provisioning profile for Bundle ID `{bundle_id}`.",+ CodesignDiagnosticsText.ENTITLEMENTS_REMEDIATION,+ footer,+ ]+ )++ if mismatch := find_mismatch(UnsupportedPlatform):+ supported_platforms = ", ".join([f"`{p}`" for p in mismatch.profile.platforms])+ return "".join(+ [+ header,+ f"The provisioning profile `{mismatch.profile.file_path.name}` is the best match, but it only supports the following platforms: {supported_platforms}. Unfortunately, it doesn't include the requested platform, `{mismatch.platform_constraint}`. ",+ f"This could indicate two possibilities: either the provisioning profile was recently updated to include the needed platform, or there is a separate profile supporting the required platform that you are missing. In the latter case, {CodesignDiagnosticsText.PLATFORM_LINK}",+ footer,+ ]+ )++ if mismatch := find_mismatch(ProfileExpired):+ return "".join(+ [+ header,+ f"The provisioning profile `{mismatch.profile.file_path.name}` is the best match; however, it has expired",+ CodesignDiagnosticsText.PROFILES_DOWNLOAD,+ footer,+ ]+ )++ return "".join(+ [+ header,+ f"No provisioning profile matching the Bundle ID `{bundle_id}` was found. ",+ CodesignDiagnosticsText.PROFILES_DOWNLOAD,+ footer,+ ]+ )
@@ -0,0 +1,110 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import unittest+from datetime import datetime+from pathlib import Path+from unittest.mock import patch++from .apple_platform import ApplePlatform+from .codesign_bundle import _try_select_from_profiles_dir+from .identity import CodeSigningIdentity+from .info_plist_metadata import InfoPlistMetadata+from .provisioning_profile_metadata import ProvisioningProfileMetadata+++def _make_profile(+ file_path: str = "/profiles/test.mobileprovision",+ bundle_id: str = "AAAAAAAAAA.com.company.app",+ fingerprint: str = "fingerprint",+ expired: bool = False,+) -> ProvisioningProfileMetadata:+ return ProvisioningProfileMetadata(+ Path(file_path),+ "00000000-0000-0000-0000-000000000000",+ datetime.min if expired else datetime.max,+ {"iOS"},+ {fingerprint},+ {"application-identifier": bundle_id},+ )+++def _make_identity(+ fingerprint: str = "fingerprint",+) -> CodeSigningIdentity:+ return CodeSigningIdentity(fingerprint, "name")+++class TestTrySelectFromProfilesDir(unittest.TestCase):+ """Tests for _try_select_from_profiles_dir helper."""++ def test_empty_dir_returns_none_tuple(self):+ with patch(+ "apple.tools.code_signing.codesign_bundle._read_profiles_from_dir",+ return_value=[],+ ):+ selected, profiles, mismatches = _try_select_from_profiles_dir(+ profiles_dir=Path("/empty"),+ info_plist_metadata=InfoPlistMetadata("com.company.app", None, False),+ identities=[_make_identity()],+ entitlements={},+ platform=ApplePlatform.ios_device,+ should_use_fast_provisioning_profile_parsing=False,+ strict_provisioning_profile_search=False,+ provisioning_profile_filter=None,+ no_check_certificates=False,+ )+ self.assertIsNone(selected)+ self.assertIsNone(profiles)+ self.assertIsNone(mismatches)++ def test_matching_profile_returns_selection(self):+ identity = _make_identity()+ profile = _make_profile()+ with patch(+ "apple.tools.code_signing.codesign_bundle._read_profiles_from_dir",+ return_value=[profile],+ ):+ selected, profiles, mismatches = _try_select_from_profiles_dir(+ profiles_dir=Path("/profiles"),+ info_plist_metadata=InfoPlistMetadata("com.company.app", None, False),+ identities=[identity],+ entitlements={},+ platform=ApplePlatform.ios_device,+ should_use_fast_provisioning_profile_parsing=False,+ strict_provisioning_profile_search=False,+ provisioning_profile_filter=None,+ no_check_certificates=False,+ )+ self.assertIsNotNone(selected)+ self.assertEqual(selected.profile, profile)+ self.assertEqual(len(profiles), 1)++ def test_no_match_returns_diagnostics(self):+ identity = _make_identity(fingerprint="other_fingerprint")+ profile = _make_profile()+ with patch(+ "apple.tools.code_signing.codesign_bundle._read_profiles_from_dir",+ return_value=[profile],+ ):+ selected, profiles, mismatches = _try_select_from_profiles_dir(+ profiles_dir=Path("/profiles"),+ info_plist_metadata=InfoPlistMetadata("com.company.app", None, False),+ identities=[identity],+ entitlements={},+ platform=ApplePlatform.ios_device,+ should_use_fast_provisioning_profile_parsing=False,+ strict_provisioning_profile_search=False,+ provisioning_profile_filter=None,+ no_check_certificates=False,+ )+ self.assertIsNone(selected)+ self.assertIsNotNone(profiles)+ self.assertEqual(len(profiles), 1)+ self.assertIsNotNone(mismatches)+ self.assertGreater(len(mismatches), 0)
@@ -0,0 +1,267 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++from __future__ import annotations++import base64+import binascii+import hashlib+from dataclasses import dataclass+from datetime import datetime+from pathlib import Path+from typing import Any, cast, Optional++from apple.tools.plistlib_utils import detect_format_and_loads++from .app_id import AppId+from .serialization import (+ expect_dict,+ expect_keys,+ expect_optional_bool,+ expect_optional_str_list,+ expect_str,+ expect_str_list,+)++_ENTITLEMENTS_BYTES_MARKER = "__apple_code_signing_bytes_b64__"+_ENTITLEMENTS_DATETIME_MARKER = "__apple_code_signing_datetime_iso__"+_ENTITLEMENTS_ESCAPED_DICT_MARKER = "__apple_code_signing_escaped_dict__"+_ENTITLEMENTS_RESERVED_MARKERS = (+ _ENTITLEMENTS_BYTES_MARKER,+ _ENTITLEMENTS_DATETIME_MARKER,+ _ENTITLEMENTS_ESCAPED_DICT_MARKER,+)+++def _serialize_datetime(dt: Optional[datetime]) -> Optional[str]:+ if dt is None:+ return None+ return dt.isoformat()+++def _deserialize_datetime(value: object, path: str) -> Optional[datetime]:+ if value is None:+ return None+ return datetime.fromisoformat(expect_str(value, path))+++def _make_entitlements_json_safe(obj: Any) -> Any:+ """Encode plist-only scalar types as tagged JSON objects."""+ if isinstance(obj, bytes):+ return {_ENTITLEMENTS_BYTES_MARKER: base64.standard_b64encode(obj).decode()}+ if isinstance(obj, datetime):+ return {_ENTITLEMENTS_DATETIME_MARKER: obj.isoformat()}+ if isinstance(obj, dict):+ encoded = {k: _make_entitlements_json_safe(v) for k, v in obj.items()}+ # A marker-shaped dictionary is valid plist data and must not be+ # mistaken for one of the tagged scalar representations when decoded.+ if len(obj) == 1 and next(iter(obj)) in _ENTITLEMENTS_RESERVED_MARKERS:+ return {_ENTITLEMENTS_ESCAPED_DICT_MARKER: encoded}+ return encoded+ if isinstance(obj, (list, tuple)):+ return [_make_entitlements_json_safe(x) for x in obj]+ return obj+++def _restore_entitlements_from_json_safe(obj: object) -> Any:+ if isinstance(obj, dict):+ data = expect_dict(obj, "entitlements")+ if set(data) == {_ENTITLEMENTS_BYTES_MARKER}:+ raw = obj[_ENTITLEMENTS_BYTES_MARKER]+ encoded = expect_str(raw, f"entitlements.{_ENTITLEMENTS_BYTES_MARKER}")+ try:+ return base64.b64decode(encoded, validate=True)+ except binascii.Error as error:+ raise ValueError("Invalid base64 entitlement value") from error+ if set(data) == {_ENTITLEMENTS_DATETIME_MARKER}:+ raw = obj[_ENTITLEMENTS_DATETIME_MARKER]+ return datetime.fromisoformat(+ expect_str(raw, f"entitlements.{_ENTITLEMENTS_DATETIME_MARKER}")+ )+ if set(data) == {_ENTITLEMENTS_ESCAPED_DICT_MARKER}:+ escaped = expect_dict(+ data[_ENTITLEMENTS_ESCAPED_DICT_MARKER],+ f"entitlements.{_ENTITLEMENTS_ESCAPED_DICT_MARKER}",+ )+ return {+ key: _restore_entitlements_from_json_safe(value)+ for key, value in escaped.items()+ }+ return {+ key: _restore_entitlements_from_json_safe(value)+ for key, value in data.items()+ }+ if isinstance(obj, list):+ return [_restore_entitlements_from_json_safe(value) for value in obj]+ if obj is None or isinstance(obj, (bool, int, float, str)):+ return obj+ raise ValueError(f"Unsupported entitlement JSON value: {type(obj).__name__}")+++@dataclass+class ProvisioningProfileMetadata:+ # Path to the provisioning profile file+ file_path: Path+ uuid: str+ # Naïve object with ignored timezone, see https://bugs.python.org/msg110249+ expiration_date: datetime+ platforms: frozenset[str]+ # Let's agree they are uppercased+ developer_certificate_fingerprints: frozenset[str]+ entitlements: dict[str, Any]+ # Naïve object with ignored timezone (same as expiration_date)+ creation_date: Optional[datetime] = None+ provisions_all_devices: Optional[bool] = None+ provisioned_devices: Optional[list[str]] = None++ _mergeable_entitlements_keys: frozenset[str] = frozenset(+ [+ "application-identifier",+ "beta-reports-active",+ "get-task-allow",+ "com.apple.developer.aps-environment",+ "com.apple.developer.team-identifier",+ ]+ )++ # See `ProvisioningProfileMetadataFactory::getAppIDFromEntitlements` from `ProvisioningProfileMetadataFactory.java` in Buck v1+ def get_app_id(self) -> AppId:+ maybe_app_id = self.entitlements.get(+ "application-identifier"+ ) or self.entitlements.get("com.apple.application-identifier")+ if not maybe_app_id:+ raise RuntimeError(+ f"Entitlements do not contain app ID: {self.entitlements}"+ )+ return AppId.from_string(maybe_app_id)++ # See `ProvisioningProfileMetadata::getMergeableEntitlements` from `ProvisioningProfileMetadata.java` in Buck v1+ def get_mergeable_entitlements(self) -> dict[str, Any]:+ return {+ k: v+ for k, v in self.entitlements.items()+ if k in ProvisioningProfileMetadata._mergeable_entitlements_keys+ }++ # See `ProvisioningProfileMetadataFactory::fromProvisioningProfilePath` from `ProvisioningProfileMetadataFactory.java` in Buck v1+ @staticmethod+ def from_provisioning_profile_file_content(+ file_path: Path, content: bytes+ ) -> ProvisioningProfileMetadata:+ root = detect_format_and_loads(content)+ developer_certificate_fingerprints = {+ hashlib.sha1(c).hexdigest().upper() for c in root["DeveloperCertificates"]+ }+ assert len(developer_certificate_fingerprints) > 0, (+ "Expected at least one suitable certificate."+ )+ return ProvisioningProfileMetadata(+ file_path=file_path,+ uuid=root["UUID"],+ expiration_date=root["ExpirationDate"],+ platforms=frozenset(root["Platform"]),+ developer_certificate_fingerprints=frozenset(+ developer_certificate_fingerprints+ ),+ entitlements=root["Entitlements"],+ creation_date=root.get("CreationDate"),+ provisions_all_devices=root.get("ProvisionsAllDevices"),+ provisioned_devices=root.get("ProvisionedDevices"),+ )++ def __hash__(self) -> int:+ return hash(+ (+ self.file_path,+ self.uuid,+ self.expiration_date,+ self.platforms,+ self.developer_certificate_fingerprints,+ )+ )++ def to_dict(self) -> dict[str, object]:+ return {+ "file_path": str(self.file_path),+ "uuid": self.uuid,+ "expiration_date": _serialize_datetime(self.expiration_date),+ "creation_date": _serialize_datetime(self.creation_date),+ "platforms": sorted(self.platforms),+ "developer_certificate_fingerprints": sorted(+ self.developer_certificate_fingerprints+ ),+ "entitlements": _make_entitlements_json_safe(self.entitlements),+ "provisions_all_devices": self.provisions_all_devices,+ "provisioned_devices": self.provisioned_devices,+ }++ @staticmethod+ def from_dict(value: object) -> ProvisioningProfileMetadata:+ data = expect_dict(value, "ProvisioningProfileMetadata")+ expect_keys(+ data,+ "ProvisioningProfileMetadata",+ frozenset(+ {+ "file_path",+ "uuid",+ "expiration_date",+ "creation_date",+ "platforms",+ "developer_certificate_fingerprints",+ "entitlements",+ "provisions_all_devices",+ "provisioned_devices",+ }+ ),+ )+ expiration = _deserialize_datetime(+ data["expiration_date"], "ProvisioningProfileMetadata.expiration_date"+ )+ if expiration is None:+ raise ValueError(+ "ProvisioningProfileMetadata.expiration_date must be a string"+ )+ creation = _deserialize_datetime(+ data["creation_date"], "ProvisioningProfileMetadata.creation_date"+ )+ entitlements = _restore_entitlements_from_json_safe(data["entitlements"])+ if not isinstance(entitlements, dict):+ raise ValueError(+ "ProvisioningProfileMetadata.entitlements must be an object"+ )+ return ProvisioningProfileMetadata(+ file_path=Path(+ expect_str(data["file_path"], "ProvisioningProfileMetadata.file_path")+ ),+ uuid=expect_str(data["uuid"], "ProvisioningProfileMetadata.uuid"),+ expiration_date=expiration,+ platforms=frozenset(+ expect_str_list(+ data["platforms"], "ProvisioningProfileMetadata.platforms"+ )+ ),+ developer_certificate_fingerprints=frozenset(+ expect_str_list(+ data["developer_certificate_fingerprints"],+ "ProvisioningProfileMetadata.developer_certificate_fingerprints",+ )+ ),+ entitlements=cast(dict[str, Any], entitlements),+ creation_date=creation,+ provisions_all_devices=expect_optional_bool(+ data["provisions_all_devices"],+ "ProvisioningProfileMetadata.provisions_all_devices",+ ),+ provisioned_devices=expect_optional_str_list(+ data["provisioned_devices"],+ "ProvisioningProfileMetadata.provisioned_devices",+ ),+ )
@@ -0,0 +1,69 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import datetime+import importlib.resources+import unittest+from pathlib import Path++from .app_id import AppId+from .provisioning_profile_metadata import ProvisioningProfileMetadata+++class TestParse(unittest.TestCase):+ def test_canary(self):+ path = Path("test_resources/sample.mobileprovision")+ file_content = (importlib.resources.files(__package__) / path).read_bytes()+ metadata = ProvisioningProfileMetadata.from_provisioning_profile_file_content(+ path, file_content+ )+ self.assertEqual(metadata.uuid, "00000000-0000-0000-0000-000000000000")+ self.assertEqual(+ metadata.get_app_id(), AppId("ABCDE12345", "com.example.TestApp")+ )+ self.assertEqual(+ metadata.expiration_date,+ datetime.datetime.fromisoformat("9999-03-05T01:33:40"),+ )+ self.assertEqual(+ metadata.developer_certificate_fingerprints,+ {"BE16FC419BFB6B59A86BC08755BA0F332EC574FB"},+ )+ self.assertEqual(+ metadata.platforms,+ {"iOS"},+ )++ def test_qualified_entitlements_parsed(self):+ path = Path("test_resources/sample.mobileprovision")+ file_content = (importlib.resources.files(__package__) / path).read_bytes()+ metadata = ProvisioningProfileMetadata.from_provisioning_profile_file_content(+ path, file_content+ )+ self.assertEqual(+ metadata.get_app_id(), AppId("ABCDE12345", "com.example.TestApp")+ )++ def test_filtered_entitlements_stripped_out(self):+ path = Path("test_resources/sample.mobileprovision")+ file_content = (importlib.resources.files(__package__) / path).read_bytes()+ metadata = ProvisioningProfileMetadata.from_provisioning_profile_file_content(+ path, file_content+ )+ self.assertIn(+ "com.apple.developer.icloud-container-development-container-identifiers",+ metadata.entitlements,+ )+ self.assertEqual(+ metadata.get_mergeable_entitlements(),+ {+ "application-identifier": "ABCDE12345.com.example.TestApp",+ "get-task-allow": False,+ "com.apple.developer.team-identifier": "12345ABCDE",+ },+ )
@@ -0,0 +1,389 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++from __future__ import annotations++import datetime+import logging+import re+from collections import defaultdict+from dataclasses import dataclass+from typing import Any, cast, Optional++from .app_id import AppId+from .apple_platform import ApplePlatform+from .identity import CodeSigningIdentity+from .info_plist_metadata import InfoPlistMetadata+from .provisioning_profile_diagnostics import (+ BundleIdMismatch,+ DeveloperCertificateMismatch,+ EntitlementsMismatch,+ IProvisioningProfileDiagnostics,+ ProfileExpired,+ TeamIdMismatch,+ UnsupportedPlatform,+)+from .provisioning_profile_metadata import ProvisioningProfileMetadata+from .serialization import expect_dict, expect_keys++_LOGGER: logging.Logger = logging.getLogger(__name__)+++class CodeSignProvisioningError(Exception):+ pass+++def _parse_team_id_from_entitlements(+ entitlements: Optional[dict[str, Any]],+) -> Optional[str]:+ if not entitlements:+ return None+ maybe_app_id = AppId.infer_from_entitlements(entitlements)+ if not maybe_app_id:+ return None+ return maybe_app_id.team_id+++def _matches_or_array_is_subset_of(+ entitlement_name: str,+ expected_value: object,+ actual_value: object,+ platform: ApplePlatform,+) -> bool:+ if expected_value is None:+ return actual_value is None+ if actual_value == "*":+ # Certain entitlements have a wildcard value, which means any value is allowed.+ return True+ if (+ actual_value is None+ and platform.is_desktop()+ and entitlement_name.startswith("com.apple.security")+ ):+ # For macOS apps, including Catalyst, the provisioning profile would _not_ have entries for+ # the sandbox entitlements, so any value matches.+ return True+ if isinstance(expected_value, list) and isinstance(actual_value, list):+ return set(expected_value).issubset(set(actual_value))+ return actual_value == expected_value+++def _bundle_match_length(expected_bundle_id: str, bundle_id_pattern: str) -> int:+ if bundle_id_pattern.endswith("*"):+ # Chop the ending * if wildcard.+ bundle_id_without_wildcard = bundle_id_pattern[:-1]+ if expected_bundle_id.startswith(bundle_id_without_wildcard):+ return len(bundle_id_without_wildcard)+ elif expected_bundle_id == bundle_id_pattern:+ return len(bundle_id_pattern)+ return -1+++# For those keys let the tooling decide if code signing should fail or succeed (every other key+# mismatch results in provisioning profile being skipped).+_IGNORE_MISMATCH_ENTITLEMENTS_KEYS = {+ "keychain-access-groups",+ "application-identifier",+ "com.apple.developer.associated-domains",+ "com.apple.developer.icloud-container-development-container-identifiers",+ "com.apple.developer.icloud-container-environment",+ "com.apple.developer.icloud-container-identifiers",+ "com.apple.developer.icloud-services",+ "com.apple.developer.ubiquity-container-identifiers",+ "com.apple.developer.ubiquity-kvstore-identifier",+}+++def _check_entitlements_match(+ expected_entitlements: Optional[dict[str, Any]],+ profile: ProvisioningProfileMetadata,+ platform: ApplePlatform,+ bundle_id_match_length: int,+) -> tuple[bool, Optional[EntitlementsMismatch]]:+ if expected_entitlements is None:+ return (True, None)+ for key, value in expected_entitlements.items():+ profile_entitlement = profile.entitlements.get(key)+ if (key not in _IGNORE_MISMATCH_ENTITLEMENTS_KEYS) and (+ not _matches_or_array_is_subset_of(+ key, value, profile_entitlement, platform+ )+ ):+ return (+ False,+ EntitlementsMismatch(+ profile=profile,+ bundle_id_match_length=bundle_id_match_length,+ mismatched_key=key,+ mismatched_value=value,+ ),+ )+ return (True, None)+++def _check_developer_certificates_match(+ profile: ProvisioningProfileMetadata,+ identities: list[CodeSigningIdentity],+ bundle_id_match_length: int,+) -> tuple[Optional[CodeSigningIdentity], Optional[DeveloperCertificateMismatch]]:+ for identity in identities:+ if identity.fingerprint in profile.developer_certificate_fingerprints:+ return (identity, None)+ return (+ None,+ DeveloperCertificateMismatch(+ profile=profile, bundle_id_match_length=bundle_id_match_length+ ),+ )+++def _make_multiple_matching_profiles_message(+ profiles: list[ProvisioningProfileMetadata],+ strict_search: bool,+) -> str:+ messages = [f"Found MULTIPLE matching profiles: {len(profiles)}"]+ messages += [+ f" Matching Profile = UUID:{profile.uuid}, creation date: {profile.creation_date}, file path: {profile.file_path}"+ for profile in profiles+ ]++ if strict_search:+ messages += [+ "Strict provisioning profile search is ENABLED, build will FAIL due to ambiguous provisioning profile search results.",+ "To resolve the problem, ensure only a single profile matches.",+ "To unblock, you have two options:",+ "Option 1: Disable strict provisioning profile search for the targets failing to build.",+ " If the target failing to build is an `apple_bundle()`, set the `strict_provisioning_profile_search` attribute to `False`.",+ " If the target failing to build is produced by `ios_binary()`, set the `bundle_strict_provisioning_profile_search` attribute to `False`.",+ " You can commit such a change, so that the issue can be investigated without blocking other developers.",+ " NB: This is a TEMPORARY WORKAROUND, as it only disables the strict checking, it does not resolve the ambiguity.",+ "Option 2: Pass `--config apple.strict_provisioning_profile_search=false` as part of your build command.",+ " DO NOT COMMIT such a change by adding this to any CI configs.",+ ]++ return "\n".join(messages)+++@dataclass+class SelectedProvisioningProfileInfo:+ profile: ProvisioningProfileMetadata+ identity: CodeSigningIdentity++ def to_dict(self) -> dict[str, Any]:+ return {+ "identity": self.identity.to_dict(),+ "profile": self.profile.to_dict(),+ }++ @staticmethod+ def from_dict(value: object) -> SelectedProvisioningProfileInfo:+ data = expect_dict(value, "SelectedProvisioningProfileInfo")+ expect_keys(+ data,+ "SelectedProvisioningProfileInfo",+ frozenset({"identity", "profile"}),+ )+ return SelectedProvisioningProfileInfo(+ profile=ProvisioningProfileMetadata.from_dict(data["profile"]),+ identity=CodeSigningIdentity.from_dict(data["identity"]),+ )+++def _filter_matching_selected_provisioning_profile_infos(+ selected_profile_infos: list[SelectedProvisioningProfileInfo],+ provisioning_profile_filter: Optional[str],+) -> list[SelectedProvisioningProfileInfo]:+ if len(selected_profile_infos) <= 1 or (not provisioning_profile_filter):+ return selected_profile_infos++ preference_regex = re.compile(provisioning_profile_filter)+ return [+ matching_profile_info+ for matching_profile_info in selected_profile_infos+ if preference_regex.search(matching_profile_info.profile.file_path.name)+ ]+++# See `ProvisioningProfileStore::getBestProvisioningProfile` in `ProvisioningProfileStore.java` for Buck v1 equivalent+# This function operates on data types only without performing any IO or process invocation.+def select_best_provisioning_profile_core(+ info_plist_metadata: InfoPlistMetadata,+ code_signing_identities: list[CodeSigningIdentity],+ provisioning_profiles: list[ProvisioningProfileMetadata],+ entitlements: Optional[dict[str, Any]],+ platform: ApplePlatform,+ strict_search: bool,+ provisioning_profile_filter: Optional[str],+ no_check_certificates: bool = False,+) -> tuple[+ Optional[SelectedProvisioningProfileInfo], list[IProvisioningProfileDiagnostics]+]:+ """Selects the best provisioning profile and certificate to use when code signing the bundle.+ Such profile could be successfully used to sign the bundle taking into account+ different constraints like entitlements or bundle ID. Given several profiles+ could be successfully used to sign the bundle the "best" one is considered+ to be a profile which matches bundle ID from `Info.plist` the most+ (i.e. profiles with specific bundle ID are preferred to wildcard bundle IDs).+ Args:+ info_plist_metadata: Object representing `Info.plist` file in the bundle.+ code_signing_identities: Code signing identities to choose from.+ provisioning_profiles: Provisioning profiles to choose from.+ entitlements: Code signing entitlements if any.+ platform: Apple platform which the bundle is built for.+ Returns:+ Provisioning profile and certificate pair to use for code signing.+ """+ maybe_team_id_constraint = _parse_team_id_from_entitlements(entitlements)++ best_match_length = -1++ # Used for error messages+ diagnostics: list[IProvisioningProfileDiagnostics] = []++ def log_mismatched_profile(mismatch: IProvisioningProfileDiagnostics) -> None:+ diagnostics.append(mismatch)+ _LOGGER.info(+ f"Skipping provisioning profile `{mismatch.profile.file_path.name}`: {mismatch.log_message()}"+ )++ selected_profile_infos_for_match_length = defaultdict(list)++ for profile in provisioning_profiles:+ app_id = profile.get_app_id()+ bundle_id = app_id.bundle_id+ current_match_length = _bundle_match_length(+ info_plist_metadata.bundle_id, bundle_id+ )+ if current_match_length < 0:+ log_mismatched_profile(+ BundleIdMismatch(+ profile=profile,+ bundle_id=app_id.bundle_id,+ bundle_id_constraint=info_plist_metadata.bundle_id,+ )+ )+ continue++ if maybe_team_id_constraint and maybe_team_id_constraint != app_id.team_id:+ log_mismatched_profile(+ TeamIdMismatch(+ profile=profile,+ team_id=app_id.team_id,+ team_id_constraint=maybe_team_id_constraint,+ )+ )+ continue++ if datetime.datetime.now() > profile.expiration_date:+ log_mismatched_profile(+ ProfileExpired(+ profile=profile, bundle_id_match_length=current_match_length+ )+ )+ continue++ maybe_provisioning_profile_name = platform.provisioning_profile_name()+ if (+ maybe_provisioning_profile_name+ and maybe_provisioning_profile_name not in profile.platforms+ ):+ log_mismatched_profile(+ UnsupportedPlatform(+ profile=profile,+ bundle_id_match_length=current_match_length,+ platform_constraint=platform,+ )+ )+ continue++ entitlements_matched, mismatch = _check_entitlements_match(+ expected_entitlements=entitlements,+ profile=profile,+ platform=platform,+ bundle_id_match_length=current_match_length,+ )+ if not entitlements_matched:+ log_mismatched_profile(cast(EntitlementsMismatch, mismatch))+ continue++ if no_check_certificates:+ certificate = CodeSigningIdentity(+ fingerprint=next(iter(profile.developer_certificate_fingerprints)),+ subject_common_name="Unknown",+ )+ else:+ certificate, mismatch = _check_developer_certificates_match(+ profile=profile,+ identities=code_signing_identities,+ bundle_id_match_length=current_match_length,+ )+ if not certificate:+ log_mismatched_profile(cast(DeveloperCertificateMismatch, mismatch))+ continue++ _LOGGER.info(+ f"Matching provisioning profile `{profile.file_path.name}` with score {current_match_length}"+ )++ selected_profile_info = SelectedProvisioningProfileInfo(profile, certificate)+ selected_profile_infos_for_match_length[current_match_length] += [+ selected_profile_info+ ]++ if current_match_length > best_match_length:+ best_match_length = current_match_length++ all_matching_selected_profile_infos = selected_profile_infos_for_match_length.get(+ best_match_length, []+ )++ all_matching_selected_profile_infos = (+ _filter_matching_selected_provisioning_profile_infos(+ all_matching_selected_profile_infos, provisioning_profile_filter+ )+ )++ if len(all_matching_selected_profile_infos) > 1:+ all_matching_profiles = [+ selected_profile_info.profile+ for selected_profile_info in all_matching_selected_profile_infos+ ]+ multiple_profiles_message = _make_multiple_matching_profiles_message(+ all_matching_profiles,+ strict_search,+ )+ _LOGGER.info(multiple_profiles_message)+ if strict_search:+ raise CodeSignProvisioningError(multiple_profiles_message)++ result = (+ # If there are multiple matching profiles, pick the one with expiration date furthest in the future+ max(+ all_matching_selected_profile_infos,+ key=lambda profile_info: profile_info.profile.expiration_date,+ )+ if all_matching_selected_profile_infos+ else None+ )++ if result:+ _LOGGER.info(+ f"Found matching provisioning profile and identity\n"+ f" Selected Identity: {result.identity}\n"+ f" Provisioning Profile: `{result.profile.file_path.name}`\n"+ f" UUID: {result.profile.uuid}\n"+ f" File: {result.profile.file_path}\n"+ f" Expiration: {result.profile.expiration_date}\n"+ f" Platforms: {result.profile.platforms}\n"+ f" Fingerprints: {result.profile.developer_certificate_fingerprints}\n"+ f" Entitlements: {result.profile.entitlements}"+ )++ return result, diagnostics
@@ -0,0 +1,659 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import copy+import unittest+from datetime import datetime, timedelta+from pathlib import Path++from .apple_platform import ApplePlatform+from .identity import CodeSigningIdentity+from .info_plist_metadata import InfoPlistMetadata+from .provisioning_profile_diagnostics import IProvisioningProfileDiagnostics+from .provisioning_profile_metadata import ProvisioningProfileMetadata+from .provisioning_profile_selection import (+ select_best_provisioning_profile_core,+ SelectedProvisioningProfileInfo,+)+++class TestSelection(unittest.TestCase):+ def verify_diagnostic_info_candidate_profile(+ self,+ diagnostic_info: list[IProvisioningProfileDiagnostics],+ reason: str,+ ):+ self.assertEqual(len(diagnostic_info), 1)+ candidate_profile = diagnostic_info[0]+ self.assertEqual(+ candidate_profile.log_message(),+ reason,+ )++ def test_expired_profiles_are_ignored(self):+ info_plist = InfoPlistMetadata("com.company.application", None, False)+ identity = CodeSigningIdentity(+ "fingerprint",+ "name",+ )+ expired_provisioning_profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.min,+ {"iOS"},+ {identity.fingerprint},+ {"application-identifier": "ABCDEFGHIJ.com.company.application"},+ )+ selected, diagnostic_info = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=[expired_provisioning_profile],+ entitlements={},+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )+ self.assertIsNone(selected)+ self.verify_diagnostic_info_candidate_profile(+ diagnostic_info,+ "Provisioning profile expired.",+ )++ fresh_provisioning_profiles = copy.copy(expired_provisioning_profile)+ fresh_provisioning_profiles.expiration_date = datetime.max+ selected, _ = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=[fresh_provisioning_profiles],+ entitlements={},+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )+ self.assertIsNotNone(selected)++ def test_multiple_matching_profiles_strict_mode(self):+ info_plist = InfoPlistMetadata("com.company.application", None, False)+ identity = CodeSigningIdentity(+ "fingerprint",+ "name",+ )+ first = ProvisioningProfileMetadata(+ Path("/foo.first"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {"application-identifier": "AAAAAAAAAA.*"},+ )+ second = ProvisioningProfileMetadata(+ Path("/foo.second"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {"application-identifier": "AAAAAAAAAA.*"},+ )+ profiles = [+ first,+ second,+ ]++ selection_failed = False+ try:+ _, _ = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=profiles,+ entitlements={"keychain-access-groups": ["AAAAAAAAAA.*"]},+ platform=ApplePlatform.ios_device,+ strict_search=True,+ provisioning_profile_filter=None,+ )+ except Exception:+ selection_failed = True++ self.assertTrue(selection_failed)++ def test_multiple_matching_profiles_with_preference(self):+ info_plist = InfoPlistMetadata("com.company.application", None, False)+ identity = CodeSigningIdentity(+ "fingerprint",+ "name",+ )+ first = ProvisioningProfileMetadata(+ Path("/foo.first"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {"application-identifier": "AAAAAAAAAA.*"},+ )+ second = ProvisioningProfileMetadata(+ Path("/foo.second"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {"application-identifier": "AAAAAAAAAA.*"},+ )+ third = ProvisioningProfileMetadata(+ Path("/foo.third"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {"application-identifier": "AAAAAAAAAA.*"},+ )+ profiles = [+ first,+ second,+ third,+ ]++ selection_failed = False+ try:+ _, _ = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=profiles,+ entitlements={"keychain-access-groups": ["AAAAAAAAAA.*"]},+ platform=ApplePlatform.ios_device,+ strict_search=True,+ provisioning_profile_filter=None,+ )+ except Exception:+ selection_failed = True++ # Check selection fails without preference+ self.assertTrue(selection_failed)++ selected_profile_info, _ = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=profiles,+ entitlements={"keychain-access-groups": ["AAAAAAAAAA.*"]},+ platform=ApplePlatform.ios_device,+ strict_search=True,+ provisioning_profile_filter=".+second",+ )+ # Check the middle profile got chosen (i.e., not first or last)+ self.assertEqual(selected_profile_info.profile, second)++ def test_multiple_matching_profiles_nonstrict_mode(self):+ info_plist = InfoPlistMetadata("com.company.application", None, False)+ identity = CodeSigningIdentity(+ "fingerprint",+ "name",+ )+ first = ProvisioningProfileMetadata(+ Path("/foo.first"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max - timedelta(days=2),+ {"iOS"},+ {identity.fingerprint},+ {"application-identifier": "AAAAAAAAAA.*"},+ )+ second = ProvisioningProfileMetadata(+ Path("/foo.second"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max - timedelta(days=1),+ {"iOS"},+ {identity.fingerprint},+ {"application-identifier": "AAAAAAAAAA.*"},+ )+ third = ProvisioningProfileMetadata(+ Path("/foo.third"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max - timedelta(days=3),+ {"iOS"},+ {identity.fingerprint},+ {"application-identifier": "AAAAAAAAAA.*"},+ )+ profiles = [+ first,+ second,+ third,+ ]++ selected_profile_info, _ = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=profiles,+ entitlements={"keychain-access-groups": ["AAAAAAAAAA.*"]},+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )++ # Check that we selected the profile with the latest expiration date+ # given multiple matches in non-strict mode+ self.assertEqual(selected_profile_info.profile, second)++ def test_prefix_override(self):+ info_plist = InfoPlistMetadata("com.company.application", None, False)+ identity = CodeSigningIdentity(+ "fingerprint",+ "name",+ )+ expected = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {"application-identifier": "AAAAAAAAAA.*"},+ )+ profiles = [+ expected,+ ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {"application-identifier": "BBBBBBBBBB.com.company.application"},+ ),+ ]+ selected, _ = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=profiles,+ entitlements={"keychain-access-groups": ["AAAAAAAAAA.*"]},+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )+ self.assertEqual(selected, SelectedProvisioningProfileInfo(expected, identity))++ def test_entitlement_keys_are_matched(self):+ info_plist = InfoPlistMetadata("com.company.application", None, False)+ identity = CodeSigningIdentity(+ "fingerprint",+ "name",+ )+ expected = ProvisioningProfileMetadata(+ Path("/foo"),+ "11111111-1111-1111-1111-111111111111",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {+ "application-identifier": "AAAAAAAAAA.com.company.application",+ "keychain-access-groups": ["AAAAAAAAAA.*"],+ "aps-environment": "production",+ "com.apple.security.application-groups": ["foo", "bar", "baz"],+ },+ )+ unexpected = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {+ "application-identifier": "AAAAAAAAAA.com.company.application",+ "keychain-access-groups": ["AAAAAAAAAA.*"],+ "aps-environment": "development",+ "com.apple.security.application-groups": ["foo", "bar"],+ },+ )+ profiles = [+ expected,+ unexpected,+ ]+ selected, _ = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=profiles,+ entitlements={+ "keychain-access-groups": ["AAAAAAAAAA.*"],+ "aps-environment": "production",+ "com.apple.security.application-groups": ["foo", "bar"],+ },+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )+ self.assertEqual(selected, SelectedProvisioningProfileInfo(expected, identity))++ selected, _ = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=profiles,+ entitlements={+ "aps-environment": "production",+ "com.apple.security.application-groups": ["foo", "bar"],+ },+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )+ self.assertEqual(selected, SelectedProvisioningProfileInfo(expected, identity))++ selected, diagnostic_info = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=[unexpected],+ entitlements={+ "aps-environment": "production",+ "com.apple.security.application-groups": ["foo", "xxx"],+ },+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )+ self.assertIsNone(selected)+ self.verify_diagnostic_info_candidate_profile(+ diagnostic_info,+ "Expected entitlement item key `aps-environment` with value `production` not found in provisioning profile.",+ )++ def test_only_profiles_containing_valid_fingerprints_are_matched(self):+ info_plist = InfoPlistMetadata("com.company.application", None, False)+ valid_identity = CodeSigningIdentity(+ "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",+ "iPhone Developer: Foo Bar (54321EDCBA)",+ )+ other_identity = CodeSigningIdentity(+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "iPhone Developer: Foo Bar (ABCDE12345)",+ )+ expected = ProvisioningProfileMetadata(+ Path("/foo"),+ "11111111-1111-1111-1111-111111111111",+ datetime.max,+ {"iOS"},+ {valid_identity.fingerprint, other_identity.fingerprint},+ {+ "application-identifier": "AAAAAAAAAA.*",+ },+ )+ unexpected = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {other_identity.fingerprint},+ {+ "application-identifier": "AAAAAAAAAA.com.company.application",+ },+ )++ profiles = [expected, unexpected]+ selected, _ = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[valid_identity],+ provisioning_profiles=profiles,+ entitlements={},+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )+ self.assertEqual(+ selected, SelectedProvisioningProfileInfo(expected, valid_identity)+ )+ selected, diagnostic_info = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[valid_identity],+ provisioning_profiles=[unexpected],+ entitlements={},+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )+ self.assertIsNone(selected)+ self.verify_diagnostic_info_candidate_profile(+ diagnostic_info,+ "Expected identity fingerprint not found in profile's certificate fingerprints `AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`.",+ )++ def test_matches_specific_app(self):+ info_plist = InfoPlistMetadata("com.facebook.test", None, False)+ identity = CodeSigningIdentity(+ "fingerprint",+ "name",+ )+ expected = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {+ "application-identifier": "BBBBBBBBBB.com.facebook.test",+ },+ )+ profiles = [+ expected,+ ProvisioningProfileMetadata(+ Path("/foo"),+ "11111111-1111-1111-1111-111111111111",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {+ "application-identifier": "BBBBBBBBBB.com.facebook.*",+ },+ ),+ ]+ selected, _ = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=profiles,+ entitlements={},+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )+ self.assertEqual(selected, SelectedProvisioningProfileInfo(expected, identity))++ selected, _ = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=reversed(profiles),+ entitlements={},+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )+ self.assertEqual(selected, SelectedProvisioningProfileInfo(expected, identity))++ def test_matches_wildcard(self):+ info_plist = InfoPlistMetadata("com.facebook.test", None, False)+ identity = CodeSigningIdentity(+ "fingerprint",+ "name",+ )+ expected = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {+ "application-identifier": "BBBBBBBBBB.*",+ },+ )+ selected, _ = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=[expected],+ entitlements=None,+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )+ self.assertEqual(selected, SelectedProvisioningProfileInfo(expected, identity))++ def test_force_included_app_entitlements(self):+ info_plist = InfoPlistMetadata("com.facebook.test", None, False)+ identity = CodeSigningIdentity(+ "fingerprint",+ "name",+ )+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {+ "application-identifier": "AAAAAAAAAA.com.facebook.test",+ "keychain-access-groups": ["AAAAAAAAAA.*"],+ "aps-environment": "production",+ },+ )+ selected, _ = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=[profile],+ entitlements={+ # Force included key, even if not present in the profile+ "application-identifier": "AAAAAAAAAA.com.facebook.BuckApp",+ "keychain-access-groups": ["AAAAAAAAAA.*"],+ "aps-environment": "production",+ },+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )+ self.assertIsNotNone(selected)++ def test_unmatched_app_entitlement(self):+ info_plist = InfoPlistMetadata("com.facebook.test", None, False)+ identity = CodeSigningIdentity(+ "fingerprint",+ "name",+ )+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {+ "application-identifier": "AAAAAAAAAA.com.facebook.test",+ "keychain-access-groups": ["AAAAAAAAAA.*"],+ "aps-environment": "production",+ },+ )+ selected, diagnostic_info = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=[profile],+ entitlements={+ "keychain-access-groups": ["AAAAAAAAAA.*"],+ "aps-environment": "production",+ "com.made.up.entitlement": "buck",+ },+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )+ self.assertIsNone(selected)+ self.verify_diagnostic_info_candidate_profile(+ diagnostic_info,+ "Expected entitlement item key `com.made.up.entitlement` with value `buck` not found in provisioning profile.",+ )++ def test_wildcard_app_entitlement_matches_any_value(self):+ info_plist = InfoPlistMetadata("com.facebook.test", None, False)+ identity = CodeSigningIdentity(+ "fingerprint",+ "name",+ )+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {+ "application-identifier": "AAAAAAAAAA.com.facebook.test",+ "keychain-access-groups": ["AAAAAAAAAA.*"],+ "aps-environment": "production",+ "com.apple.security.hardened-process.enhanced-security-version": "*",+ "com.apple.security.hardened-process.platform-restrictions": "*",+ },+ )+ selected, _ = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=[profile],+ entitlements={+ "com.apple.security.hardened-process.enhanced-security-version": "1",+ "com.apple.security.hardened-process.platform-restrictions": "2",+ },+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )+ self.assertEqual(selected, SelectedProvisioningProfileInfo(profile, identity))++ def test_unmatched_wildcard_app_entitlement(self):+ info_plist = InfoPlistMetadata("com.facebook.test", None, False)+ identity = CodeSigningIdentity(+ "fingerprint",+ "name",+ )+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {identity.fingerprint},+ {+ "application-identifier": "AAAAAAAAAA.com.facebook.test",+ "keychain-access-groups": ["AAAAAAAAAA.*"],+ "aps-environment": "production",+ },+ )+ selected, diagnostic_info = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[identity],+ provisioning_profiles=[profile],+ entitlements={+ "com.apple.security.hardened-process.enhanced-security-version": "1",+ "com.apple.security.hardened-process.platform-restrictions": "2",+ },+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ )+ self.assertIsNone(selected)+ self.verify_diagnostic_info_candidate_profile(+ diagnostic_info,+ "Expected entitlement item key `com.apple.security.hardened-process.enhanced-security-version` with value `1` not found in provisioning profile.",+ )++ def test_no_check_certificates_skips_identity_matching(self):+ info_plist = InfoPlistMetadata("com.company.application", None, False)+ profile = ProvisioningProfileMetadata(+ Path("/foo"),+ "00000000-0000-0000-0000-000000000000",+ datetime.max,+ {"iOS"},+ {"some_fingerprint"},+ {"application-identifier": "AAAAAAAAAA.com.company.application"},+ )+ # Empty identities list - would fail without no_check_certificates+ selected, _ = select_best_provisioning_profile_core(+ info_plist_metadata=info_plist,+ code_signing_identities=[],+ provisioning_profiles=[profile],+ entitlements={},+ platform=ApplePlatform.ios_device,+ strict_search=False,+ provisioning_profile_filter=None,+ no_check_certificates=True,+ )+ self.assertIsNotNone(selected)+ self.assertEqual(selected.profile, profile)+ self.assertEqual(selected.identity.fingerprint, "some_fingerprint")+ self.assertEqual(selected.identity.subject_common_name, "Unknown")
@@ -0,0 +1,39 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++from abc import ABCMeta, abstractmethod+from pathlib import Path+from typing import Union+++class IReadProvisioningProfileCommandFactory(metaclass=ABCMeta):+ @abstractmethod+ def read_provisioning_profile_command(self, path: Path) -> list[Union[str, Path]]:+ raise NotImplementedError+++# See `DEFAULT_READ_COMMAND` in `AppleConfig.java` in Buck v1+OPENSSL_PROV_PROFILE_READ_COMMAND = [+ "openssl",+ "smime",+ "-inform",+ "der",+ "-verify",+ "-noverify",+ "-nosigs",+ "-in",+]+++class DefaultReadProvisioningProfileCommandFactory(+ IReadProvisioningProfileCommandFactory+):+ def read_provisioning_profile_command(self, path: Path) -> list[Union[str, Path]]:+ return OPENSSL_PROV_PROFILE_READ_COMMAND + [path]
@@ -0,0 +1,67 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++from typing import cast+++def expect_dict(value: object, path: str) -> dict[str, object]:+ if not isinstance(value, dict) or not all(+ isinstance(key, str) for key in value.keys()+ ):+ raise ValueError(f"{path} must be an object")+ return cast(dict[str, object], value)+++def expect_keys(+ data: dict[str, object],+ path: str,+ expected: frozenset[str],+) -> None:+ actual = frozenset(data)+ if actual != expected:+ missing = sorted(expected - actual)+ unexpected = sorted(actual - expected)+ raise ValueError(+ f"{path} has invalid keys: missing={missing}, unexpected={unexpected}"+ )+++def expect_str(value: object, path: str) -> str:+ if not isinstance(value, str):+ raise ValueError(f"{path} must be a string")+ return value+++def expect_optional_str(value: object, path: str) -> str | None:+ if value is None:+ return None+ return expect_str(value, path)+++def expect_bool(value: object, path: str) -> bool:+ if not isinstance(value, bool):+ raise ValueError(f"{path} must be a boolean")+ return value+++def expect_optional_bool(value: object, path: str) -> bool | None:+ if value is None:+ return None+ return expect_bool(value, path)+++def expect_str_list(value: object, path: str) -> list[str]:+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):+ raise ValueError(f"{path} must be a list of strings")+ return cast(list[str], value)+++def expect_optional_str_list(value: object, path: str) -> list[str] | None:+ if value is None:+ return None+ return expect_str_list(value, path)
@@ -0,0 +1,143 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path+from typing import Optional, Union++from .identity import CodeSigningIdentity+from .info_plist_metadata import InfoPlistMetadata+from .provisioning_profile_selection import SelectedProvisioningProfileInfo+from .serialization import expect_dict, expect_keys, expect_str+++@dataclass+class SigningContextWithProfileSelection:+ info_plist_source: Path+ info_plist_destination: Path+ info_plist_metadata: InfoPlistMetadata+ selected_profile_info: SelectedProvisioningProfileInfo++ def to_dict(self) -> dict[str, object]:+ return {+ "info_plist_source": str(self.info_plist_source),+ "info_plist_destination": str(self.info_plist_destination),+ "info_plist_metadata": self.info_plist_metadata.to_dict(),+ "selected_profile_info": self.selected_profile_info.to_dict(),+ }++ @staticmethod+ def from_dict(value: object) -> SigningContextWithProfileSelection:+ data = expect_dict(value, "SigningContextWithProfileSelection")+ expect_keys(+ data,+ "SigningContextWithProfileSelection",+ frozenset(+ {+ "info_plist_source",+ "info_plist_destination",+ "info_plist_metadata",+ "selected_profile_info",+ }+ ),+ )+ return SigningContextWithProfileSelection(+ info_plist_source=Path(+ expect_str(+ data["info_plist_source"],+ "SigningContextWithProfileSelection.info_plist_source",+ )+ ),+ info_plist_destination=Path(+ expect_str(+ data["info_plist_destination"],+ "SigningContextWithProfileSelection.info_plist_destination",+ )+ ),+ info_plist_metadata=InfoPlistMetadata.from_dict(+ data["info_plist_metadata"]+ ),+ selected_profile_info=SelectedProvisioningProfileInfo.from_dict(+ data["selected_profile_info"]+ ),+ )+++@dataclass+class AdhocSigningContext:+ codesign_identity: str+ profile_selection_context: Optional[SigningContextWithProfileSelection]++ def __init__(+ self,+ codesign_identity: Optional[str] = None,+ profile_selection_context: Optional[SigningContextWithProfileSelection] = None,+ ) -> None:+ self.codesign_identity = codesign_identity or "-"+ self.profile_selection_context = profile_selection_context++ def identity(self) -> CodeSigningIdentity:+ if self.profile_selection_context:+ return self.profile_selection_context.selected_profile_info.identity+ return CodeSigningIdentity(+ fingerprint=self.codesign_identity,+ subject_common_name="",+ )++ def to_dict(self) -> dict[str, object]:+ return {+ "codesign_identity": self.codesign_identity,+ "profile_selection_context": (+ self.profile_selection_context.to_dict()+ if self.profile_selection_context+ else None+ ),+ }++ @staticmethod+ def from_dict(value: object) -> AdhocSigningContext:+ data = expect_dict(value, "AdhocSigningContext")+ expect_keys(+ data,+ "AdhocSigningContext",+ frozenset({"codesign_identity", "profile_selection_context"}),+ )+ psc_data = data["profile_selection_context"]+ psc = (+ SigningContextWithProfileSelection.from_dict(psc_data)+ if psc_data is not None+ else None+ )+ return AdhocSigningContext(+ codesign_identity=expect_str(+ data["codesign_identity"], "AdhocSigningContext.codesign_identity"+ ),+ profile_selection_context=psc,+ )+++def selection_profile_context_from_signing_context(+ signing_context: Optional[+ Union[AdhocSigningContext, SigningContextWithProfileSelection]+ ],+) -> Optional[SigningContextWithProfileSelection]:+ if signing_context:+ if isinstance(signing_context, SigningContextWithProfileSelection):+ selection_profile_context = signing_context+ elif isinstance(signing_context, AdhocSigningContext):+ selection_profile_context = signing_context.profile_selection_context+ else:+ raise RuntimeError(+ f"Unexpected type of signing context `{type(signing_context)}`"+ )+ return selection_profile_context+ return None
@@ -0,0 +1,316 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import datetime+import json+import unittest+from pathlib import Path++from .identity import CodeSigningIdentity+from .info_plist_metadata import InfoPlistMetadata+from .provisioning_profile_metadata import ProvisioningProfileMetadata+from .provisioning_profile_selection import SelectedProvisioningProfileInfo+from .signing_context_types import (+ AdhocSigningContext,+ SigningContextWithProfileSelection,+)+++class TestIdentitySerialization(unittest.TestCase):+ def test_round_trip(self):+ identity = CodeSigningIdentity(+ fingerprint="ABCDEF1234567890ABCDEF1234567890ABCDEF12",+ subject_common_name="Apple Development: Test",+ )+ data = identity.to_dict()+ restored = CodeSigningIdentity.from_dict(data)+ self.assertEqual(identity, restored)+ json_str = json.dumps(data)+ loaded = json.loads(json_str)+ restored2 = CodeSigningIdentity.from_dict(loaded)+ self.assertEqual(identity, restored2)++ def test_rejects_unknown_fields(self):+ with self.assertRaisesRegex(ValueError, "unexpected=.*team_id"):+ CodeSigningIdentity.from_dict(+ {+ "fingerprint": "ABC",+ "subject_common_name": "Developer",+ "team_id": "TEAM",+ }+ )++ def test_rejects_invalid_field_type(self):+ with self.assertRaisesRegex(ValueError, "fingerprint must be a string"):+ CodeSigningIdentity.from_dict(+ {"fingerprint": 123, "subject_common_name": "Developer"}+ )+++class TestInfoPlistMetadataSerialization(unittest.TestCase):+ def test_round_trip(self):+ metadata = InfoPlistMetadata(+ bundle_id="com.test.app", bundle_type="APPL", is_watchos_app=False+ )+ data = metadata.to_dict()+ restored = InfoPlistMetadata.from_dict(data)+ self.assertEqual(metadata, restored)++ def test_optional_fields(self):+ data = {"bundle_id": "com.test", "bundle_type": None, "is_watchos_app": False}+ restored = InfoPlistMetadata.from_dict(data)+ self.assertEqual(restored.bundle_id, "com.test")+ self.assertIsNone(restored.bundle_type)++ def test_requires_watchos_field(self):+ with self.assertRaisesRegex(ValueError, "missing=.*is_watchos_app"):+ InfoPlistMetadata.from_dict({"bundle_id": "com.test", "bundle_type": None})+++class TestProvisioningProfileMetadataSerialization(unittest.TestCase):+ def test_round_trip_basic(self):+ expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)+ creation = datetime.datetime(2024, 1, 1, 12, 0, 0)+ profile = ProvisioningProfileMetadata(+ file_path=Path("/tmp/profile.mobileprovision"),+ uuid="UUID-1234",+ expiration_date=expiration,+ platforms=frozenset(["iOS"]),+ developer_certificate_fingerprints=frozenset(["ABCDEF1234567890"]),+ entitlements={"application-identifier": "TEAM.com.test.app"},+ creation_date=creation,+ provisions_all_devices=False,+ provisioned_devices=["device1"],+ )+ data = profile.to_dict()+ restored = ProvisioningProfileMetadata.from_dict(data)+ self.assertEqual(restored.uuid, profile.uuid)+ self.assertEqual(restored.expiration_date, profile.expiration_date)+ self.assertEqual(restored.creation_date, profile.creation_date)+ self.assertEqual(restored.platforms, profile.platforms)+ self.assertEqual(+ restored.developer_certificate_fingerprints,+ profile.developer_certificate_fingerprints,+ )+ self.assertEqual(restored.entitlements, profile.entitlements)++ def test_bytes_and_datetime_entitlements(self):+ expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)+ profile = ProvisioningProfileMetadata(+ file_path=Path("/tmp/profile.mobileprovision"),+ uuid="UUID-BYTES",+ expiration_date=expiration,+ platforms=frozenset(["iOS"]),+ developer_certificate_fingerprints=frozenset(["ABC"]),+ entitlements={+ "data-key": b"\x00\x01\x02binary",+ "date-key": datetime.datetime(2024, 6, 1, 10, 0, 0),+ "nested": {"inner-bytes": b"inner"},+ },+ creation_date=None,+ provisions_all_devices=False,+ provisioned_devices=None,+ )+ data = profile.to_dict()+ json_str = json.dumps(data)+ loaded = json.loads(json_str)+ restored = ProvisioningProfileMetadata.from_dict(loaded)+ self.assertEqual(restored.entitlements["data-key"], b"\x00\x01\x02binary")+ self.assertEqual(+ restored.entitlements["date-key"],+ datetime.datetime(2024, 6, 1, 10, 0, 0),+ )+ self.assertEqual(restored.entitlements["nested"]["inner-bytes"], b"inner")++ def test_rejects_missing_fields(self):+ profile = self._profile()+ data = profile.to_dict()+ del data["platforms"]+ with self.assertRaisesRegex(ValueError, "missing=.*platforms"):+ ProvisioningProfileMetadata.from_dict(data)++ def test_rejects_malformed_entitlement_marker(self):+ profile = self._profile()+ data = profile.to_dict()+ data["entitlements"] = {"data-key": {"__apple_code_signing_bytes_b64__": 123}}+ with self.assertRaisesRegex(ValueError, "must be a string"):+ ProvisioningProfileMetadata.from_dict(data)++ def test_marker_shaped_entitlement_dicts_round_trip(self):+ profile = self._profile()+ profile.entitlements = {+ "bytes-marker": {"__apple_code_signing_bytes_b64__": "YWJj"},+ "datetime-marker": {+ "__apple_code_signing_datetime_iso__": "2025-01-01T12:00:00"+ },+ "escape-marker": {+ "__apple_code_signing_escaped_dict__": {"nested": "value"}+ },+ }++ serialized = json.loads(json.dumps(profile.to_dict()))+ restored = ProvisioningProfileMetadata.from_dict(serialized)++ self.assertEqual(profile.entitlements, restored.entitlements)++ def _profile(self) -> ProvisioningProfileMetadata:+ return ProvisioningProfileMetadata(+ file_path=Path("/tmp/profile.mobileprovision"),+ uuid="UUID-STRICT",+ expiration_date=datetime.datetime(2025, 1, 1, 12, 0, 0),+ platforms=frozenset(["iOS"]),+ developer_certificate_fingerprints=frozenset(["ABC"]),+ entitlements={},+ creation_date=None,+ provisions_all_devices=False,+ provisioned_devices=None,+ )+++class TestSelectedProvisioningProfileInfoSerialization(unittest.TestCase):+ def test_round_trip(self):+ expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)+ profile = ProvisioningProfileMetadata(+ file_path=Path("/tmp/profile.mobileprovision"),+ uuid="UUID-1234",+ expiration_date=expiration,+ platforms=frozenset(["iOS"]),+ developer_certificate_fingerprints=frozenset(["ABC"]),+ entitlements={},+ creation_date=None,+ provisions_all_devices=False,+ provisioned_devices=None,+ )+ identity = CodeSigningIdentity(+ fingerprint="ABC", subject_common_name="Apple Development: Test"+ )+ data_no_file = {+ "identity": identity.to_dict(),+ "profile": profile.to_dict(),+ }+ json_str = json.dumps(data_no_file)+ loaded = json.loads(json_str)+ restored = SelectedProvisioningProfileInfo.from_dict(loaded)+ self.assertEqual(restored.profile.uuid, "UUID-1234")+ self.assertEqual(restored.identity.fingerprint, "ABC")+++class TestSigningContextWithProfileSelectionSerialization(unittest.TestCase):+ def test_round_trip(self):+ expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)+ profile = ProvisioningProfileMetadata(+ file_path=Path("/tmp/profile.mobileprovision"),+ uuid="UUID-1234",+ expiration_date=expiration,+ platforms=frozenset(["iOS"]),+ developer_certificate_fingerprints=frozenset(["ABC"]),+ entitlements={},+ creation_date=None,+ provisions_all_devices=False,+ provisioned_devices=None,+ )+ identity = CodeSigningIdentity(fingerprint="ABC", subject_common_name="Dev")+ selected = SelectedProvisioningProfileInfo(profile=profile, identity=identity)+ metadata = InfoPlistMetadata(+ bundle_id="com.test.app", bundle_type="APPL", is_watchos_app=False+ )+ ctx = SigningContextWithProfileSelection(+ info_plist_source=Path("/tmp/Info.plist"),+ info_plist_destination=Path("Info.plist"),+ info_plist_metadata=metadata,+ selected_profile_info=selected,+ )+ dict_without_file = {+ "info_plist_source": str(ctx.info_plist_source),+ "info_plist_destination": str(ctx.info_plist_destination),+ "info_plist_metadata": metadata.to_dict(),+ "selected_profile_info": {+ "identity": identity.to_dict(),+ "profile": profile.to_dict(),+ },+ }+ json_str = json.dumps(dict_without_file)+ loaded = json.loads(json_str)+ restored = SigningContextWithProfileSelection.from_dict(loaded)+ self.assertEqual(restored.info_plist_source, Path("/tmp/Info.plist"))+ self.assertEqual(restored.info_plist_metadata.bundle_id, "com.test.app")+ self.assertEqual(restored.selected_profile_info.profile.uuid, "UUID-1234")+++class TestAdhocSigningContextSerialization(unittest.TestCase):+ def test_adhoc_without_profile(self):+ ctx = AdhocSigningContext(codesign_identity="-", profile_selection_context=None)+ data = ctx.to_dict()+ self.assertIsNone(data["profile_selection_context"])+ json_str = json.dumps(data)+ loaded = json.loads(json_str)+ restored = AdhocSigningContext.from_dict(loaded)+ self.assertEqual(restored.codesign_identity, "-")+ self.assertIsNone(restored.profile_selection_context)++ def test_rejects_null_codesign_identity(self):+ with self.assertRaisesRegex(ValueError, "codesign_identity must be a string"):+ AdhocSigningContext.from_dict(+ {+ "codesign_identity": None,+ "profile_selection_context": None,+ }+ )++ def test_adhoc_with_profile_explicit_none_check(self):+ # Ensures from_dict uses `is not None` check, not truthiness, so empty dict case would be preserved if ever occurs+ expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)+ profile = ProvisioningProfileMetadata(+ file_path=Path("/tmp/profile.mobileprovision"),+ uuid="UUID-5678",+ expiration_date=expiration,+ platforms=frozenset(["iOS"]),+ developer_certificate_fingerprints=frozenset(["AAA"]),+ entitlements={},+ creation_date=None,+ provisions_all_devices=True,+ provisioned_devices=None,+ )+ identity = CodeSigningIdentity(fingerprint="AAA", subject_common_name="Adhoc")+ selected = SelectedProvisioningProfileInfo(profile=profile, identity=identity)+ metadata = InfoPlistMetadata(+ bundle_id="com.test.app", bundle_type="APPL", is_watchos_app=False+ )+ distribution = SigningContextWithProfileSelection(+ info_plist_source=Path("/tmp/Info.plist"),+ info_plist_destination=Path("Info.plist"),+ info_plist_metadata=metadata,+ selected_profile_info=selected,+ )+ adhoc = AdhocSigningContext(+ codesign_identity="Apple Development: Adhoc",+ profile_selection_context=distribution,+ )+ data = adhoc.to_dict()+ json_str = json.dumps(+ {+ "codesign_identity": data["codesign_identity"],+ "profile_selection_context": {+ "info_plist_source": str(distribution.info_plist_source),+ "info_plist_destination": str(distribution.info_plist_destination),+ "info_plist_metadata": metadata.to_dict(),+ "selected_profile_info": {+ "identity": identity.to_dict(),+ "profile": profile.to_dict(),+ },+ },+ }+ )+ loaded = json.loads(json_str)+ restored = AdhocSigningContext.from_dict(loaded)+ self.assertEqual(restored.codesign_identity, "Apple Development: Adhoc")+ assert restored.profile_selection_context is not None+ self.assertEqual(+ restored.profile_selection_context.selected_profile_info.profile.uuid,+ "UUID-5678",+ )
@@ -0,0 +1,78 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>AppIDName</key>+ <string>Example</string>+ <key>ApplicationIdentifierPrefix</key>+ <array>+ <string>ABCDE12345</string>+ </array>+ <key>CreationDate</key>+ <date>2015-07-08T20:27:14Z</date>+ <key>Platform</key>+ <array>+ <string>iOS</string>+ </array>+ <key>DeveloperCertificates</key>+ <array>+ <data>+ MIIDSzCCAjOgAwIBAgIBATANBgkqhkiG9w0BAQsFADBTMSAwHgYDVQQDDBdCdWNrIFRlc3QgQ29kZXNp+ Z24gQ2VydDELMAkGA1UEBhMCVVMxIjAgBgkqhkiG9w0BCQEWE2V4YW1wbGVAZXhhbXBsZS5jb20wHhcN+ MTUxMDIzMjAwNzI1WhcNMzIwMzI3MjAwNzI1WjBTMSAwHgYDVQQDDBdCdWNrIFRlc3QgQ29kZXNpZ24g+ Q2VydDELMAkGA1UEBhMCVVMxIjAgBgkqhkiG9w0BCQEWE2V4YW1wbGVAZXhhbXBsZS5jb20wggEiMA0G+ CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCrmmMdeV17d72ihmdbB0MTn5v3iu9LSGVYlbnJbI+FNmDJ+ 1U/0PAR7aLIPux0puN3N1Rob5VMdSZCG+SvsjV5zUNyepiRYlhf1jMyYTGDuoF8EOtfE94w9kr1EH9gl+ aKRqir4770oXrFywbOaDO1iLPkpiVnfKVkkoU4dM0UD3YEtXoM70LIpYouGtVvNyc0Sx9/emvyiMH3iA+ yQz5erVdfJQ2O85eyXz+U6rrcsNQpE0AuyQNnBnm0irSvtvnoPxlCsf0EbLnmnkDlv8yTrgCxzj/jmys+ 0zs+EZFAjYCX/I2ef63Ll+Wm7ilh7CjwNaRMIQmL0QpJIR9kUYnp3v33AgMBAAGjKjAoMA4GA1UdDwEB+ /wQEAwIHgDAWBgNVHSUBAf8EDDAKBggrBgEFBQcDAzANBgkqhkiG9w0BAQsFAAOCAQEATpWzY5IXhyb4+ PXiRS64Q6Sh2YXj6Dot2srWC+FJwWngGbF6J8aQfoymsRTkgTa+69WinMefmdRkEzysmXvAUfD1iWpBX+ jRREQXkUhmt2FwqKp8pWbYSlgOTaQMojQn3DdvDu8l5ZFIrU+8Z8X4g/aggvffoIOygHvhbwkcgrA6Lq+ TziJssmKd56+QKfVfx52vg6pv1Ok03pmVsQ8semHTJr53juc4QutADhtJBXe9inVs1evosO15At0N731+ Lz37Bzwedpu8DSEr4PIdwF5yBDRbQoyAF29zQaJgO/mU2G4i9wYTZJrj75BD/qr2ukjQOYOtz4IVNUuz+ kPu+rDPz4A==+ </data>+ </array>+ <key>Entitlements</key>+ <dict>+ <key>keychain-access-groups</key>+ <array>+ <string>ABCDE12345.*</string>+ </array>+ <key>com.apple.security.get-task-allow</key>+ <false/>+ <key>com.apple.application-identifier</key>+ <string>ABCDE12345.com.example.TestApp</string>+ <key>com.apple.security.application-groups</key>+ <array>+ <string>group.com.example</string>+ </array>+ <key>com.apple.developer.team-identifier</key>+ <string>12345ABCDE</string>+ <key>com.apple.developer.icloud-container-development-container-identifiers</key>+ <array>+ <string>iCloud.com.appleseedinc.MyProject</string>+ <string>iCloud.com.appleseedinc.container1</string>+ </array>+ </dict>+ <key>ExpirationDate</key>+ <date>9999-03-05T01:33:40Z</date>+ <key>Name</key>+ <string>Example</string>+ <key>ProvisionsAllDevices</key>+ <true/>+ <key>TeamIdentifier</key>+ <array>+ <string>12345ABCDE</string>+ </array>+ <key>TeamName</key>+ <string>Example</string>+ <key>TimeToLive</key>+ <integer>240</integer>+ <key>UUID</key>+ <string>00000000-0000-0000-0000-000000000000</string>+ <key>Version</key>+ <integer>1</integer>+</dict>+</plist>
@@ -0,0 +1,78 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>AppIDName</key>+ <string>Example</string>+ <key>ApplicationIdentifierPrefix</key>+ <array>+ <string>ABCDE12345</string>+ </array>+ <key>CreationDate</key>+ <date>2015-07-08T20:27:14Z</date>+ <key>Platform</key>+ <array>+ <string>iOS</string>+ </array>+ <key>DeveloperCertificates</key>+ <array>+ <data>+ MIIDSzCCAjOgAwIBAgIBATANBgkqhkiG9w0BAQsFADBTMSAwHgYDVQQDDBdCdWNrIFRlc3QgQ29kZXNp+ Z24gQ2VydDELMAkGA1UEBhMCVVMxIjAgBgkqhkiG9w0BCQEWE2V4YW1wbGVAZXhhbXBsZS5jb20wHhcN+ MTUxMDIzMjAwNzI1WhcNMzIwMzI3MjAwNzI1WjBTMSAwHgYDVQQDDBdCdWNrIFRlc3QgQ29kZXNpZ24g+ Q2VydDELMAkGA1UEBhMCVVMxIjAgBgkqhkiG9w0BCQEWE2V4YW1wbGVAZXhhbXBsZS5jb20wggEiMA0G+ CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCrmmMdeV17d72ihmdbB0MTn5v3iu9LSGVYlbnJbI+FNmDJ+ 1U/0PAR7aLIPux0puN3N1Rob5VMdSZCG+SvsjV5zUNyepiRYlhf1jMyYTGDuoF8EOtfE94w9kr1EH9gl+ aKRqir4770oXrFywbOaDO1iLPkpiVnfKVkkoU4dM0UD3YEtXoM70LIpYouGtVvNyc0Sx9/emvyiMH3iA+ yQz5erVdfJQ2O85eyXz+U6rrcsNQpE0AuyQNnBnm0irSvtvnoPxlCsf0EbLnmnkDlv8yTrgCxzj/jmys+ 0zs+EZFAjYCX/I2ef63Ll+Wm7ilh7CjwNaRMIQmL0QpJIR9kUYnp3v33AgMBAAGjKjAoMA4GA1UdDwEB+ /wQEAwIHgDAWBgNVHSUBAf8EDDAKBggrBgEFBQcDAzANBgkqhkiG9w0BAQsFAAOCAQEATpWzY5IXhyb4+ PXiRS64Q6Sh2YXj6Dot2srWC+FJwWngGbF6J8aQfoymsRTkgTa+69WinMefmdRkEzysmXvAUfD1iWpBX+ jRREQXkUhmt2FwqKp8pWbYSlgOTaQMojQn3DdvDu8l5ZFIrU+8Z8X4g/aggvffoIOygHvhbwkcgrA6Lq+ TziJssmKd56+QKfVfx52vg6pv1Ok03pmVsQ8semHTJr53juc4QutADhtJBXe9inVs1evosO15At0N731+ Lz37Bzwedpu8DSEr4PIdwF5yBDRbQoyAF29zQaJgO/mU2G4i9wYTZJrj75BD/qr2ukjQOYOtz4IVNUuz+ kPu+rDPz4A==+ </data>+ </array>+ <key>Entitlements</key>+ <dict>+ <key>keychain-access-groups</key>+ <array>+ <string>ABCDE12345.*</string>+ </array>+ <key>get-task-allow</key>+ <false/>+ <key>application-identifier</key>+ <string>ABCDE12345.com.example.TestApp</string>+ <key>com.apple.security.application-groups</key>+ <array>+ <string>group.com.example</string>+ </array>+ <key>com.apple.developer.team-identifier</key>+ <string>12345ABCDE</string>+ <key>com.apple.developer.icloud-container-development-container-identifiers</key>+ <array>+ <string>iCloud.com.appleseedinc.MyProject</string>+ <string>iCloud.com.appleseedinc.container1</string>+ </array>+ </dict>+ <key>ExpirationDate</key>+ <date>9999-03-05T01:33:40Z</date>+ <key>Name</key>+ <string>Example</string>+ <key>ProvisionsAllDevices</key>+ <true/>+ <key>TeamIdentifier</key>+ <array>+ <string>12345ABCDE</string>+ </array>+ <key>TeamName</key>+ <string>Example</string>+ <key>TimeToLive</key>+ <integer>240</integer>+ <key>UUID</key>+ <string>00000000-0000-0000-0000-000000000000</string>+ <key>Version</key>+ <integer>1</integer>+</dict>+</plist>
@@ -0,0 +1,10 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>keychain-access-groups</key>+ <array>+ <string>ABCDE12345.com.example.TestApp</string>+ </array>+</dict>+</plist>
@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>application-identifier</key>+ <string>ABCDE12345.com.example.TestApp</string>+</dict>+</plist>
@@ -0,0 +1,10 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.developer.team-identifier</key>+ <string>ABCDE12345</string>+ <key>CFBundleIdentifier</key>+ <string>com.example.TestApp</string>+</dict>+</plist>
@@ -0,0 +1,11 @@+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("ios_devx")++source_listing()++python_binary(+ name = "codesign_manifest_tree_postprocessor",+ main = "main.py",+ visibility = ["PUBLIC"],+)
@@ -0,0 +1,97 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import argparse+import json+import os+from pathlib import Path+++def _extract_codesign_invocations_from_codesign_manifest_tree(+ current_path, codesign_manifest_tree, invocations+):+ inner_manifests = codesign_manifest_tree.get("inner_codesign_manifests", {})+ for inner_rel_path, inner_codesign_manifest_tree in inner_manifests.items():+ inner_path = os.path.join(current_path, inner_rel_path)+ # Process inner bundles first (i.e., inside out), as signing outer bundles+ # requires inner bundles to have already been signed (otherwise the outer+ # signature would be invalidated if the inner bundle is signed afterwards).+ _extract_codesign_invocations_from_codesign_manifest_tree(+ current_path=inner_path,+ codesign_manifest_tree=inner_codesign_manifest_tree,+ invocations=invocations,+ )++ codesign_manifest_path = codesign_manifest_tree.get("codesign_manifest")+ if codesign_manifest_path:+ with open(codesign_manifest_path, "r") as codesign_manifest_file:+ codesign_manifest = json.load(codesign_manifest_file)+ codesign_manifest_invocations = codesign_manifest.get("invocations", [])+ for original_manifest_invocation in codesign_manifest_invocations:+ original_invocation_path = original_manifest_invocation["path"]+ updated_invocation_path = (+ os.path.join(current_path, original_invocation_path)+ if original_invocation_path != "."+ else current_path+ )++ updated_manifest_invocation = dict(original_manifest_invocation)+ updated_manifest_invocation["path"] = updated_invocation_path++ invocations.append(updated_manifest_invocation)+++def _args_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description="Tool which postprocesses a codesign manifest tree."+ )+ parser.add_argument(+ "--codesign-manifest-tree",+ metavar="<codesign_manifest_tree.json>",+ type=Path,+ required=True,+ help="Path to the [codesign-manifest-tree] subtarget output.",+ )+ parser.add_argument(+ "--output",+ metavar="<output.json>",+ type=Path,+ required=True,+ help="Path to the postprocessed file.",+ )++ return parser+++def _main() -> None:+ args_parser = _args_parser()+ args = args_parser.parse_args()++ with open(args.codesign_manifest_tree, "r") as codesign_manifest_tree_file:+ codesign_manifest_tree = json.load(codesign_manifest_tree_file)++ invocations = []+ _extract_codesign_invocations_from_codesign_manifest_tree(+ current_path="",+ codesign_manifest_tree=codesign_manifest_tree,+ invocations=invocations,+ )++ with open(args.output, "w") as output_file:+ json.dump(+ {+ "version": 1,+ "invocations": invocations,+ },+ output_file,+ indent=4,+ )+++if __name__ == "__main__":+ _main()
@@ -0,0 +1,65 @@+#!/usr/bin/env fbpython+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import argparse+import json+++def _dedupe_entries(entries: list) -> list:+ # swiftc rejects an explicit module map with two entries for the same module+ # name reached via distinct tset nodes. The dedup key is+ # (moduleName, is_swiftmodule); in the projected JSON, swiftmodule entries+ # have a modulePath field while clang pcm entries have a clangModulePath+ # field, so the presence of modulePath reproduces is_swiftmodule exactly.+ seen = set()+ deduped = []+ for entry in entries:+ if "modulePath" in entry:+ key = (entry["moduleName"], True)+ elif "clangModulePath" in entry:+ key = (entry["moduleName"], False)+ else:+ raise RuntimeError(f"Unrecognized module map entry: {entry}")++ if key in seen:+ continue+ seen.add(key)+ deduped.append(entry)++ return deduped+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="De-duplicate entries in a Swift explicit module map."+ )+ parser.add_argument(+ "--input",+ required=True,+ help="Path to the input Swift module map JSON.",+ )+ parser.add_argument(+ "--output",+ required=True,+ help="Path to write the de-duplicated Swift module map JSON.",+ )+ args = parser.parse_args()++ with open(args.input) as f:+ entries = json.load(f)++ deduped = _dedupe_entries(entries)++ with open(args.output, "w") as f:+ json.dump(deduped, f, indent=2)+ f.write("\n")+++if __name__ == "__main__":+ main()
@@ -0,0 +1,51 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# @oss-disable[end= ]: load("@fbsource//tools/build_defs:python_platform.bzl", "set_platform_decorator_for_python")+load("@prelude//:is_full_meta_repo.bzl", "is_full_meta_repo")+load("@prelude//:native.bzl", _native = "native")++set_platform_decorator_for_python = lambda **kwargs: kwargs # @oss-enable++def meta_python_test(name, **kwargs):+ # Set the platform attributes as needed for proper exec platform resolution+ kwargs = set_platform_decorator_for_python(+ # @oss-disable[end= ]: set_python_constraint_overrides = True,+ **kwargs,+ )++ _native.python_test(name = name, **kwargs)++_PYTHON_SCRUBBER = "prelude//apple/tools/selective_debugging:tool"+_NATIVE_SCRUBBER = "prelude//apple/tools/meta_only/prebuilt_native_oso_scrubber:prebuilt_native_oso_scrubber"++def apple_oso_scrubber_target():+ if not is_full_meta_repo():+ return _PYTHON_SCRUBBER++ native_oso_scrubber_enabled_override = read_root_config("apple", "native_oso_scrubber_enabled_override", None)+ if native_oso_scrubber_enabled_override != None:+ # Override buckconfig takes precedence over everything else+ native_oso_scrubber_enabled = native_oso_scrubber_enabled_override.lower() == "true"+ return _NATIVE_SCRUBBER if native_oso_scrubber_enabled else _PYTHON_SCRUBBER++ native_oso_scrubber_enabled = read_root_config("apple", "native_oso_scrubber_enabled", "").lower() == "true"+ default_scrubber = _NATIVE_SCRUBBER if native_oso_scrubber_enabled else _PYTHON_SCRUBBER++ return select({+ "DEFAULT": default_scrubber,+ "ovr_config//features/apple/constraints:native_oso_scrubber_disabled": _PYTHON_SCRUBBER,+ "ovr_config//features/apple/constraints:native_oso_scrubber_enabled": _NATIVE_SCRUBBER,+ })++def bundle_telemetry_logger_target():+ return read_root_config("apple", "bundle_telemetry_logger", None)++def swiftmodule_change_analysis_target():+ # Overridable via buckconfig either way.+ return read_root_config("apple", "swiftmodule_change_analysis", None)
@@ -0,0 +1,36 @@+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("ios_pika")++source_listing()++cxx_binary(+ name = "native_dist_lto_planner",+ srcs = [+ "dist_lto_planner.cpp",+ ],+ compiler_flags = [+ "-Wno-deprecated-declarations",+ "-O2",+ ],+ linker_flags = [+ "-lc",+ ],+ tests = [+ "fbsource//xplat/buck2/tests/apple/rules/dist_lto:main-alias-iphonesimulator-arm64-pika-fat-lld-platform-distributed-thin-lto",+ ],+ visibility = ["PUBLIC"],+ deps = [+ "fbcode//common/files:files",+ "fbcode//folly:file_util",+ "fbcode//folly:json",+ "fbcode//folly:subprocess",+ "fbcode//folly/coro:blocking_wait",+ "fbcode//folly/coro:collect",+ "fbcode//folly/coro:shared_mutex",+ "fbcode//folly/coro:task",+ "fbcode//folly/executors:global_executor",+ "fbcode//folly/executors:io_thread_pool_executor",+ "fbcode//folly/init:init",+ ],+)
@@ -0,0 +1,468 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is dual-licensed under either the MIT license found in the+ * LICENSE-MIT file in the root directory of this source tree or the Apache+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory+ * of this source tree. You may select, at your option, one of the+ * above-listed licenses.+ */++#include <folly/DynamicConverter.h>+#include <folly/Subprocess.h>+#include <folly/coro/BlockingWait.h>+#include <folly/coro/Collect.h>+#include <folly/coro/SharedMutex.h>+#include <folly/coro/Task.h>+#include <folly/executors/GlobalExecutor.h>+#include <folly/executors/IOThreadPoolExecutor.h>+#include <folly/init/Init.h>+#include <folly/json.h>+#include <string.h>+#include <algorithm>+#include <filesystem>+#include <fstream>+#include <iostream>+#include <memory>+#include <optional>+#include <sstream>+#include <string>+#include <vector>+#include "common/files/FileUtil.h"++namespace {++static std::string metaFileInputPath;+static std::string indexFileOutputPath;+static std::string linkPlanFileOutputPath;+static bool enablePreMerger = false;+static bool dumpLinkerInvocation = false;+static std::vector<std::string> linkerInvocationCommand;+folly::coro::SharedMutex absorbedBitcodeFilesMutex;+folly::coro::SharedMutex nonLTOObjectFilesMutex;++struct ObjectFileRecord {+ const std::string inputObjectFilePath;+ const int starlarkArrayIndex;+ const std::string outputPlanFilePath;+ const std::string outputIndexShardFilePath;+ const std::optional<std::string> outputPremergedBitcodeFilePath;++ ObjectFileRecord(+ const std::string& inputObjectFilePath,+ const std::string& outputIndexShardFilePath,+ const std::string& outputPremergedBitcodeFilePath,+ const std::string& outputPlanFilePath,+ const int starlarkArrayIndex)+ : inputObjectFilePath(inputObjectFilePath),+ starlarkArrayIndex(starlarkArrayIndex),+ outputPlanFilePath(outputPlanFilePath),+ outputIndexShardFilePath(outputIndexShardFilePath),+ outputPremergedBitcodeFilePath(outputPremergedBitcodeFilePath) {}+};++enum class BitcodeMergeState {+ Standalone,+ Absorbed,+ Root,+ NotLoaded,+};++static const folly::json::serialization_opts jsonSerializationOptions = []() {+ folly::json::serialization_opts sorted;+ sorted.sort_keys = true;+ return sorted;+}();++static void parseArgs(int argc, char** argv) {+ int position = 1;+ const auto boundsCheckFlag = [&](const std::string& flag) {+ if (position + 1 >= argc) {+ std::cerr << "Missing argument for flag: " << flag << std::endl;+ std::abort();+ }+ };++ while (position < argc) {+ if (strcmp(argv[position], "--meta") == 0) {+ boundsCheckFlag("--meta");+ metaFileInputPath = argv[position + 1];+ position += 2;+ } else if (strcmp(argv[position], "--index") == 0) {+ boundsCheckFlag("--index");+ indexFileOutputPath = argv[position + 1];+ position += 2;+ } else if (strcmp(argv[position], "--link-plan") == 0) {+ boundsCheckFlag("--link-plan");+ linkPlanFileOutputPath = argv[position + 1];+ position += 2;+ } else if (strcmp(argv[position], "--enable-premerger") == 0) {+ enablePreMerger = true;+ position += 1;+ } else if (strcmp(argv[position], "--dump-linker-invocation") == 0) {+ dumpLinkerInvocation = true;+ position += 1;+ } else if (strcmp(argv[position], "--") == 0) {+ for (position++; position < argc; position++) {+ linkerInvocationCommand.emplace_back(argv[position]);+ }+ } else {+ std::cerr << "Could not recognize argument: " << argv[position]+ << std::endl;+ std::abort();+ }+ }+}++enum class MetaFileRecordType {+ ArchiveMember,+ ObjectFile,+};++constexpr std::string_view MERGED_BITCODE_SUFFIX = ".merged.bc";+constexpr std::string_view SUMMARY_SHARD_SUFFIX = ".thinlto.bc";+constexpr std::string_view IMPORTS_FILE_SUFFIX = ".imports";++using ObjectFileRecordsMapTy =+ std::unordered_map<std::string, std::shared_ptr<const ObjectFileRecord>>;++static void parseMetaFileRecords(ObjectFileRecordsMapTy& objectFileRecordsMap) {+ std::ifstream metaFile(metaFileInputPath);+ if (!metaFile.is_open()) {+ std::cerr << "Failed to open file: " << metaFileInputPath << std::endl;+ std::abort();+ }+ std::stringstream buffer;+ buffer << metaFile.rdbuf();+ try {+ auto jsonData = folly::parseJson(buffer.str());+ for (const auto& record : jsonData) {+ const std::string emptyString;+ const std::string outputPremergedBitcodeFilePath = enablePreMerger+ ? record["output_premerged_bitcode_file_path"].getString()+ : emptyString;+ std::shared_ptr<const ObjectFileRecord> parsedObjectFileRecord =+ std::make_shared<ObjectFileRecord>(+ record["input_object_file_path"].getString(),+ record["output_index_shard_file_path"].getString(),+ outputPremergedBitcodeFilePath,+ record["output_plan_file_path"].getString(),+ record["starlark_array_index"].getInt());+ objectFileRecordsMap[parsedObjectFileRecord->inputObjectFilePath] =+ parsedObjectFileRecord;+ }+ } catch (const folly::json::parse_error& e) {+ std::cerr << "Error parsing JSON: " << e.what() << std::endl;+ std::abort();+ }+}++static void populatePreMergerPathConversionMaps(+ const ObjectFileRecordsMapTy& objectFileRecordsMap,+ std::unordered_map<std::string, std::string>& preMergeToPostMerge,+ std::unordered_map<std::string, std::string>& postMergeToPreMerge) {+ for (const auto& [preMergePath, objectFileRecord] : objectFileRecordsMap) {+ std::string postMergePath;+ postMergePath = objectFileRecord->outputPremergedBitcodeFilePath.value();+ preMergeToPostMerge[preMergePath] = postMergePath;+ postMergeToPreMerge[postMergePath] = preMergePath;+ }+}++static void runThinLink(+ const std::unordered_map<std::string, std::string>& preMergeToPostMerge) {+ if (enablePreMerger) {+ // Buck requires actions write output files to a location set by the build+ // system. When toolchain binaries cannot for whatever reason easily+ // produce output files at known locations configurable locations, the usual+ // approach is to use a wrapper Python script such as this one to place the+ // files at the locations buck expects. In this case, this will not work as+ // sharded summaries embed paths to other bitcode files within the bitcode.+ // That means the toolchain must write the merged bitcode files to locations+ // buck expects in the first place. This json document is parsed by the+ // linker and communicates the locations at which the toolchain must write+ // the merged bitcode files.+ facebook::files::TemporaryFile preMergerOutputFileMappingFile(+ nullptr, "premergerOutputMap", /* keep */ true);+ std::ofstream stream(preMergerOutputFileMappingFile.filename());+ stream << folly::toJson(folly::toDynamic(preMergeToPostMerge));+ stream.flush();+ std::string preMergerMapFlag = "-Wl,-mllvm,-premerger-output-map=";+ preMergerMapFlag += preMergerOutputFileMappingFile.filename();+ linkerInvocationCommand.push_back((preMergerMapFlag));+ }++ if (dumpLinkerInvocation) {+ for (const auto& argument : linkerInvocationCommand) {+ std::cout << argument << " ";+ }+ std::cout << "\n";+ return;+ }++ folly::Subprocess subprocess(+ linkerInvocationCommand, folly::Subprocess::Options().usePath());+ subprocess.waitChecked();+}++static std::filesystem::path thinLTOPrefixReplacedPath(+ const std::filesystem::path& path) {+ // The linker is passed --thinlto-prefix-replace=";<indexFileOutPath>" which+ // instructs the linker to prefix various paths with the value of+ // <indexFileOutPath>.+ return std::filesystem::path(indexFileOutputPath) / path;+}++static std::unordered_map<std::string, uint> parseLoadedObjectFiles() {+ std::unordered_map<std::string, uint> loadedObjectFilesPositions;+ std::ifstream stream(thinLTOPrefixReplacedPath("index.full"));+ std::string line;+ uint position = 0;+ while (std::getline(stream, line)) {+ // Paths to bitcode files will be prefixed with the argument to+ // --thinlto-prefix-replace, so we need to remove that prefix first to get a+ // normalized path.+ if (line.size() >= indexFileOutputPath.size() &&+ line.substr(0, indexFileOutputPath.size()) == indexFileOutputPath) {+ std::string normalizedPath = line.substr(indexFileOutputPath.size() + 1);+ loadedObjectFilesPositions[normalizedPath] = position;+ } else {+ loadedObjectFilesPositions[line] = position;+ }+ position++;+ }+ return loadedObjectFilesPositions;+}++static const std::vector<std::string> readImportsFile(+ const std::string& importsFilePath,+ const std::unordered_map<std::string, std::string>& postMergeToPreMerge) {+ std::ifstream stream(importsFilePath);+ std::string line;+ std::vector<std::string> imports;+ while (std::getline(stream, line)) {+ if (enablePreMerger) {+ if (line.ends_with(MERGED_BITCODE_SUFFIX)) {+ imports.push_back(postMergeToPreMerge.at(line));+ } else {+ imports.push_back(line);+ }+ } else {+ imports.push_back(line);+ }+ }+ return imports;+}++static std::string getBitcodeMergeStateSpelling(const BitcodeMergeState state) {+ switch (state) {+ case BitcodeMergeState::Standalone:+ return "STANDALONE";+ case BitcodeMergeState::Absorbed:+ return "ABSORBED";+ case BitcodeMergeState::Root:+ return "ROOT";+ case BitcodeMergeState::NotLoaded:+ return "NOT_LOADED";+ }+}++static bool isFileLLVMBitcodeWrapperFile(const std::string& filePath) {+ const uint32_t LLVM_BITCODE_WRAPPER_FILE_MAGIC = 0xB17C0DE;+ std::ifstream stream(filePath, std::ios::binary);+ uint32_t magic;+ char buffer[sizeof(magic)];+ if (stream.read(buffer, sizeof(magic))) {+ memcpy(&magic, buffer, sizeof(magic));+ return magic == LLVM_BITCODE_WRAPPER_FILE_MAGIC;+ } else {+ std::cerr << "Failed to read magic number from file: " << filePath+ << std::endl;+ std::abort();+ }+}++static BitcodeMergeState readMergedBitcodeFile(+ const std::string& mergedBitcodePath) {+ if (!std::filesystem::file_size(mergedBitcodePath)) {+ return BitcodeMergeState::NotLoaded;+ }++ if (isFileLLVMBitcodeWrapperFile(mergedBitcodePath)) {+ return BitcodeMergeState::Root;+ }++ std::ifstream stream(mergedBitcodePath);+ std::string line;+ while (std::getline(stream, line)) {+ if (line == "standalone") {+ return BitcodeMergeState::Standalone;+ }+ if (line == "absorbed") {+ return BitcodeMergeState::Absorbed;+ }+ }++ std::cerr << "Ill-formatted merged bitcode file: " << mergedBitcodePath+ << std::endl;+ std::abort();+}++static void writeObjectFileOptimizationPlanToJSONFile(+ const std::vector<int>& objectFileImports,+ const bool isBitcode,+ const std::optional<BitcodeMergeState> bitcodeMergeState,+ const bool loadedByLinker,+ const std::string& outputPath,+ const int finalLinkLinePosition) {+ std::ofstream stream(outputPath);+ folly::dynamic json = folly::dynamic::object();+ json["imports"] = folly::toDynamic(objectFileImports);+ json["is_bitcode"] = isBitcode;+ if (bitcodeMergeState) {+ json["merge_state"] =+ getBitcodeMergeStateSpelling(bitcodeMergeState.value());+ }+ json["loaded_by_linker"] = loadedByLinker;+ json["final_link_line_position"] = finalLinkLinePosition;+ stream << folly::json::serialize(json, jsonSerializationOptions);+}++static void writeLinkPlan(std::vector<int>& nonLTOObjectFiles) {+ std::ofstream stream(linkPlanFileOutputPath);+ folly::dynamic json = folly::dynamic::object;+ folly::dynamic nonLTOObjectsJson = folly::dynamic::object();+ for (const auto starlarkIndex : nonLTOObjectFiles) {+ nonLTOObjectsJson[std::to_string(starlarkIndex)] = 1;+ }+ json["non_lto_objects"] = nonLTOObjectsJson;+ stream << folly::json::serialize(json, jsonSerializationOptions);+}++static folly::coro::Task<void> writeOptimizationPlanForObjectFile(+ const std::string& inputObjectFilePath,+ const ObjectFileRecord* objectFile,+ const ObjectFileRecordsMapTy& objectFileRecordsMap,+ const std::unordered_map<std::string, std::string>& postMergeToPreMerge,+ const std::unordered_map<std::string, uint>& loadedObjectFilesPositions,+ std::unordered_set<std::string>& absorbedBitcodeFiles,+ std::vector<int>& nonLTOObjectFiles) {+ co_await folly::coro::co_reschedule_on_current_executor;++ std::filesystem::create_directories(+ std::filesystem::path(objectFile->outputIndexShardFilePath)+ .parent_path());++ const std::string temporaryIndexShardFilePath =+ thinLTOPrefixReplacedPath(objectFile->inputObjectFilePath)+ .concat(SUMMARY_SHARD_SUFFIX);++ const std::string importsFilePath =+ thinLTOPrefixReplacedPath(objectFile->inputObjectFilePath)+ .concat(IMPORTS_FILE_SUFFIX);++ int finalLinkLinePosition = -1;+ auto it = loadedObjectFilesPositions.find(inputObjectFilePath);+ if (it != loadedObjectFilesPositions.end()) {+ finalLinkLinePosition = it->second;+ }++ if (std::filesystem::exists(importsFilePath)) {+ std::filesystem::rename(+ temporaryIndexShardFilePath, objectFile->outputIndexShardFilePath);++ const auto imports = readImportsFile(importsFilePath, postMergeToPreMerge);++ std::vector<int> objectFileImports;+ for (const auto& importPath : imports) {+ const auto& objectFileRecord = objectFileRecordsMap.at(importPath);+ objectFileImports.push_back(objectFileRecord->starlarkArrayIndex);+ }++ std::optional<BitcodeMergeState> bitcodeMergeState;+ if (enablePreMerger) {+ bitcodeMergeState = readMergedBitcodeFile(+ objectFile->outputPremergedBitcodeFilePath.value());+ if (bitcodeMergeState == BitcodeMergeState::Absorbed) {+ co_await absorbedBitcodeFilesMutex.co_lock();+ absorbedBitcodeFiles.insert(objectFile->inputObjectFilePath);+ absorbedBitcodeFilesMutex.unlock();+ }+ }++ writeObjectFileOptimizationPlanToJSONFile(+ objectFileImports,+ /* isBitcode */ true,+ bitcodeMergeState,+ /* loadedByLinker */+ loadedObjectFilesPositions.contains(inputObjectFilePath),+ objectFile->outputPlanFilePath,+ finalLinkLinePosition);+ } else {+ co_await nonLTOObjectFilesMutex.co_lock();+ nonLTOObjectFiles.push_back(objectFile->starlarkArrayIndex);+ nonLTOObjectFilesMutex.unlock();+ // The linker will not generate an index shard, or a merged bitcode file if+ // the input is not bitcode. Buck still expects the output, so write empty+ // files.+ std::ofstream(objectFile->outputIndexShardFilePath).close();++ if (enablePreMerger) {+ std::ofstream(objectFile->outputPremergedBitcodeFilePath.value()).close();+ }++ writeObjectFileOptimizationPlanToJSONFile(+ /* objectFileImports */ {},+ /* isBitcode */ false,+ // Native object files do no participate in bitcode merging+ /* bitcodeMergeState */ std::nullopt,+ loadedObjectFilesPositions.contains(inputObjectFilePath),+ objectFile->outputPlanFilePath,+ finalLinkLinePosition);+ }+ co_return;+}++} // namespace++int main(int argc, char** argv) {+ int fakeArgc = 1;+ folly::Init init(&fakeArgc, &argv);+ parseArgs(argc, argv);+ ObjectFileRecordsMapTy objectFileRecordsMap;+ parseMetaFileRecords(objectFileRecordsMap);+ std::unordered_map<std::string, std::string> preMergeToPostMerge;+ std::unordered_map<std::string, std::string> postMergeToPreMerge;+ if (enablePreMerger) {+ populatePreMergerPathConversionMaps(+ objectFileRecordsMap, preMergeToPostMerge, postMergeToPreMerge);+ }+ runThinLink(preMergeToPostMerge);+ if (dumpLinkerInvocation) {+ return 0;+ }++ std::unordered_map<std::string, uint> loadedObjectFilesPositions =+ parseLoadedObjectFiles();++ std::unordered_set<std::string> absorbedBitcodeFiles;+ std::vector<int> nonLTOObjectFiles;+ std::vector<folly::coro::Task<void>> tasks;+ for (const auto& [inputObjectFilePath, objectFileRecord] :+ objectFileRecordsMap) {+ tasks.push_back(writeOptimizationPlanForObjectFile(+ inputObjectFilePath,+ objectFileRecord.get(),+ objectFileRecordsMap,+ postMergeToPreMerge,+ loadedObjectFilesPositions,+ absorbedBitcodeFiles,+ nonLTOObjectFiles));+ }++ folly::coro::blockingWait(co_withExecutor(+ folly::getGlobalCPUExecutor(),+ folly::coro::collectAllRange(std::move(tasks))));++ writeLinkPlan(nonLTOObjectFiles);+}
@@ -0,0 +1,82 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import argparse+import plistlib+import shutil+from pathlib import Path++_CODE_SIGN_DRY_RUN_ARGS_FILE = "BUCK_code_sign_args.plist"+_CODE_SIGN_DRY_RUN_ENTITLEMENTS_FILE = "BUCK_code_sign_entitlements.plist"+++def _args_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description="""+ Tool which implements `DryCodeSignStep` class from buck1.+ Instead of code signing the bundle it just creates a file named `BUCK_code_sign_args.plist` inside,+ which contains all parameters needed to perform a deferred signing later.+ """+ )+ parser.add_argument(+ "root",+ type=Path,+ )+ parser.add_argument(+ "--entitlements",+ metavar="<Entitlements.plist>",+ type=Path,+ required=False,+ help="Path to file with entitlements to be used during code signing.",+ )+ parser.add_argument(+ "--identity",+ type=str,+ required=True,+ )+ parser.add_argument(+ "--subject-common-name",+ type=str,+ required=True,+ )+ parser.add_argument(+ "--extra-paths-to-sign",+ type=str,+ nargs="*",+ )++ return parser+++def _main() -> None:+ args = _args_parser().parse_args()+ content = {+ # This is always empty string if you check `DryCodeSignStep` class usages in buck1+ "relative-path-to-sign": "",+ "use-entitlements": args.entitlements is not None,+ "debug-info": {+ "identity": args.identity,+ "subject-common-name": args.subject_common_name,+ },+ }+ if args.extra_paths_to_sign:+ content["extra-paths-to-sign"] = args.extra_paths_to_sign+ with open(args.root / _CODE_SIGN_DRY_RUN_ARGS_FILE, "wb") as f:+ # Do not sort to keep the ordering same as in buck1.+ plistlib.dump(content, f, sort_keys=False, fmt=plistlib.FMT_XML)+ if args.entitlements:+ shutil.copy2(+ args.entitlements,+ args.root / _CODE_SIGN_DRY_RUN_ENTITLEMENTS_FILE,+ )+++if __name__ == "__main__":+ _main()
@@ -0,0 +1,72 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++"""+Removes files from a framework that are not necessary when distributing+inside app bundles. Specifically Modules/* Headers/* and Documentation/*++Example Usage:+xcframework_sanitizer.py --input original/Foo.framework \+--output output/Foo.framework +"""++import argparse+import os+import re+import shutil+from pathlib import Path+from typing import Callable, Iterable+++def _should_ignore(+ framework_root: str,+) -> Callable[[str, list[str]], Iterable[str]]:+ prohibited: list[str] = ["Modules", "Headers", "Documentation"]++ def _should_ignore_impl(root: str, contents: list[str]) -> Iterable[str]:+ if re.sub(r"/Versions/[A-Z]", "", root) == framework_root:+ return prohibited+ return []++ return _should_ignore_impl+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="Prepare a framework for distribution by removing unnecessary files."+ )++ parser.add_argument("--input", required=True)+ parser.add_argument("--output", required=True)+ parser.add_argument("--replacement-binary")+ args = parser.parse_args()++ out_path = Path(args.output)++ shutil.copytree(+ args.input,+ out_path,+ symlinks=True,+ dirs_exist_ok=False,+ ignore=_should_ignore(args.input),+ )++ if args.replacement_binary:+ framework_name = os.path.splitext(os.path.basename(out_path))[0]+ # Use realpath() because for macOS versioned bundles+ # we may need to follow a symlink:+ framework_binary_path = os.path.realpath(out_path / framework_name)+ os.chmod(framework_binary_path, 0o644)++ shutil.copy(args.replacement_binary, framework_binary_path)+++if __name__ == "__main__":+ main()
@@ -0,0 +1,27 @@+load("@prelude//apple/tools:defs.bzl", "meta_python_test")+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("apple_build_infra")++source_listing()++python_bootstrap_binary(+ name = "merge_index_store",+ main = "merge_index_store.py",+ visibility = ["PUBLIC"],+)++python_bootstrap_library(+ name = "merge_index_store_lib",+ srcs = ["merge_index_store.py"],+ tests = [":merge_index_store_tests"],+ visibility = ["PUBLIC"],+)++meta_python_test(+ name = "merge_index_store_tests",+ srcs = [+ "merge_index_store.py",+ "merge_index_store_tests.py",+ ],+)
@@ -0,0 +1,102 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import argparse+import os+import subprocess+import sys+from argparse import Namespace+from concurrent.futures import as_completed, ThreadPoolExecutor+from pathlib import Path++MAX_WORKERS = 8+++def parse_arguments() -> Namespace:+ parser = argparse.ArgumentParser()+ parser.add_argument("-d", "--dest", type=str, required=True)+ parser.add_argument("-s", "--sources", nargs="+", type=str, required=True)+ return parser.parse_args()+++def merge_directory(source: str, destination: str) -> None:+ if os.path.isdir(source):+ print(f"Merging {source} to {destination}", file=sys.stderr)+ if not source.endswith("/"):+ source = source + "/"++ # Each index store is a directory containing record and unit files.+ #+ # $ ls my_index_store+ # v5/records/93/scope6_var.h-3KOUVOFGN7X93+ # v5/records/93/ShareViewController.swift-336T0RUILP193+ # v5/records/95/host_security.h-NRLXTM4VIC95+ # v5/units/ShareViewController.swift-5TSSN9QOIJ15+ #+ # We want a single destination directory containing all the record and unit+ # files from all the source directories.+ #+ # There's no built-in way to merge directories in buck. In Python, there is+ # `shutil.copytree(source, dest, dirs_exist_ok=True)` but that overwrites+ # files in the destination when there are multiple sources with the same+ # file. That's slower.+ #+ # Instead, use rsync to merge the directories.+ #+ # Use `--no-owner` to ensure the files in the destination directory are+ # owned by the current user, even if some of the input files were owned by+ # root.+ result = subprocess.run(+ [+ "rsync",+ "-a",+ "--ignore-existing",+ "--no-owner",+ "--no-group",+ source,+ destination,+ ],+ stderr=subprocess.PIPE,+ text=True,+ )+ if result.returncode != 0:+ raise Exception(+ f"Failed to merge {source} to {destination}:\n\t{result.stderr}"+ )+ else:+ raise Exception(f"Directory {source} does not exist or is not a directory")+++def main() -> None:+ args = parse_arguments()+ destination = args.dest++ directories = []+ for source in args.sources:+ if source.startswith("@"):+ with open(source[1:]) as f:+ for line in f.readlines():+ directories.append(line.strip())+ else:+ directories.append(source)++ Path(destination).mkdir(parents=True, exist_ok=True)++ with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:+ futures = [+ executor.submit(merge_directory, index_dir, destination)+ for index_dir in directories+ ]+ for future in as_completed(futures):+ future.result() # This will raise any exceptions that occurred+++if __name__ == "__main__":+ main()
@@ -0,0 +1,69 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import subprocess+import unittest+from unittest.mock import MagicMock, patch++from .merge_index_store import merge_directory, parse_arguments+++class TestMergeIndexStore(unittest.TestCase):+ def test_parse_arguments(self) -> None:+ test_args = ["-d", "destination", "-s", "source1", "source2"]+ with patch("sys.argv", ["script"] + test_args):+ args = parse_arguments()+ self.assertEqual(args.dest, "destination")+ self.assertEqual(args.sources, ["source1", "source2"])++ @patch("os.path.isdir")+ @patch("subprocess.run")+ def test_merge_directories(+ self, mock_run: MagicMock, mock_isdir: MagicMock+ ) -> None:+ mock_isdir.return_value = True+ mock_run.return_value = MagicMock(returncode=0, stderr="")++ merge_directory("source", "destination")+ mock_run.assert_called_once_with(+ [+ "rsync",+ "-a",+ "--ignore-existing",+ "--no-owner",+ "--no-group",+ "source/",+ "destination",+ ],+ stderr=subprocess.PIPE,+ text=True,+ )++ @patch("os.path.isdir")+ @patch("subprocess.run")+ def test_merge_directories_failure(+ self, mock_run: MagicMock, mock_isdir: MagicMock+ ) -> None:+ mock_isdir.return_value = True+ mock_run.return_value = MagicMock(returncode=1, stderr="Error")++ with self.assertRaises(Exception) as context:+ merge_directory("source", "destination")+ self.assertTrue("Failed to merge" in str(context.exception))++ @patch("os.path.isdir")+ def test_merge_non_existing_directory(self, mock_isdir: MagicMock) -> None:+ mock_isdir.return_value = False+ with self.assertRaises(Exception) as context:+ merge_directory("source", "destination")+ self.assertTrue(+ "Directory source does not exist or is not a directory"+ in str(context.exception)+ )
@@ -0,0 +1,40 @@+load("@prelude//apple/tools:defs.bzl", "meta_python_test")+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("build_infra")++source_listing()++python_library(+ name = "preprocess",+ srcs = ["preprocess.py"],+)++meta_python_test(+ name = "preprocess_test",+ srcs = ["preprocess_test.py"],+ deps = [":preprocess"],+)++python_library(+ name = "process",+ srcs = ["process.py"],+ visibility = ["PUBLIC"],+ deps = ["prelude//apple/tools:plistlib_utils"],+)++meta_python_test(+ name = "process_test",+ srcs = ["process_test.py"],+ deps = [":process"],+)++python_binary(+ name = "tool",+ main = "main.py",+ visibility = ["PUBLIC"],+ deps = [+ ":preprocess",+ ":process",+ ],+)
@@ -0,0 +1,194 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import argparse+import io+import plistlib+from contextlib import ExitStack+from enum import Enum+from pathlib import Path++from apple.tools.plistlib_utils import detect_format_and_load++from .preprocess import preprocess+from .process import process+++class _SubcommandName(str, Enum):+ preprocess = "preprocess"+ process = "process"+++def _create_preprocess_subparser(+ subparsers: "argparse._SubParsersAction[argparse.ArgumentParser]",+) -> None:+ parser = subparsers.add_parser(+ _SubcommandName.preprocess.value,+ description="Sub-command to expand macro variables in parametrized Info.plist files. It's the Buck v2 equivalent of what `FindAndReplaceStep` and `InfoPlistSubstitution` do.",+ )+ parser.add_argument(+ "--input",+ metavar="<Input.plist>",+ type=Path,+ required=True,+ help="Path to the input which is a .plist file ",+ )+ parser.add_argument(+ "--output",+ metavar="<Output.plist>",+ type=Path,+ required=True,+ help="Path where the output, .plist with applied substitutions, should be written to",+ )+ parser.add_argument(+ "--product-name",+ metavar="<Product Name>",+ type=str,+ required=True,+ help="Product name, the value of `apple_bundle().product_name` attribute to be used in substitutions",+ )+ parser.add_argument(+ "--substitutions-json",+ metavar="<Substitutions JSON File>",+ type=Path,+ help="JSON file containing substitutions mapping",+ )+ parser.add_argument(+ "--enforce-minimum-os-plist-key",+ metavar="<Minimum OS Version Key>",+ type=str,+ help="Key for minimum OS version that should not be present in the plist file",+ )+++def _create_process_subparser(+ subparsers: "argparse._SubParsersAction[argparse.ArgumentParser]",+) -> None:+ parser = subparsers.add_parser(+ _SubcommandName.process.value,+ description="Sub-command to do the final processing of the Info.plist before it's copied to the application bundle. It's the Buck v2 equivalent of what `PlistProcessStep` does in v1.",+ )+ parser.add_argument(+ "--input",+ metavar="<Input.plist>",+ type=Path,+ required=True,+ help="Path to unprocessed .plist file",+ )+ parser.add_argument(+ "--override-input",+ metavar="<OverrideInput.plist>",+ type=Path,+ help="Path to the additional .plist file which should be merged into final result overriding keys present in unprocessed file or any other --additional-* argument.",+ )+ parser.add_argument(+ "--additional-keys",+ metavar="<AdditionalKeys.json>",+ type=Path,+ help="Path to .json file containing additional data which should be merged into the final result if keys are not yet present in unprocessed file.",+ )+ parser.add_argument(+ "--override-keys",+ metavar="<OverrideKeys.json>",+ type=Path,+ help="Path to .json file with additional data which should be merged into the final result overriding keys present in unprocessed file or any other --additional-* or --override-* argument.",+ )+ parser.add_argument(+ "--output",+ metavar="<Output.plist>",+ type=Path,+ required=True,+ help="Path where processed .plist file should be placed",+ )+ parser.add_argument(+ "--output-xml",+ action="store_true",+ help="Output as XML",+ )+ parser.add_argument(+ "--mutations",+ metavar="<Mutations.json>",+ type=Path,+ help="Path to .json file containing mutation operations to apply to the plist",+ )+++def _parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description="Tool to process Info.plist file before it is placed into the bundle. It's the Buck v2 equivalent of what `AppleInfoPlist` build rule from v1 does."+ )+ subparsers = parser.add_subparsers(dest="subcommand_name")+ _create_preprocess_subparser(subparsers)+ _create_process_subparser(subparsers)+ return parser.parse_args()+++def main() -> None:+ args = _parse_args()+ if args.subcommand_name == _SubcommandName.preprocess:+ with ExitStack() as stack:+ with args.input.open(mode="rb") as binary_file:+ plist_data = detect_format_and_load(binary_file)+ xml_content = plistlib.dumps(plist_data, fmt=plistlib.FMT_XML).decode(+ "utf-8"+ )+ input_file = io.StringIO(xml_content)++ output_file = stack.enter_context(args.output.open(mode="w"))+ substitutions_json = (+ stack.enter_context(args.substitutions_json.open(mode="r"))+ if args.substitutions_json is not None+ else None+ )+ preprocess(+ input_file,+ output_file,+ substitutions_json,+ args.product_name,+ args.enforce_minimum_os_plist_key,+ )+ elif args.subcommand_name == _SubcommandName.process:+ with ExitStack() as stack:+ input_file = stack.enter_context(args.input.open(mode="rb"))+ output_file = stack.enter_context(args.output.open(mode="wb"))+ override_input = (+ stack.enter_context(args.override_input.open(mode="rb"))+ if args.override_input is not None+ else None+ )+ additional_keys = (+ stack.enter_context(args.additional_keys.open(mode="rb"))+ if args.additional_keys is not None+ else None+ )+ override_keys = (+ stack.enter_context(args.override_keys.open(mode="rb"))+ if args.override_keys is not None+ else None+ )+ output_format = plistlib.FMT_XML if args.output_xml else plistlib.FMT_BINARY+ mutations_file = (+ stack.enter_context(args.mutations.open(mode="r"))+ if args.mutations is not None+ else None+ )+ process(+ input_file=input_file,+ output_file=output_file,+ override_input_file=override_input,+ additional_keys_file=additional_keys,+ override_keys_file=override_keys,+ output_format=output_format,+ mutations_file=mutations_file,+ )+++if __name__ == "__main__":+ main()
@@ -0,0 +1,99 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import json+import re+import sys+from enum import Enum+from typing import Optional, TextIO+++class _ReGroupName(str, Enum):+ openparen = "openparen"+ variable = "variable"+ modifier = "modifier"+ closeparen = "closeparen"++ def __format__(self, spec):+ return f"{self.value}"+++_re_string: str = "\\$(?P<{openparen}>[\\{{\\(])(?P<{variable}>[^\\}}\\):]+)(?::(?P<{modifier}>[^\\}}\\)]+))?(?P<{closeparen}>[\\}}\\)])".format(+ openparen=_ReGroupName.openparen,+ variable=_ReGroupName.variable,+ modifier=_ReGroupName.modifier,+ closeparen=_ReGroupName.closeparen,+)+++def _make_substitution_dict(+ substitutions_json_file: TextIO, product_name: str+) -> dict[str, str]:+ result = {+ "EXECUTABLE_NAME": product_name,+ "PRODUCT_NAME": product_name,+ }+ if substitutions_json_file is not None:+ # JSON file take precedence over default substitutions+ result.update(json.load(substitutions_json_file))+ return result+++def _process_line(+ line: str,+ pattern: re.Pattern[str],+ substitutions: dict[str, str],+ minimum_os_version_key: Optional[str],+) -> str:+ if (+ minimum_os_version_key is not None+ and line.strip() == f"<key>{minimum_os_version_key}</key>"+ ):+ print("Found minimum OS version key in plist file", file=sys.stderr)+ sys.exit(1)++ result = line+ pos = 0+ substituted_keys = set()+ while True:+ match = pattern.search(result, pos)+ if match is None:+ break+ key = match.group(_ReGroupName.variable)+ if key in substituted_keys:+ raise RuntimeError(f"Recursive plist variable: ... -> {key} -> ...")+ if key in substitutions:+ result = (+ result[: match.start()] + substitutions[key] + result[match.end() :]+ )+ substituted_keys.add(key)+ # Keep the same position to handle the situation when variable was expanded into another variable+ new_pos = match.start()+ else:+ new_pos = match.end()+ if new_pos != pos:+ substituted_keys = set()+ pos = new_pos+ return result+++def preprocess(+ input_file: TextIO,+ output_file: TextIO,+ substitutions_file: TextIO,+ product_name: str,+ minimum_os_version_key: Optional[str] = None,+) -> None:+ pattern = re.compile(_re_string)+ substitutions = _make_substitution_dict(substitutions_file, product_name)+ for line in input_file:+ output_file.write(+ _process_line(line, pattern, substitutions, minimum_os_version_key)+ )
@@ -0,0 +1,91 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import io+import unittest++from .preprocess import preprocess+++class TestPreprocess(unittest.TestCase):+ def test_default_substitution_values(self):+ input_file = io.StringIO(+ r"""+<string>${PRODUCT_NAME}</string>+<string>${EXECUTABLE_NAME}</string>+"""+ )+ expected = r"""+<string>my_product_name</string>+<string>my_product_name</string>+"""+ substitutions_file = io.StringIO(r"{}")+ output_file = io.StringIO("")+ preprocess(input_file, output_file, substitutions_file, "my_product_name")+ self.assertEqual(output_file.getvalue(), expected)++ def test_json_substitution_values_precede_default_ones(self):+ input_file = io.StringIO(+ r"""+<string>${PRODUCT_NAME}</string>+<string>${EXECUTABLE_NAME}</string>+"""+ )+ expected = r"""+<string>foo</string>+<string>bar</string>+"""+ substitutions_file = io.StringIO(+ r"""+{+ "PRODUCT_NAME": "foo",+ "EXECUTABLE_NAME": "bar"+}+"""+ )+ output_file = io.StringIO("")+ preprocess(input_file, output_file, substitutions_file, "my_product_name")+ self.assertEqual(output_file.getvalue(), expected)++ def test_chained_substitutions(self):+ input_file = io.StringIO(r"<string>${foo}</string>")+ expected = r"<string>baz</string>"+ substitutions_file = io.StringIO(+ r"""+{+ "foo": "${bar}",+ "bar": "baz"+}+"""+ )+ output_file = io.StringIO("")+ preprocess(input_file, output_file, substitutions_file, "my_product_name")+ self.assertEqual(output_file.getvalue(), expected)++ def test_recursive_substitutions_throws(self):+ input_file = io.StringIO(r"<string>${foo}</string>")+ substitutions_file = io.StringIO(+ r"""+{+ "foo": "${bar}",+ "bar": "${foo}"+}+"""+ )+ output_file = io.StringIO("")+ with self.assertRaises(Exception) as context:+ preprocess(input_file, output_file, substitutions_file, "my_product_name")+ self.assertTrue("Recursive" in str(context.exception))++ def test_variable_with_modifier(self):+ input_file = io.StringIO(r"<string>${foo:modifier}</string>")+ expected = r"<string>bar</string>"+ substitutions_file = io.StringIO(r'{"foo":"bar"}')+ output_file = io.StringIO("")+ preprocess(input_file, output_file, substitutions_file, "my_product_name")+ self.assertEqual(output_file.getvalue(), expected)
@@ -0,0 +1,269 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import json+import plistlib+import sys+from typing import Any, IO, Optional, TextIO++from apple.tools.plistlib_utils import detect_format_and_load+++def _deepmerge_plist_dicts(source: dict[str, Any], destination: dict[str, Any]):+ for key in source:+ if key not in destination:+ destination[key] = source[key]+ elif isinstance(source[key], dict) and isinstance(destination[key], dict):+ _deepmerge_plist_dicts(source[key], destination[key])+ elif isinstance(source[key], list) and isinstance(destination[key], list):+ for item in source[key]:+ if item not in destination[key]:+ destination[key].append(item)+ elif destination[key] == source[key]:+ pass+ else:+ print(+ f'Cannot merge value "{source[key]}" into "{destination[key]}" at "{key}"',+ file=sys.stderr,+ )+ exit(3)+++# Corresponding v1 code is contained in `com/facebook/buck/apple/PlistProcessStep.java`, `PlistProcessStep::execute` method.+def _merge_plist_dicts(+ source: dict[str, Any],+ destination: dict[str, Any],+ override: bool = False,+) -> None:+ for key, value in source.items():+ if key not in destination:+ destination[key] = value+ elif isinstance(value, dict) and isinstance(destination[key], dict):+ destination[key].update(value)+ elif override:+ # override the value+ destination[key] = value+++def _apply_merge(plist_data: dict[str, Any], merge_path: str) -> None:+ """Apply a merge mutation to plist data."""+ try:+ # Load the plist file to merge+ with open(merge_path, "rb") as merge_file:+ merge_data = detect_format_and_load(merge_file)+ # Merge the data into the main plist+ _deepmerge_plist_dicts(+ source=merge_data,+ destination=plist_data,+ )+ except OSError:+ # If the file can't be found or read, skip this merge operation+ # This maintains compatibility with the current behavior+ pass+++def _traverse_keypath(+ plist_data: dict[str, Any],+ keypath_str: str,+ insert_arrays=True,+) -> tuple[str | int, Any]:+ """Return the internal object in plist_data found at the keypath_str, save+ for the last component.++ keypath_str is a key-value coding key path, extended to allow a numerical+ element to index in an array. As a consequence, we can return an int or a+ str for the last component.+ """++ keypath = keypath_str.split(".")+ plist_pointer = plist_data++ for key in keypath[:-1]:+ if isinstance(plist_pointer, list):+ found = False+ for elem in plist_pointer:+ if key in elem:+ plist_pointer = elem+ found = True+ break+ if not found:+ new_object = {key: []}+ plist_pointer.append(new_object)+ plist_pointer = new_object+ if key.endswith("]"):+ key, indexstr = key[:-1].split("[")+ index = int(indexstr)+ plist_pointer = plist_pointer[key][index]+ else:+ if key not in plist_pointer and insert_arrays:+ plist_pointer[key] = []+ plist_pointer = plist_pointer[key]+ final_key = keypath[-1]+ if final_key.endswith("]"):+ key, indexstr = final_key[:-1].split("[")+ plist_pointer = plist_pointer[key]+ final_key = int(indexstr)++ return final_key, plist_pointer+++def _apply_insert(plist_data: dict[str, Any], insert_params: dict[str, Any]) -> None:+ """Apply an insert mutation to plist data.+ Sample data:+ <key>CFBundleURLTypes</key>+ <array>+ <dict>+ <key>CFBundleURLSchemes</key>+ <array>+ <string>spotify</string>+ </array>+ </dict>+ …+ </array>+ </key>++ Sample mutation:+ {"keypath": "CFBundleURLTypes.CFBundleURLSchemes", "value": "fb-messenger-public"}++ Result:+ <key>CFBundleURLTypes</key>+ <array>+ <dict>+ <key>CFBundleURLSchemes</key>+ <array>+ <string>spotify</string>+ <string>fb-messenger-public</string>+ </array>+ </dict>+ …+ </array>+ </key>+ """+ keypath = insert_params["keypath"]+ value = insert_params["value"]+ key, plist_pointer = _traverse_keypath(plist_data, keypath)++ if isinstance(plist_pointer, list):+ # e.g. See example above where CFBundleURLSchemes is contained in a+ # list inside a dict.+ found = False+ for element in plist_pointer:+ if key in element:+ plist_pointer = element+ found = True+ break++ if not found:+ new_dict = {key: []}+ plist_pointer.append(new_dict)+ plist_pointer = new_dict++ if not isinstance(plist_pointer, dict):+ print(+ f"Expected dictionary at keypath {keypath}, but found: {type(plist_pointer)}",+ file=sys.stderr,+ )+ exit(3)+ if key not in plist_pointer:+ plist_pointer[key] = []+ plist_pointer = plist_pointer[key]++ if value not in plist_pointer:+ plist_pointer.insert(0, value)+++def _apply_set(plist_data: dict[str, Any], set_params: dict[str, Any]) -> None:+ """Apply a set mutation to plist data."""+ keypath = set_params["keypath"]+ value = set_params["value"]+ key, plist_pointer = _traverse_keypath(plist_data, keypath)+ plist_pointer[key] = value+++def _apply_copy(+ plist_data: dict[str, Any], source_path: str, copy_params: list[str]+) -> None:+ """Copy an element from a source plist to the target plist"""+ source_keypath = copy_params["source_keypath"]+ target_keypath = copy_params["target_keypath"]+ ignore_missing_source = copy_params.get("ignore_missing_source", False)+ with open(source_path, "rb") as source_file:+ source_data = detect_format_and_load(source_file)+ target_key, target_element = _traverse_keypath(plist_data, target_keypath)+ try:+ source_key, source_element = _traverse_keypath(+ source_data, source_keypath, insert_arrays=False+ )+ target_element[target_key] = source_element[source_key]+ except (KeyError, IndexError) as e:+ print(+ f"source plist doesn't contain keypath {source_keypath} for copy",+ file=sys.stderr,+ )+ if ignore_missing_source:+ return+ raise e+++def _apply_mutations(+ plist_data: dict[str, Any], mutations: list[tuple[str, str] | tuple[str, dict]]+) -> None:+ """Apply a list of mutation operations to plist data."""+ for mutation in mutations:+ operation = mutation[0]+ if operation == "merge":+ _apply_merge(plist_data, mutation[1])+ elif operation == "insert":+ _apply_insert(plist_data, mutation[1])+ elif operation == "set":+ _apply_set(plist_data, mutation[1])+ elif operation == "copy":+ _apply_copy(plist_data, mutation[1], mutation[2])+ else:+ print(+ f"Attempting to apply unknown plist mutation operation {operation}",+ file=sys.stderr,+ )+ sys.exit(2)+++def process(+ input_file: IO[bytes],+ output_file: IO[bytes],+ override_input_file: Optional[IO[bytes]] = None,+ additional_keys: Optional[dict[str, Any]] = None,+ additional_keys_file: Optional[TextIO] = None,+ override_keys_file: Optional[TextIO] = None,+ mutations_file: Optional[TextIO] = None,+ output_format: plistlib.PlistFormat = plistlib.FMT_BINARY,+) -> None:+ root = detect_format_and_load(input_file)+ if override_input_file is not None:+ extra = detect_format_and_load(override_input_file)+ # Overriding here for backwards compatibility with v1,+ # see `PlistProcessStep::execute` implementation+ _merge_plist_dicts(source=extra, destination=root, override=True)+ if additional_keys is not None:+ _merge_plist_dicts(source=additional_keys, destination=root)+ if additional_keys_file is not None:+ additional_keys_from_file = json.load(additional_keys_file)+ _merge_plist_dicts(source=additional_keys_from_file, destination=root)+ if override_keys_file is not None:+ override_keys_from_file = json.load(override_keys_file)+ _merge_plist_dicts(+ source=override_keys_from_file, destination=root, override=True+ )++ # Apply mutations if provided+ if mutations_file is not None:+ mutations = [tuple(item) for item in json.load(mutations_file)]+ _apply_mutations(root, mutations)++ plistlib.dump(root, output_file, fmt=output_format)
@@ -0,0 +1,464 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import io+import plistlib+import unittest++from .process import _apply_insert, _apply_merge, _apply_set, process+++class TestProcess(unittest.TestCase):+ def test_canary(self):+ input_file = io.BytesIO(+ b"""<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>foo</key>+ <string>bar</string>+</dict>+</plist>+"""+ )+ output_file = io.BytesIO()+ process(input_file, output_file)+ self.assertTrue(len(output_file.getvalue()) > 0)++ def test_additional_input_given_no_keys_conflict(self):+ input_file = io.BytesIO(+ b"""<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>foo</key>+ <string>bar</string>+</dict>+</plist>+"""+ )+ override_input_file = io.BytesIO(+ b"""<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>baz</key>+ <string>qux</string>+</dict>+</plist>+"""+ )+ output_file = io.BytesIO()+ process(input_file, output_file, override_input_file)+ output_file.seek(0)+ root = plistlib.load(output_file)+ self.assertEqual(root, {"foo": "bar", "baz": "qux"})++ def test_additional_input_given_keys_conflict(self):+ input_file = io.BytesIO(+ b"""<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>foo</key>+ <string>bar</string>+ <key>qux</key>+ <dict>+ <key>a</key>+ <string>b</string>+ <key>b</key>+ <string>c</string>+ </dict>+ <key>foobar</key>+ <dict>+ <key>hello</key>+ <string>world</string>+ </dict>+</dict>+</plist>+"""+ )+ override_input_file = io.BytesIO(+ b"""<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>foo</key>+ <string>baz</string>+ <key>qux</key>+ <dict>+ <key>a</key>+ <string>z</string>+ <key>c</key>+ <string>x</string>+ </dict>+ <key>foobar</key>+ <string>zanzibar</string>+</dict>+</plist>+"""+ )+ output_file = io.BytesIO()+ process(input_file, output_file, override_input_file)+ output_file.seek(0)+ root = plistlib.load(output_file)+ self.assertEqual(+ root,+ {"foo": "baz", "qux": {"a": "z", "b": "c", "c": "x"}, "foobar": "zanzibar"},+ )++ def test_additional_keys(self):+ input_file = io.BytesIO(+ b"""<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>foo</key>+ <string>bar</string>+</dict>+</plist>+"""+ )+ additional_keys = {"baz": "qux"}+ output_file = io.BytesIO()+ process(input_file, output_file, additional_keys=additional_keys)+ output_file.seek(0)+ root = plistlib.load(output_file)+ self.assertEqual(root, {"foo": "bar", "baz": "qux"})++ def test_additional_keys_do_not_override(self):+ input_file = io.BytesIO(+ b"""<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>foo</key>+ <string>bar</string>+</dict>+</plist>+"""+ )+ additional_keys = {"foo": "baz"}+ output_file = io.BytesIO()+ process(input_file, output_file, additional_keys=additional_keys)+ output_file.seek(0)+ root = plistlib.load(output_file)+ self.assertEqual(root, {"foo": "bar"})++ def test_additional_keys_from_file(self):+ input_file = io.BytesIO(+ b"""<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>foo</key>+ <string>bar</string>+</dict>+</plist>+"""+ )+ additional_keys_file = io.BytesIO(b"""{"baz": "qux"}""")+ output_file = io.BytesIO()+ process(input_file, output_file, additional_keys_file=additional_keys_file)+ output_file.seek(0)+ root = plistlib.load(output_file)+ self.assertEqual(root, {"foo": "bar", "baz": "qux"})++ def test_override_keys_from_file(self):+ input_file = io.BytesIO(+ b"""<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>foo</key>+ <string>bar</string>+</dict>+</plist>+"""+ )+ override_keys_file = io.BytesIO(b"""{"foo": "baz"}""")+ output_file = io.BytesIO()+ process(input_file, output_file, override_keys_file=override_keys_file)+ output_file.seek(0)+ root = plistlib.load(output_file)+ self.assertEqual(root, {"foo": "baz"})++ def test_apply_set_string(self):+ """Test _apply_set with a string value."""+ plist_data = {"ExistingKey": "ExistingValue"}+ set_params = {"keypath": "TestKey", "value": "TestValue"}+ _apply_set(plist_data, set_params)+ self.assertEqual(plist_data["TestKey"], "TestValue")+ self.assertEqual(plist_data["ExistingKey"], "ExistingValue")++ def test_apply_set_integer(self):+ """Test _apply_set with an integer value."""+ plist_data = {"ExistingKey": "ExistingValue"}+ set_params = {"keypath": "TestKey", "value": 42}+ _apply_set(plist_data, set_params)+ self.assertEqual(plist_data["TestKey"], 42)+ self.assertIsInstance(plist_data["TestKey"], int)++ def test_apply_set_boolean(self):+ """Test _apply_set with a boolean value."""+ plist_data = {"ExistingKey": "ExistingValue"}+ set_params = {"keypath": "TestKey", "value": True}+ _apply_set(plist_data, set_params)+ self.assertEqual(plist_data["TestKey"], True)+ self.assertIsInstance(plist_data["TestKey"], bool)++ def test_apply_set_override(self):+ """Test _apply_set overriding an existing key."""+ plist_data = {"TestKey": "OldValue"}+ set_params = {"keypath": "TestKey", "value": "NewValue"}+ _apply_set(plist_data, set_params)+ self.assertEqual(plist_data["TestKey"], "NewValue")++ def test_apply_insert_simple(self):+ """Test _apply_insert with a simple list."""+ plist_data = {"TestList": ["existing_value"]}+ insert_params = {"keypath": "TestList", "value": "new_value"}+ _apply_insert(plist_data, insert_params)+ self.assertEqual(plist_data["TestList"], ["new_value", "existing_value"])++ def test_apply_insert_create_list(self):+ """Test _apply_insert creating a new list."""+ plist_data = {}+ insert_params = {"keypath": "NewList", "value": "new_value"}+ _apply_insert(plist_data, insert_params)+ self.assertEqual(plist_data["NewList"], ["new_value"])++ def test_apply_insert_nested(self):+ """Test _apply_insert with a nested list structure."""+ plist_data = {"CFBundleURLTypes": [{"CFBundleURLSchemes": ["existing_scheme"]}]}+ insert_params = {+ "keypath": "CFBundleURLTypes.CFBundleURLSchemes",+ "value": "new_scheme",+ }+ _apply_insert(plist_data, insert_params)+ expected = {+ "CFBundleURLTypes": [+ {"CFBundleURLSchemes": ["new_scheme", "existing_scheme"]}+ ]+ }+ self.assertEqual(plist_data, expected)++ def test_apply_insert_nested_create(self):+ """Test _apply_insert creating a nested structure."""+ plist_data = {"CFBundleURLTypes": []}+ insert_params = {+ "keypath": "CFBundleURLTypes.CFBundleURLSchemes",+ "value": "new_scheme",+ }+ _apply_insert(plist_data, insert_params)+ expected = {"CFBundleURLTypes": [{"CFBundleURLSchemes": ["new_scheme"]}]}+ self.assertEqual(plist_data, expected)++ def test_apply_insert_with_type(self):+ """Test _apply_insert with type conversion."""+ plist_data = {"NumberList": []}+ insert_params = {"keypath": "NumberList", "value": 42}+ _apply_insert(plist_data, insert_params)+ self.assertEqual(plist_data["NumberList"], [42])+ self.assertIsInstance(plist_data["NumberList"][0], int)++ def test_apply_merge(self):+ """Test _apply_merge with a temporary file."""+ import tempfile++ # Create a temporary plist file to merge+ with tempfile.NamedTemporaryFile(mode="wb", delete=False) as temp_file:+ merge_data = {+ "MergedKey": "MergedValue",+ "NestedDict": {"SubKey2": "SubValue2"},+ "MergedList": ["item1", "item2"],+ }+ plistlib.dump(merge_data, temp_file)+ temp_path = temp_file.name++ try:+ # Test merging the file+ plist_data = {+ "ExistingKey": "ExistingValue",+ "NestedDict": {+ "SubKey1": "OriginalValue",+ "ExistingSubKey": "KeepThis",+ },+ "MergedList": ["existing_item"],+ }++ _apply_merge(plist_data, temp_path)++ # Verify the results+ self.assertEqual(plist_data["MergedKey"], "MergedValue")+ self.assertEqual(plist_data["ExistingKey"], "ExistingValue")++ # Check deep merge of nested dictionary+ self.assertEqual(plist_data["NestedDict"]["SubKey1"], "OriginalValue")+ self.assertEqual(plist_data["NestedDict"]["SubKey2"], "SubValue2")+ self.assertEqual(plist_data["NestedDict"]["ExistingSubKey"], "KeepThis")++ # Check list merging+ self.assertEqual(len(plist_data["MergedList"]), 3)+ self.assertIn("item1", plist_data["MergedList"])+ self.assertIn("item2", plist_data["MergedList"])+ self.assertIn("existing_item", plist_data["MergedList"])+ finally:+ # Clean up the temporary file+ import os++ os.unlink(temp_path)++ def test_apply_merge_nonexistent_file(self):+ """Test _apply_merge with a nonexistent file (should not raise an error)."""+ plist_data = {"ExistingKey": "ExistingValue"}+ # This should not raise an exception+ _apply_merge(plist_data, "/nonexistent/file/path.plist")+ # Data should remain unchanged+ self.assertEqual(plist_data, {"ExistingKey": "ExistingValue"})++ def test_apply_merge_nested_list_of_dicts(self):+ """Test _apply_merge with a nested list of dictionaries."""+ import tempfile++ # Create a temporary plist file to merge with nested list of dicts+ with tempfile.NamedTemporaryFile(mode="wb", delete=False) as temp_file:+ merge_data = {+ "NestedListOfDicts": [+ {"SubKey1": "SubValue1", "SubKey2": "SubValue2"},+ {"SubKey3": "SubValue3"},+ ]+ }+ plistlib.dump(merge_data, temp_file)+ temp_path = temp_file.name++ try:+ # Test merging the file+ plist_data = {+ "NestedListOfDicts": [+ {"SubKey1": "OriginalValue", "UniqueKey": "KeepThis"},+ {"SubKey4": "SubValue4"},+ ]+ }++ _apply_merge(plist_data, temp_path)++ # Verify the results+ self.assertEqual(len(plist_data["NestedListOfDicts"]), 4)++ # Check that the original items are preserved+ self.assertIn(+ {"SubKey1": "OriginalValue", "UniqueKey": "KeepThis"},+ plist_data["NestedListOfDicts"],+ )+ self.assertIn({"SubKey4": "SubValue4"}, plist_data["NestedListOfDicts"])++ # Check that the new items are added+ self.assertIn(+ {"SubKey1": "SubValue1", "SubKey2": "SubValue2"},+ plist_data["NestedListOfDicts"],+ )+ self.assertIn({"SubKey3": "SubValue3"}, plist_data["NestedListOfDicts"])+ finally:+ # Clean up the temporary file+ import os++ os.unlink(temp_path)++ def test_apply_insert_complex_keypath(self):+ """Test _apply_insert with a complex keypath including array indexing."""+ # Create a non-trivial plist_data structure with nested dictionaries and arrays+ plist_data = {+ "Root": {+ "Level1": [+ {"Name": "Item0", "Values": ["a", "b", "c"]},+ {"Name": "Item1", "Values": ["d", "e", "f"]},+ {"Name": "Item2", "Values": ["g", "h", "i"]},+ {+ "Name": "Item3",+ "Values": ["j", "k", "l"],+ "Nested": {+ "Config": [+ {"Type": "Type1", "Options": ["opt1", "opt2"]},+ {"Type": "Type2", "Options": ["opt3", "opt4"]},+ ]+ },+ },+ ]+ }+ }++ # Insert a new option at a complex keypath with array indexing+ insert_params = {+ "keypath": "Root.Level1[3].Nested.Config[1].Options",+ "value": "new_option",+ }+ _apply_insert(plist_data, insert_params)++ # Verify that the value was inserted at the correct location+ expected_options = ["new_option", "opt3", "opt4"]+ self.assertEqual(+ plist_data["Root"]["Level1"][3]["Nested"]["Config"][1]["Options"],+ expected_options,+ )++ # Verify that other parts of the structure remain unchanged+ self.assertEqual(plist_data["Root"]["Level1"][0]["Name"], "Item0")+ self.assertEqual(plist_data["Root"]["Level1"][3]["Values"], ["j", "k", "l"])+ self.assertEqual(+ plist_data["Root"]["Level1"][3]["Nested"]["Config"][0]["Options"],+ ["opt1", "opt2"],+ )++ def test_apply_set_complex_keypath(self):+ """Test _apply_set with a complex keypath including array indexing."""+ # Create a non-trivial plist_data structure with nested dictionaries and arrays+ plist_data = {+ "Root": {+ "Level1": [+ {"Name": "Item0", "Values": ["a", "b", "c"]},+ {"Name": "Item1", "Values": ["d", "e", "f"]},+ {"Name": "Item2", "Values": ["g", "h", "i"]},+ {+ "Name": "Item3",+ "Values": ["j", "k", "l"],+ "Nested": {+ "Config": [+ {"Type": "Type1", "Settings": {"Enabled": False}},+ {"Type": "Type2", "Settings": {"Enabled": False}},+ ]+ },+ },+ ]+ }+ }++ # Set a value at a complex keypath with array indexing+ set_params = {+ "keypath": "Root.Level1[3].Nested.Config[0].Settings.Enabled",+ "value": True,+ }+ _apply_set(plist_data, set_params)++ # Verify that the value was set at the correct location+ self.assertEqual(+ plist_data["Root"]["Level1"][3]["Nested"]["Config"][0]["Settings"][+ "Enabled"+ ],+ True,+ )++ # Verify that other parts of the structure remain unchanged+ self.assertEqual(plist_data["Root"]["Level1"][0]["Name"], "Item0")+ self.assertEqual(plist_data["Root"]["Level1"][3]["Values"], ["j", "k", "l"])+ self.assertEqual(+ plist_data["Root"]["Level1"][3]["Nested"]["Config"][1]["Settings"][+ "Enabled"+ ],+ False,+ )
@@ -0,0 +1,113 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import argparse+import os+import shutil+import subprocess+import tempfile+from pathlib import Path++from apple.tools.re_compatibility_utils.writable import make_dir_recursively_writable+++def _copy_ipa_contents(ipa_contents_dir: Path, output_dir: Path) -> None:+ if os.path.exists(output_dir):+ shutil.rmtree(output_dir, ignore_errors=False)+ shutil.copytree(ipa_contents_dir, output_dir, symlinks=True, dirs_exist_ok=False)+++def _delete_empty_SwiftSupport_dir(output_dir: Path) -> None:+ swiftSupportDir = output_dir / "SwiftSupport"+ if not swiftSupportDir.exists():+ return++ swiftSupportDirHasFiles = False+ for _, _, files in os.walk(swiftSupportDir):+ if files:+ swiftSupportDirHasFiles = True+ break++ if not swiftSupportDirHasFiles:+ shutil.rmtree(swiftSupportDir)+++def _package_ipa_contents(+ ipa_contents_dir: Path,+ ipa_output_path: Path,+ compression_level: int,+) -> None:+ with tempfile.TemporaryDirectory() as processed_package_dir:+ processed_package_dir_path = Path(processed_package_dir)+ _copy_ipa_contents(ipa_contents_dir, processed_package_dir_path)++ # Apple requires SwiftSupport dir to be non-empty+ _delete_empty_SwiftSupport_dir(processed_package_dir_path)++ # Apple requires all executable files in an `.ipa` to be _writable_, otherwise App Store validation fails with:+ # "Asset validation failed (90711) Invalid executable permissions. The executable $X does not have its writable bit set."+ # Furthermore, there's additional internal infra that needs certain files to be writable.+ #+ # In normal development outside Meta, all files in an .ipa will be user writable, so let's just the sensible thing+ # and mirror behavior which Apple expects, so we're future-proof.+ make_dir_recursively_writable(str(processed_package_dir_path))++ with open(ipa_output_path, "wb") as ipa_file:+ zip_cmd = [+ "zip",+ "-X",+ "-n",+ "zst", # avoid deflating already compressed files+ "-r",+ f"-{compression_level}",+ "-",+ ".",+ ]+ subprocess.run(+ zip_cmd,+ # .ipa zip file requires to be created relative to the package dir,+ # zip command has no way to express apart from changing cwd+ cwd=processed_package_dir_path,+ stdout=ipa_file,+ check=True,+ )+++def main() -> None:+ parser = argparse.ArgumentParser(description="Tool to make an .ipa package file.")+ parser.add_argument(+ "--ipa-contents-dir",+ required=True,+ type=Path,+ help="The directory which has the contents of the .ipa file.",+ )+ parser.add_argument(+ "--ipa-output-path",+ required=True,+ type=Path,+ help="The path to the output .ipa file.",+ )+ parser.add_argument(+ "--compression-level",+ type=int,+ required=True,+ help="The compression level to use for 'zip'.",+ )++ args = parser.parse_args()+ _package_ipa_contents(+ args.ipa_contents_dir,+ args.ipa_output_path,+ args.compression_level,+ )+++if __name__ == "__main__":+ main()
@@ -0,0 +1,209 @@+#!/usr/bin/env python3+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import argparse+import os+import re+from io import TextIOWrapper+++_RESERVED_KEYWORDS: frozenset[str] = frozenset(+ [+ "config_macros",+ "conflict",+ "exclude",+ "explicit",+ "extern",+ "export_as",+ "export",+ "framework",+ "header",+ "link",+ "module",+ "private",+ "requires",+ "textual",+ "umbrella",+ "use",+ ]+)+++class Module:+ def __init__(self, name: str, is_framework: bool) -> None:+ self.name: str = name+ self.headers: list[str] = []+ self.submodules: dict[str, Module] = {}+ self.is_framework: bool = is_framework++ def add_header(self, src: str) -> None:+ self.headers.append(src)++ def get_submodule(self, name: str, is_framework: bool) -> "Module":+ if name not in self.submodules:+ self.submodules[name] = Module(name, is_framework)++ return self.submodules[name]++ def render(self, f: TextIOWrapper, indent: int = 0) -> None:+ space = " " * indent+ name = self.name+ if name in _RESERVED_KEYWORDS:+ name = f"{name}_"+ if self.is_framework:+ f.write(f"{space}framework module {name} {{\n")+ else:+ f.write(f"{space}module {name} {{\n")++ submodule_names = set()+ for submodule_name in sorted(self.submodules.keys()):+ submodule = self.submodules[submodule_name]++ # remove any extensions for readability+ sanitized_name = os.path.splitext(submodule_name)[0]++ # module names can only be ascii or _+ sanitized_name = re.sub(r"[^A-Za-z0-9_]", "_", sanitized_name)+ if sanitized_name[0].isdigit():+ sanitized_name = "_" + sanitized_name++ # avoid any collisions with other files+ while sanitized_name in submodule_names:+ sanitized_name += "_"++ submodule_names.add(sanitized_name)+ submodule.name = sanitized_name+ submodule.render(f, indent + 4)++ header_space = " " * (indent + 4)+ for h in sorted(self.headers):+ f.write(f'{header_space}header "{h}"\n')++ if self.headers:+ f.write(f"{header_space}export *\n")++ f.write(f"{space}}}\n")+++def _write_single_module(+ f: TextIOWrapper,+ name: str,+ headers: dict[str, str],+ is_framework: bool,+) -> None:+ module = Module(name, is_framework)+ for path in headers.values():+ module.add_header(path)++ module.render(f)+++def _write_submodules(+ f: TextIOWrapper,+ name: str,+ headers: dict[str, str],+ is_framework: bool,+) -> None:+ # Create a tree of nested modules, one for each path component.+ root_module = Module(name, is_framework)+ for include_path, disk_path in headers.items():+ module = root_module+ for i, component in enumerate(include_path.split(os.sep)):+ if i == 0 and component == name:+ # The common case is we have a single header path prefix that matches the module name.+ # In this case we add the headers directly to the root module.+ pass+ else:+ module = module.get_submodule(component, is_framework)++ module.add_header(disk_path)++ root_module.render(f)+++def _write_swift_header(f: TextIOWrapper, name: str, swift_header_path: str) -> None:+ f.write(+ f"""+module {name}.Swift {{+ header "{swift_header_path}"+ requires objc+}}+"""+ )+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument(+ "--output", required=True, help="The path to write the modulemap to"+ )+ parser.add_argument("--name", required=True, help="The name of the module")+ parser.add_argument(+ "--swift-header", help="If this is a mixed module extend with this Swift header"+ )+ parser.add_argument(+ "--use-submodules",+ action="store_true",+ help="If set produce a modulemap with per-header submodules",+ )+ parser.add_argument(+ "--framework",+ help="This modulemap is for embedding in a framework.",+ action="store_true",+ )+ parser.add_argument(+ "mappings",+ nargs="*",+ default=[],+ help="A list of tuples of include path to disk paths",+ )+ args = parser.parse_args()++ if len(args.mappings) % 2 != 0:+ raise RuntimeError(+ "Mappings must be a list of pairs of include path to disk path"+ )++ headers = {}+ for i in range(0, len(args.mappings), 2):+ path = args.mappings[i + 1]+ if args.framework:+ pass+ else:+ # We need to relativize the path to the modulemap file+ path = os.path.relpath(path, os.path.dirname(args.output))++ headers[args.mappings[i]] = path++ with open(args.output, "w") as f:+ if args.use_submodules:+ _write_submodules(+ f,+ args.name,+ headers,+ args.framework,+ )+ else:+ _write_single_module(+ f,+ args.name,+ headers,+ args.framework,+ )++ if args.swift_header:+ _write_swift_header(+ f,+ args.name,+ os.path.relpath(args.swift_header, os.path.dirname(args.output)),+ )+++if __name__ == "__main__":+ main()
@@ -0,0 +1,60 @@+#!/usr/bin/env python3+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Utility to create Swift's compilation DBs++$ make_swift_comp_db.py gen --output=entry.json foo.swift -- -I /path/ -Xcc -fno-implicit-modules+"""++import argparse+import json+import shlex+import sys+++def gen(args):+ with open(args.project_root_file, "r") as project_root_file:+ project_root = project_root_file.read().replace("\n", "")++ entry = {}+ entry["files"] = list(args.files)+ entry["directory"] = project_root++ arguments = []+ for arg in args.arguments:+ if arg.startswith("@"):+ with open(arg[1:]) as argsfile:+ for line in argsfile:+ # The argsfile's arguments are separated by newlines; we+ # don't want those included in the argument list.+ arguments.append(" ".join(shlex.split(line)))+ else:+ arguments.append(arg)+ entry["arguments"] = arguments++ json.dump([entry], args.output, indent=2)+ args.output.close()+++def main(argv):+ parser = argparse.ArgumentParser()++ parser.add_argument("--output", type=argparse.FileType("w"), default=sys.stdout)+ parser.add_argument("--files", nargs="*")+ # A path to a file that contains project root+ parser.add_argument("--project-root-file")+ parser.add_argument("arguments", nargs="*")++ args = parser.parse_args(argv[1:])++ gen(args)+++sys.exit(main(sys.argv))
@@ -0,0 +1,290 @@+#!/usr/bin/env fbpython+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Remaps swiftc arguments to be usable by swift-ide-test, and invokes+swift-ide-test with said arguments.+"""++import argparse+import dataclasses+import optparse+import pathlib+import subprocess as proc+import sys+from collections.abc import Iterable+from contextlib import contextmanager+from typing import Optional+++@dataclasses.dataclass+class SwiftIDETestArguments:+ sdk: Optional[str]+ target: Optional[str]+ xcc: Iterable[str]+ defines: Iterable[str]+ frameworks: Iterable[str]+ includes: Iterable[str]+ resource_dir: str+ enable_cxx_interop: bool+ cxx_interoperability_mode: Optional[str]+ upcoming_features: Iterable[str]+ explicit_swift_module_map: Optional[str]+ swift_version: Optional[str]++ def to_args(self) -> list[str]:+ args = []+ if self.target:+ args.append("--target")+ args.append(self.target)++ if self.sdk:+ args.append("--sdk")+ args.append(self.sdk)++ for define in self.defines:+ args.append("-D")+ args.append(define)++ for include in self.includes:+ args.append("-I")+ args.append(include)++ for framework in self.frameworks:+ args.append("-F")+ args.append(framework)++ for xcc in self.xcc:+ args.append("--Xcc")+ args.append(xcc)++ args.append("--resource-dir")+ args.append(self.resource_dir)++ if self.enable_cxx_interop:+ args.append("-enable-experimental-cxx-interop")++ if self.cxx_interoperability_mode:+ # swift-ide-test only understands -enable-experimental-cxx-interop,+ # not the versioned -cxx-interoperability-mode=.+ args.append("-enable-experimental-cxx-interop")++ if self.upcoming_features:+ for feature in self.upcoming_features:+ args.append("-enable-upcoming-feature")+ args.append(feature)++ if self.explicit_swift_module_map:+ args.append("--explicit-swift-module-map-file")+ args.append(self.explicit_swift_module_map)++ if self.swift_version:+ args.append("-swift-version")+ args.append(self.swift_version)+ return args+++class LongSingleDashOpt(optparse.Option):+ """+ This Option subclass allows for long arguments specified with single dashes,+ e.g. -sdk (the default implementation only allows long options with two+ dashes)+ """++ def _set_opt_strings(self, opts):+ for opt in opts:+ if len(opt) < 2:+ raise optparse.OptionError(+ "invalid option string %r: "+ "must be at least two characters long" % opt,+ self,+ )+ elif len(opt) == 2:+ self._short_opts.append(opt)+ else:+ self._long_opts.append(opt)+++class IgnoreUnknownLongSingleDashOptParser(optparse.OptionParser):+ """+ This OptionParser subclass allows for+ (a) long arguments specified with single dashes (e.g. -sdk)+ (b) ignoring unknown arguments+ The default OptionParser doesn't have either of these behaviors.+ """++ def __init__(self, *args, **kwargs):+ kwargs["option_class"] = LongSingleDashOpt+ super().__init__(*args, **kwargs)++ def _process_args(self, largs, rargs, values):+ while rargs:+ try:+ arg = rargs[0]+ if arg == "--":+ del rargs[0]+ return+ elif arg[0:2] == "--":+ self._process_long_opt(rargs, values)+ elif arg[:1] == "-" and len(arg) > 1:+ if len(arg) > 2:+ self._process_long_opt(rargs, values)+ else:+ self._process_short_opts(rargs, values)+ elif self.allow_interspersed_args:+ largs.append(arg)+ del rargs[0]+ else:+ return+ except optparse.BadOptionError:+ continue+++def parse_swiftc_args(arguments: list[str]) -> SwiftIDETestArguments: # noqa: C901+ """+ We can't use argparse to do our parsing because arguments like -Xcc+ need to accept arguments that are prefixed with `-`.++ optparse can handle this, and it's only soft deprecated (i.e. it should+ stay around, just not actively developed), so we should be safe to use it.++ Additionally, our subclasses above are safe, since optparse is no longer+ actively developed.+ """+ parser = IgnoreUnknownLongSingleDashOptParser()++ parser.add_option("-sdk", dest="sdk")+ parser.add_option("-target", dest="target")+ parser.add_option("-Xcc", action="append", default=[], dest="xcc")+ parser.add_option("-D", dest="defines", action="append", default=[])+ parser.add_option("-F", dest="frameworks", action="append", default=[])+ parser.add_option("-I", dest="includes", action="append", default=[])+ parser.add_option("-resource-dir", dest="resource_dir")+ parser.add_option(+ "-enable-experimental-cxx-interop",+ action="store_true",+ default=False,+ dest="enable_experimental_cxx_interop",+ )+ parser.add_option("-Xfrontend", action="append", default=[], dest="xfrontend")+ parser.add_option("-swift-version", dest="swift_version")+ parser.add_option("-cxx-interoperability-mode", dest="cxx_interoperability_mode")++ options, leftovers = parser.parse_args(arguments)++ frontend_parser = IgnoreUnknownLongSingleDashOptParser()+ frontend_parser.add_option(+ "-enable-upcoming-feature",+ dest="enable_upcoming_feature",+ action="append",+ default=[],+ )+ frontend_parser.add_option(+ "-explicit-swift-module-map-file", dest="explicit_swift_module_map"+ )+ frontend_options = frontend_parser.parse_args(options.xfrontend)[0]++ resource_dir = options.resource_dir+ if not resource_dir:+ # If an explicit resource dir was not provided, we need to figure out+ # which resource id would have been used, which, in the case of Xcode,+ # is relative to the swiftc used.+ assert len(leftovers) >= 1+ compiler_path = pathlib.Path(leftovers[0])+ assert compiler_path.name == "swiftc"+ resource_dir_path = compiler_path.parents[1] / "lib" / "swift"+ assert resource_dir_path.exists()+ resource_dir = str(resource_dir_path)++ return SwiftIDETestArguments(+ options.sdk,+ options.target,+ options.xcc,+ options.defines,+ options.frameworks,+ options.includes,+ resource_dir,+ options.enable_experimental_cxx_interop,+ options.cxx_interoperability_mode,+ frontend_options.enable_upcoming_feature,+ frontend_options.explicit_swift_module_map,+ options.swift_version,+ )+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description="Uses swift-ide-test to generate a swift interface",+ fromfile_prefix_chars="@",+ )+ parser.add_argument(+ "--swift-ide-test-tool",+ required=True,+ help="Path to swift-ide-test binary.",+ )+ parser.add_argument(+ "--module",+ required=True,+ help="Name of the module to generate the interface for.",+ )+ parser.add_argument(+ "--out",+ help="Path to output file.",+ default="-",+ )+ parser.add_argument(+ "arguments",+ nargs="*",+ default=[],+ help="File containing compiler arguments to use to invoke"+ + " swift-ide-test. Note these arguments should be in the format CC"+ + " expects, not swift-ide-test, as this tool converts the arguments"+ + " as needed",+ )+ return parser.parse_args()+++@contextmanager+def open_or_stdout(out):+ if out == "-":+ yield sys.stdout+ else:+ with open(out, "w") as f:+ yield f+++def main() -> None:+ args = parse_args()++ parsed = parse_swiftc_args(args.arguments)+ with open_or_stdout(args.out) as out:+ try:+ proc.run(+ [+ args.swift_ide_test_tool,+ "--source-filename=x",+ "--print-module",+ "--module-to-print",+ args.module,+ "--module-print-submodules",+ ]+ + parsed.to_args(),+ stdout=out,+ stderr=proc.PIPE,+ check=True,+ text=True,+ )+ except proc.CalledProcessError as exc:+ print("swift-ide-test error:", file=sys.stderr)+ sys.stderr.write(exc.stderr)+ sys.exit(exc.returncode)+++if __name__ == "__main__":+ main()
@@ -0,0 +1,96 @@+#!/usr/bin/env fbpython+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import argparse+import itertools+import json+import os+from typing import TypedDict++# Example VFS overlay in JSON format+# ----------------------------------+# {+# 'version': 0,+# 'roots': [+# { 'name': 'OUT_DIR', 'type': 'directory',+# 'contents': [+# { 'name': 'module.map', 'type': 'file',+# 'external-contents': 'INPUT_DIR/actual_module2.map'+# }+# ]+# }+# ]+# }+++class OverlayRoot(TypedDict):+ name: str+ type: str+ contents: list[dict[str, str]]+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument(+ "--output", required=True, help="The path to write the VFS overlay to"+ )+ parser.add_argument(+ "mappings", nargs="*", default=[], help="A list of virtual paths to real paths"+ )+ args = parser.parse_args()++ if len(args.mappings) % 2 != 0:+ parser.error("mappings must be dest-source pairs")++ # Group the mappings by containing directory+ mappings: dict[str, list[tuple[str, str]]] = {}+ for src, dst in itertools.zip_longest(*([iter(args.mappings)] * 2)):+ folder, basename = os.path.split(src)+ mappings.setdefault(folder, []).append((basename, dst))++ with open(args.output, "w") as f:+ json.dump(+ {+ "version": 0,+ "roots": _get_roots(mappings),+ },+ f,+ sort_keys=True,+ indent=4,+ )+ f.write("\n")+ f.flush()+++def _get_roots(mappings: dict[str, list[tuple[str, str]]]) -> list[OverlayRoot]:+ roots = []+ for folder, file_maps in mappings.items():+ contents = []+ for src, dst in file_maps:+ contents.append(+ {+ "name": src,+ "type": "file",+ "external-contents": dst,+ }+ )++ roots.append(+ {+ "name": folder,+ "type": "directory",+ "contents": contents,+ }+ )++ return roots+++if __name__ == "__main__":+ main()
@@ -0,0 +1,32 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import plistlib+from io import BytesIO+from typing import Any, IO+++def _is_fmt_binary(header: bytes) -> bool:+ return header[:8] == b"bplist00"+++def detect_format_and_load(fp: IO[bytes]) -> dict[str, Any]:+ header = fp.read(32)+ fp.seek(0)+ if _is_fmt_binary(header):+ fmt = plistlib.FMT_BINARY+ else:+ fmt = plistlib.FMT_XML+ return plistlib.load(fp, fmt=fmt)+++def detect_format_and_loads(value: bytes) -> dict[str, Any]:+ fp = BytesIO(value)+ return detect_format_and_load(fp)
@@ -0,0 +1,24 @@+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("build_infra")++source_listing()++prelude = native++prelude.python_library(+ name = "re_compatibility_utils",+ srcs = [+ "writable.py",+ ],+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_library(+ name = "bootstrap_re_compatibility_utils",+ srcs = [+ "writable.py",+ ],+ has_content_based_path = True,+ visibility = ["PUBLIC"],+)
@@ -0,0 +1,54 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import os+import pathlib+import platform+import stat+import sys+++def make_path_user_writable(path: str) -> None:+ # On Linux, `os.chmod()` does not support setting the permissions on a symlink.+ # `chmod` manpage says:+ # > AT_SYMLINK_NOFOLLOW If pathname is a symbolic link, do not+ # > dereference it: instead operate on the link itself.+ # > This flag is not currently implemented.+ #+ # In Python, an exception will be thrown:+ # > NotImplementedError: chmod: follow_symlinks unavailable on this platform+ #+ # Darwin supports permission setting on symlinks.+ follow_symlinks = platform.system() != "Darwin"+ st = os.stat(path, follow_symlinks=False)++ try:+ os.chmod(path, st.st_mode | stat.S_IWUSR, follow_symlinks=follow_symlinks)+ except FileNotFoundError as e:+ path_obj = pathlib.Path(path)+ if path_obj.is_symlink():+ resolved_path_obj = path_obj.resolve()+ if not resolved_path_obj.exists():+ # On Linux systems, all symlinks are followed when `chmod`-ing+ # (see comment above about `AT_SYMLINK_NOFOLLOW`). If that happens,+ # we can ignore the `chmod` error as its harmless.+ print(+ f"Tried setting permission on a symlink to a non-existing path, ignoring error... {e}",+ file=sys.stderr,+ )+ return+ raise e+++def make_dir_recursively_writable(dir: str) -> None:+ for dirpath, _, filenames in os.walk(dir):+ make_path_user_writable(dirpath)+ for filename in filenames:+ make_path_user_writable(os.path.join(dirpath, filename))
@@ -0,0 +1,38 @@+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("build_infra")++source_listing()++python_binary(+ name = "resource_broker",+ main = "main.py",+ visibility = ["PUBLIC"],+ deps = [+ ":main",+ ],+)++python_library(+ name = "main",+ srcs = ["main.py"],+ deps = [+ ":lib",+ ],+)++python_library(+ name = "lib",+ srcs = glob(+ [+ "*.py",+ ],+ exclude = [+ "main.py",+ ],+ ),+ deps = [+ "fbsource//third-party/pypi/dataclasses-json:dataclasses-json",+ "fbsource//third-party/pypi/packaging:packaging",+ ],+)
@@ -0,0 +1,31 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import os+import shlex+import sys++REPLAY_ENVS_TO_REMOVE = [+ "DUMP_REPLAY",+]+++def debug_dump_replay() -> None:+ if os.environ.get("DUMP_REPLAY") is None:+ return+ filtered_envs = dict(os.environ)+ for env in REPLAY_ENVS_TO_REMOVE:+ filtered_envs.pop(env, None)+ envs = " ".join(+ f"{key}={shlex.quote(value)}" for key, value in sorted(filtered_envs.items())+ )+ command = shlex.join(sys.argv)+ replay_file = "/tmp/resource_broker_replay.sh"+ with open(replay_file, "w") as f:+ f.write(f"{envs} {command}\n")+ os.chmod(replay_file, 0o755)
@@ -0,0 +1,319 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import os+from dataclasses import dataclass+from typing import Optional++from packaging.version import Version++from .simctl_runtime import list_runtimes, XCSimRuntime+from .simulator import (+ managed_simulators_list_from_stdout,+ Simulator,+ SimulatorInfo,+ SimulatorState,+ SimulatorType,+)+from .timeouts import SIMULATOR_BOOT_TIMEOUT+from .utils import execute_generic_text_producing_command+++@dataclass(frozen=True)+class SimulatorSpec:+ device: str+ os_version: str+++def _device_set_path() -> str:+ return os.path.expanduser("~/Library/Developer/Buck2IdbDeviceSet")+++def _list_managed_simulators_command(simulator_manager: str) -> list[str]:+ return [+ simulator_manager,+ "list",+ "--device-set-path",+ _device_set_path(),+ "--only",+ "simulator",+ ]+++def _create_simulator_command(simulator_manager: str, sim_spec: str) -> list[str]:+ return [+ simulator_manager,+ "create",+ "--device-set-path",+ _device_set_path(),+ "--configuration",+ sim_spec,+ ]+++def _boot_simulator_command(simulator_manager: str, udid: str) -> list[str]:+ return [+ simulator_manager,+ "boot",+ "--device-set-path",+ _device_set_path(),+ udid,+ ]+++def _compatible_device_type_from_runtime(+ runtime: XCSimRuntime, simulator_type: SimulatorType, device: Optional[str]+) -> Optional[str]:+ device_types = list(runtime.supported_device_types)+ device_types = [+ device_type+ for device_type in device_types+ if simulator_type.matches_device_identifier(device_type.identifier)+ ]+ if device:+ if device.startswith("com.apple."):+ # filter by device type identifier+ device_types = [+ device_type+ for device_type in device_types+ if device_type.identifier == device+ ]+ else:+ # filter by device name+ device_types = [+ device_type+ for device_type in device_types+ if device_type.name == device+ ]+ if not device_types:+ return None+ selected_device = next(+ (+ device_type.name+ for device_type in device_types+ if device_type.name == simulator_type.default_device()+ ),+ device_types[0].name,+ )+ return selected_device+++def _select_simulator_spec(+ runtimes: list[XCSimRuntime],+ simulator_type: SimulatorType,+ os_version: Optional[str],+ device: Optional[str],+) -> SimulatorSpec:+ runtimes = [+ runtime+ for runtime in runtimes+ if any(+ simulator_type.matches_device_identifier(device_type.identifier)+ for device_type in runtime.supported_device_types+ )+ ]+ runtimes.sort(key=lambda x: Version(x.version), reverse=True)++ if os_version:+ runtimes = [x for x in runtimes if x.name == os_version]+ for runtime in runtimes:+ device_type = _compatible_device_type_from_runtime(+ runtime=runtime, simulator_type=simulator_type, device=device+ )+ if device_type:+ return SimulatorSpec(device_type, f"{runtime.platform} {runtime.version}")+ raise RuntimeError(+ "No Xcode simctl compatible os runtime and device available. Try to `sudo xcode-select -s <path_to_xcode>` and *open Xcode to install all required components*."+ )+++async def _generic_managed_simulators_list_command(+ name: str, cmd: list[str]+) -> list[Simulator]:+ stdout = await execute_generic_text_producing_command(name=name, cmd=cmd)+ return managed_simulators_list_from_stdout(stdout)+++async def _list_managed_simulators(simulator_manager: str) -> list[Simulator]:+ list_cmd = _list_managed_simulators_command(simulator_manager=simulator_manager)+ return await _generic_managed_simulators_list_command(+ name="list managed simulators", cmd=list_cmd+ )+++def normalize_os_version(os_version: str) -> Version:+ # os version should be in the format "iOS 17.2.0" or "iOS 17.2"+ return Version(os_version.split(" ")[1])+++def choose_simulators(+ simulators: list[Simulator],+ simulator_type: SimulatorType,+ os_version: Optional[str],+ device: Optional[str],+) -> list[Simulator]:+ # If no device or os_version is specified, filter by simulator type+ if not device and not os_version:+ simulators = list(+ filter(+ lambda s: (s.is_type(simulator_type)),+ simulators,+ )+ )++ # Check if device is a device type identifier+ device_type_identifier: Optional[str] = None+ if device is not None and device.startswith("com.apple."):+ device_type_identifier = device+ device = None++ filtered_simulators = filter(+ lambda simulator: (+ (+ normalize_os_version(simulator.os_version).major+ == normalize_os_version(os_version).major+ and normalize_os_version(simulator.os_version).minor+ == normalize_os_version(os_version).minor+ if os_version+ else True+ )+ and (+ simulator.device_type_identifier == device_type_identifier+ if device_type_identifier is not None+ else True+ )+ and (simulator.name == device if device is not None else True)+ ),+ simulators,+ )++ return list(filtered_simulators)+++async def _create_simulator(+ simulator_manager: str,+ simulator_type: SimulatorType,+ os_version: Optional[str] = None,+ device: Optional[str] = None,+) -> None:+ runtimes = await list_runtimes()+ spec = _select_simulator_spec(runtimes, simulator_type, os_version, device)+ spec_str = f"{spec.device},{spec.os_version}"+ create_cmd = _create_simulator_command(+ simulator_manager=simulator_manager, sim_spec=spec_str+ )+ await execute_generic_text_producing_command(+ name="create simulators", cmd=create_cmd+ )+++async def _get_managed_simulators_create_if_needed(+ simulator_manager: str,+ simulator_type: SimulatorType,+ os_version: Optional[str] = None,+ device: Optional[str] = None,+) -> list[Simulator]:+ managed_simulators = await _get_managed_simulators(+ simulator_manager=simulator_manager,+ simulator_type=simulator_type,+ os_version=os_version,+ device=device,+ )+ if managed_simulators:+ return managed_simulators++ await _create_simulator(+ simulator_manager=simulator_manager,+ simulator_type=simulator_type,+ os_version=os_version,+ device=device,+ )+ managed_simulators = await _get_managed_simulators(+ simulator_manager=simulator_manager,+ simulator_type=simulator_type,+ os_version=os_version,+ device=device,+ )+ if managed_simulators:+ return managed_simulators++ raise RuntimeError(+ "Failed to create a simulator. Try to `sudo xcode-select -s <path_to_xcode>` and *open Xcode to install all required components*."+ )+++async def _get_managed_simulators(+ simulator_manager: str,+ simulator_type: SimulatorType,+ os_version: Optional[str] = None,+ device: Optional[str] = None,+) -> list[Simulator]:+ managed_simulators = await _list_managed_simulators(+ simulator_manager=simulator_manager+ )+ return choose_simulators(managed_simulators, simulator_type, os_version, device)+++def _select_simulator(+ only_booted: bool, all_simulators: list[Simulator]+) -> Optional[Simulator]:+ return next(+ filter(+ lambda s: s.state == SimulatorState.booted if only_booted else True,+ iter(all_simulators),+ ),+ None,+ )+++def _select_simulator_with_preference(+ prefer_booted: bool, all_simulators: list[Simulator]+) -> Simulator:+ simulator = _select_simulator(+ only_booted=prefer_booted, all_simulators=all_simulators+ )+ if not simulator and prefer_booted:+ simulator = _select_simulator(only_booted=False, all_simulators=all_simulators)+ if not simulator:+ raise RuntimeError("Expected at least unbooted simulator entity to be selected")+ return simulator+++async def prepare_simulator(+ simulator_manager: str,+ simulator_type: SimulatorType,+ os_version: Optional[str] = None,+ device: Optional[str] = None,+) -> SimulatorInfo:+ managed_simulators = await _get_managed_simulators_create_if_needed(+ simulator_manager=simulator_manager,+ simulator_type=simulator_type,+ os_version=os_version,+ device=device,+ )++ simulator = _select_simulator_with_preference(+ prefer_booted=simulator_type.booted(), all_simulators=managed_simulators+ )++ if simulator.state != SimulatorState.booted and simulator_type.booted():+ boot_cmd = _boot_simulator_command(+ simulator_manager=simulator_manager, udid=simulator.udid+ )+ await execute_generic_text_producing_command(+ name="boot simulator",+ cmd=boot_cmd,+ timeout=SIMULATOR_BOOT_TIMEOUT,+ )++ return SimulatorInfo(+ udid=simulator.udid,+ device_set_path=_device_set_path(),+ )
@@ -0,0 +1,84 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import argparse+import asyncio+import json+import sys++from .debug import debug_dump_replay+from .ios import prepare_simulator+from .simulator import SimulatorType+++def _args_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description="Utility to set up simulators which are used by buck to run tests locally."+ )+ parser.add_argument(+ "--simulator-manager",+ required=True,+ type=str,+ help="Tool to manage simulators and their lifecycle. Required.",+ )+ parser.add_argument(+ "--type",+ metavar="<TYPE>",+ type=SimulatorType,+ choices=[e.value for e in SimulatorType],+ required=True,+ help=f"""+ Type of required resources.+ Pass `{SimulatorType.iphoneUnbooted}` to get an unbooted iPhone simulator.+ Pass `{SimulatorType.iphoneBooted}` to get a booted iPhone simulator.+ Pass `{SimulatorType.ipad}` to get an iPad simulator.+ Pass `{SimulatorType.watch}` to get an Apple Watch simulator.+ """,+ )+ parser.add_argument(+ "--os_version",+ required=False,+ type=str,+ help="OS version to use for simulator",+ )+ parser.add_argument(+ "--device",+ required=False,+ type=str,+ help="Device to use for simulator",+ )+ return parser+++def main() -> None:+ debug_dump_replay()+ args = _args_parser().parse_args()+ device = args.device if args.device else args.type.default_device()+ sim = asyncio.run(+ prepare_simulator(+ simulator_manager=args.simulator_manager,+ simulator_type=args.type,+ os_version=args.os_version,+ device=device,+ )+ )+ result = {+ "resources": [+ {+ "udid": sim.udid,+ "device_set_path": sim.device_set_path,+ }+ ]+ }+ json.dump(result, sys.stdout)+++if __name__ == "__main__":+ main()
@@ -0,0 +1,68 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import json+from dataclasses import dataclass, field+from typing import Optional++from dataclasses_json import config, dataclass_json++from .utils import execute_generic_text_producing_command+++@dataclass_json+@dataclass+class XCSimDevice:+ name: str+ identifier: str+ product_family: str = field(metadata=config(field_name="productFamily"))+++@dataclass_json+@dataclass+class XCSimRuntime:+ name: str+ platform: str+ version: str+ supported_device_types: list[XCSimDevice] = field(+ metadata=config(field_name="supportedDeviceTypes")+ )+++@dataclass_json+@dataclass+class _XCSimRuntimes:+ runtimes: list[XCSimRuntime]+++def _list_runtimes_command() -> list[str]:+ return [+ "xcrun",+ "simctl",+ "list",+ "runtimes",+ "available",+ "--json",+ ]+++def _simctl_runtimes_from_stdout(stdout: Optional[str]) -> list[XCSimRuntime]:+ if not stdout:+ return []+ data = json.loads(stdout)+ # pyre-ignore[16]: `from_dict` is dynamically provided by `dataclass_json`+ return _XCSimRuntimes.from_dict(data).runtimes+++async def list_runtimes() -> list[XCSimRuntime]:+ stdout = await execute_generic_text_producing_command(+ name="list runtimes", cmd=_list_runtimes_command()+ )+ return _simctl_runtimes_from_stdout(stdout)
@@ -0,0 +1,96 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import json+from dataclasses import dataclass+from enum import Enum+from typing import Optional++from dataclasses_json import dataclass_json+++class SimulatorState(str, Enum):+ booted = "Booted"+ booting = "Booting"+ creating = "Creating"+ shutdown = "Shutdown"+ shutting_down = "Shutting Down"+ unknown = "Unknown"+++class SimulatorType(str, Enum):+ iphoneUnbooted = "iphone_unbooted_simulator"+ iphoneBooted = "iphone_booted_simulator"+ ipad = "ipad_simulator"+ watch = "watch_simulator"++ def booted(self) -> bool:+ return self in (+ SimulatorType.iphoneBooted,+ SimulatorType.ipad,+ SimulatorType.watch,+ )++ def default_device(self) -> str:+ return {+ SimulatorType.iphoneUnbooted: "iPhone 11",+ SimulatorType.iphoneBooted: "iPhone 11",+ SimulatorType.ipad: "iPad (A16)",+ SimulatorType.watch: "Apple Watch Series 10 (46mm)",+ }[self]++ def matches_device_identifier(self, identifier: str) -> bool:+ identifier_prefix = {+ SimulatorType.iphoneUnbooted: "iPhone",+ SimulatorType.iphoneBooted: "iPhone",+ SimulatorType.ipad: "iPad",+ SimulatorType.watch: "Apple-Watch",+ }[self]+ return identifier_prefix in identifier+++@dataclass_json+@dataclass+class Simulator:+ name: str = ""+ device_type_identifier: str = ""+ os_version: str = ""+ udid: str = ""+ state: SimulatorState = SimulatorState.shutdown++ def is_type(self, simulator_type: SimulatorType) -> bool:+ return simulator_type.matches_device_identifier(self.device_type_identifier)++ def is_valid(self):+ return self.os_version != "" and self.udid != ""+++@dataclass+class SimulatorInfo:+ udid: str+ device_set_path: str+++def managed_simulator_from_stdout(stdout: Optional[str]) -> Simulator:+ if not stdout:+ return None+ # pyre-ignore[16]: `from_dict` is dynamically provided by `dataclass_json`+ return Simulator.from_dict(json.loads(stdout))+++def managed_simulators_list_from_stdout(stdout: Optional[str]) -> list[Simulator]:+ if not stdout:+ return []+ targets = map(+ # pyre-ignore[16]: `from_dict` is dynamically provided by `dataclass_json`+ Simulator.from_dict,+ json.loads(stdout),+ )+ return list(filter(lambda target: target.is_valid(), targets))
@@ -0,0 +1,15 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++DEFAULT_OPERATION_TIMEOUT = 10++# Simulator boot is an expensive command and can take a long time to complete+# depending on machine configuration and current machine load.+SIMULATOR_BOOT_TIMEOUT = 90
@@ -0,0 +1,46 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import asyncio+import json+import shlex++from .timeouts import DEFAULT_OPERATION_TIMEOUT+++async def _read_until_valid_json(stream: asyncio.StreamReader) -> object:+ buffer = b""+ while True:+ data = await stream.readuntil(b"}")+ buffer += data+ try:+ return json.loads(buffer.decode())+ except json.JSONDecodeError:+ pass+ raise RuntimeError(+ "Should not be reachable since either the valid JSON is there or `asyncio.IncompleteReadError` is raised."+ )+++async def execute_generic_text_producing_command(+ name: str, cmd: list[str], timeout: float = DEFAULT_OPERATION_TIMEOUT+) -> str:+ process = await asyncio.create_subprocess_exec(+ *cmd,+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)+ if process.returncode != 0:+ raise RuntimeError(+ f"Failed to {name} with command:\n```\n{shlex.join(cmd)}\n```\nstdout:\n```\n{stdout.decode(errors='ignore')}\n```\nstdout:\n```\n{stderr.decode(errors='ignore')}\n```\n"+ )+ return stdout.decode()
@@ -0,0 +1,44 @@+load("@prelude//apple/tools:defs.bzl", "meta_python_test")+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("build_infra")++source_listing()++python_library(+ name = "lib",+ srcs = [+ "macho.py",+ "macho_parser.py",+ "scrubber.py",+ "spec.py",+ "utils.py",+ ],+ deps = [+ "prelude//apple/tools/re_compatibility_utils:re_compatibility_utils",+ ],+)++python_binary(+ name = "tool",+ main = "main.py",+ visibility = ["PUBLIC"],+ deps = [+ ":lib",+ ],+)++meta_python_test(+ name = "tests",+ srcs = [+ "scrubber_test.py",+ "spec_test.py",+ ],+ resources = glob([+ "test_resources/*",+ ]),+ deps = [+ "fbsource//third-party/pypi/importlib-resources:importlib-resources",+ ":lib",+ ],+)
@@ -0,0 +1,84 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++from dataclasses import dataclass++MH_MAGIC = 0xFEEDFACE+MH_CIGAM = 0xCEFAEDFE+MH_MAGIC_64 = 0xFEEDFACF+MH_CIGAM_64 = 0xCFFAEDFE++LC_CODE_SIGNATURE = 0x1D+LC_SEGMENT_64 = 0x19+LC_SYMTAB = 0x02++N_OSO = 0x66+++class MachO:+ def __str__(self) -> str:+ props = {}+ for k, v in self.__dict__.items():+ props[k] = hex(v)+ return str(props)+++@dataclass+class MachOHeader(MachO):+ magic: int+ cpu_type: int+ cpu_subtype: int+ file_type: int+ n_cmds: int+ size_of_cmds: int+ flags: int+ reserved: int++ @property+ def is_valid(self) -> bool:+ return self.magic in (MH_CIGAM_64, MH_MAGIC_64)+++@dataclass+class LoadCommand(MachO):+ cmd: int+ cmd_size: int+++@dataclass+class LinkEditCommand(LoadCommand):+ segment_name: bytes+ VM_addr: int+ VM_size: int+ file_offset: int+ file_size: int+ maximum_VM_protection: int+ initial_VM_protection: int+ n_sections: int+ flags: int+++@dataclass+class SymtabCommand(LoadCommand):+ cmd: int+ cmd_size: int+ symtab_offset: int+ n_symbols: int+ strtab_offset: int+ strtab_size: int+++@dataclass+class Symbol(MachO):+ strtab_index: int+ sym_type: int+ section_index: int+ desc: int+ value: int
@@ -0,0 +1,136 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import struct+import sys+from typing import BinaryIO, Optional++from .macho import (+ LC_CODE_SIGNATURE,+ LC_SEGMENT_64,+ LC_SYMTAB,+ LinkEditCommand,+ MachOHeader,+ N_OSO,+ Symbol,+ SymtabCommand,+)++"""+// Each LC_SYMTAB entry consists of the following fields:+// - String Index: 4 bytes, offset into the string table (I == unsigned int)+// - Type: 1 byte (B == unsigned char)+// - Section: 1 byte, (B == unsigned char)+// - Description: 2 bytes (H == unsigned short)+// - Value: 8 bytes on 64bit, 4 bytes on 32bit (Q == unsigned long long)+// - Everything is little-endian representation (denoted by <)+"""+_LC_SYMTAB_STRUCT = struct.Struct("<IBBHQ")+++def _read_bytes(f: BinaryIO, n_bytes: int) -> int:+ b = f.read(n_bytes)+ return int.from_bytes(b, "little")+++def load_header(f: BinaryIO, offset: int) -> tuple[MachOHeader, int]:+ f.seek(offset)+ magic = _read_bytes(f, 4)+ cpu_type = _read_bytes(f, 4)+ cpu_sub_type = _read_bytes(f, 4)+ file_type = _read_bytes(f, 4)+ cmd_cnt = _read_bytes(f, 4)+ cmd_size = _read_bytes(f, 4)+ flags = _read_bytes(f, 4)+ reserved = _read_bytes(f, 4)+ header = MachOHeader(+ magic, cpu_type, cpu_sub_type, file_type, cmd_cnt, cmd_size, flags, reserved+ )+ return header, f.tell()+++def load_commands(+ f: BinaryIO, offset: int, n_cmds: int+) -> tuple[Optional[LinkEditCommand], Optional[SymtabCommand]]:+ """+ The OSO entries are identified in segments named __LINKEDIT.+ If no segment is found with that name, there is nothing to scrub.+ """+ lc_linkedit = None+ lc_symtab = None+ f.seek(offset)+ for _ in range(n_cmds):+ pos = f.tell()+ cmd = _read_bytes(f, 4)+ size = _read_bytes(f, 4)+ if cmd == LC_SEGMENT_64:+ name = f.read(16)+ if "LINKEDIT" in name.decode():+ vm_addr = _read_bytes(f, 8)+ vm_size = _read_bytes(f, 8)+ file_offset = _read_bytes(f, 8)+ file_size = _read_bytes(f, 8)+ maximum_vm_protection = _read_bytes(f, 4)+ initial_vm_protection = _read_bytes(f, 4)+ sections = _read_bytes(f, 4)+ flags = _read_bytes(f, 4)+ lc_linkedit = LinkEditCommand(+ cmd,+ size,+ name,+ vm_addr,+ vm_size,+ file_offset,+ file_size,+ maximum_vm_protection,+ initial_vm_protection,+ sections,+ flags,+ )+ continue+ elif cmd == LC_SYMTAB:+ symtab_offset = _read_bytes(f, 4)+ n_symbols = _read_bytes(f, 4)+ strtab_offset = _read_bytes(f, 4)+ strtab_size = _read_bytes(f, 4)+ lc_symtab = SymtabCommand(+ cmd, size, symtab_offset, n_symbols, strtab_offset, strtab_size+ )+ continue+ elif cmd == LC_CODE_SIGNATURE:+ print("[Focused Debugging][Warning] Code signature found.", file=sys.stderr)++ f.seek(pos)+ f.seek(size, 1)+ return lc_linkedit, lc_symtab+++def load_debug_symbols(f: BinaryIO, offset: int, n_symbol: int) -> list[Symbol]:+ """+ // Each LC_SYMTAB entry consists of the following fields:+ // - String Index: 4 bytes (offset into the string table)+ // - Type: 1 byte+ // - Section: 1 byte+ // - Description: 2 bytes+ // - Value: 8 bytes on 64bit, 4 bytes on 32bit+ """+ f.seek(offset)+ data = f.read(n_symbol * _LC_SYMTAB_STRUCT.size)+ return [+ Symbol(strtab_index, sym_type, section_idx, desc, value)+ for (+ strtab_index,+ sym_type,+ section_idx,+ desc,+ value,+ ) in _LC_SYMTAB_STRUCT.iter_unpack(data)+ if sym_type == N_OSO+ ]
@@ -0,0 +1,65 @@+#!/usr/bin/env fbpython+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import argparse+import sys++from .scrubber import scrub+++def _parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description="Tool to postprocess executables/dylibs."+ )+ parser.add_argument(+ "--input",+ required=True,+ help="Path to the input which is an executable/dylib file.",+ )+ parser.add_argument("--output", required=True, help="Path to the output file.")+ group = parser.add_mutually_exclusive_group(required=True)+ group.add_argument(+ "--targets-file",+ help="Path to a json file which contains user-focused Buck targets",+ )+ group.add_argument(+ "--spec-file",+ help="Path to a json file which contains user-focused include/exclude specs",+ )+ parser.add_argument(+ "--adhoc-codesign-tool",+ help="An adhoc codesign tool to use to re-sign the executables/dylibs, if provided.",+ )+ parser.add_argument(+ "--persisted-targets-file",+ help="A JSON file with additional targets that must be preserved by the scrubber.",+ )+ return parser.parse_args()+++def main() -> None:+ args = _parse_args()+ try:+ scrub(+ input_file=args.input,+ output_file=args.output,+ persisted_targets_file=args.persisted_targets_file,+ targets_file=args.targets_file,+ spec_file=args.spec_file,+ adhoc_codesign_tool=args.adhoc_codesign_tool,+ )+ except Exception as e:+ print(f"Focused debugging failed: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()
@@ -0,0 +1,250 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import json+import os+import shutil+import subprocess+from collections.abc import Callable+from typing import BinaryIO, Optional++from apple.tools.re_compatibility_utils.writable import make_path_user_writable++from .macho import Symbol+from .macho_parser import load_commands, load_debug_symbols, load_header+from .spec import Spec+from .utils import MachOException+++FAKE_PATH = b"fake/path"+# buck-out/isolation_dir/gen/project_cell/{hash}/....+NUM_OF_COMPONENTS_IN_BUCK2_OUTPUT_PATH_BEFORE_PROJECT_PATH = 5+# buck-out/isolation_dir/gen/project_cell//X/Y/__name__/{hash}/....+NUM_OF_COMPONENTS_IN_BUCK2_OUTPUT_PATH_BEFORE_PROJECT_PATH_WITH_CONTENT_BASED_PATH = 4+++def _always_scrub(_: str) -> bool:+ return True+++# Visible for testing+def load_focused_targets_output_paths(json_file_path: str) -> set[str]:+ if json_file_path is None or not os.path.exists(json_file_path):+ return set()+ with open(json_file_path) as f:+ content = f.read()+ if not content:+ return set()+ data = json.loads(content)+ output_paths = set()+ for target in data["targets"]:+ _, package_and_name = target.split("//")+ package, name = package_and_name.split(":")+ # This assumes the output path created by buck2, which if+ # modified, would break this logic.+ output_directory = f"{package}/__{name}__"+ output_paths.add(output_directory)+ return output_paths+++# This function converts buck-out/isolation_dir/gen/project_cell/{hash}/X/Y/__name__/libFoo.a+# into X/Y/__name__ to match the focus target output path created by load_focused_targets_output_paths+# Visible for testing+def _get_target_output_path_from_debug_file_path(+ debug_target_path: str,+) -> str:+ # This function assumes the debug file path created by buck2 in one of the following formats:+ # Without content based path:+ # buck-out/isolation_dir/gen/project_cell/{hash}/.../__name__/libFoo.a+ # buck-out/isolation_dir/gen/project_cell/{hash}/.../__name__/__objects__/bar.o+ # buck-out/isolation_dir/gen/project_cell/{hash}/.../__name__/swift_object_file.swift.o+ # With content based path:+ # buck-out/isolation_dir/gen/project_cell/.../__name__/{hash}/libFoo.a+ # buck-out/isolation_dir/gen/project_cell/.../__name__/__objects__/{hash}/bar.o+ # buck-out/isolation_dir/gen/project_cell/.../__name__/{hash}/swift_object_file.swift.o+ parts = debug_target_path.split("/")++ # We are doing the traverse in reverse order because this way we'll find the first+ # target directory sooner. _should_scrub can get called many times, so it's+ # important that we make it as efficient as possible.+ i = 1+ while i <= len(parts):+ # We are looking for the path component that matches __name__ in the examples above, and if we don't explicitly skip __objects__, we'll get the wrong path+ if (+ parts[-i].startswith("__")+ and parts[-i].endswith("__")+ and parts[-i] != "__objects__"+ ):+ break+ i += 1+ if i > len(parts):+ raise Exception(+ f"Unrecognized format for debug file path : {debug_target_path}"+ )++ # This handles the two cases, one with content based path, and one without+ return "/".join(+ parts[NUM_OF_COMPONENTS_IN_BUCK2_OUTPUT_PATH_BEFORE_PROJECT_PATH : -i + 1]+ ), "/".join(+ parts[+ NUM_OF_COMPONENTS_IN_BUCK2_OUTPUT_PATH_BEFORE_PROJECT_PATH_WITH_CONTENT_BASED_PATH : -i+ + 1+ ]+ )+++# Visible for testing+def should_scrub_with_focused_targets_output_paths(+ focused_targets_output_paths: set[str], debug_file_path: str+) -> bool:+ # All paths to be scrubbed when no focused target is specified+ if len(focused_targets_output_paths) == 0:+ return True++ # debug_file_path usually have the format x/y/z/libFoo.a(bar.m.o)+ if "(" in debug_file_path:+ debug_target_path = debug_file_path.split("(")[0]+ else:+ debug_target_path = debug_file_path++ if debug_file_path.startswith("buck-out/"):+ target_output_path, target_output_content_based_path = (+ _get_target_output_path_from_debug_file_path(debug_target_path)+ )+ return (+ target_output_path not in focused_targets_output_paths+ and target_output_content_based_path not in focused_targets_output_paths+ )+ else:+ # occasionally archive file can be directly from source.+ (package, name) = os.path.split(debug_file_path)+ while package != "" and package != "/":+ if f"{package}/__{name}__" in focused_targets_output_paths:+ return False+ (package, name) = os.path.split(package)++ return True+++def _should_scrub_with_targets_file(+ json_file_path: str, additional_labels: set[str]+) -> Callable[[str], bool]:+ focused_targets_output_paths = load_focused_targets_output_paths(json_file_path)+ return lambda debug_file_path: should_scrub_with_focused_targets_output_paths(+ focused_targets_output_paths.union(additional_labels), debug_file_path+ )+++def _should_scrub_with_spec_file(+ json_file_path: str, additional_labels: set[str]+) -> Callable[[str], bool]:+ spec = Spec(json_file_path)+ return lambda debug_file_path: should_scrub_with_focused_targets_output_paths(+ additional_labels, debug_file_path+ ) and spec.scrub_debug_file_path(debug_file_path)+++def _scrub(+ f: BinaryIO,+ strtab_offset: int,+ symbols: list[Symbol],+ scrub_handler: Callable[[str], bool],+) -> list[tuple[str, str]]:+ """+ Return a list of tuples.+ Each tuple contains a pair of the original path and the rewritten path+ """+ results = []+ for symbol in symbols:+ f.seek(strtab_offset)+ f.seek(symbol.strtab_index, 1)++ # Read a byte at a time until we reach the end of the path, denoted by Hex 0.+ start = end = f.tell()+ path = b""+ b = f.read(1)+ while b != b"\x00":+ path += b+ end += 1+ b = f.read(1)+ str_len = end - start++ path_str = path.decode()+ if scrub_handler(path_str):+ f.seek(start)+ # We don't want to modify the length of the path, so pad the replacement+ # path with spaces+ buffer = FAKE_PATH + b" " * (str_len - len(FAKE_PATH))+ f.write(buffer)+ results.append((path_str, buffer.decode()))+ else:+ results.append((path_str, path_str))+ return results+++def scrub(+ input_file: str,+ output_file: str,+ persisted_targets_file: str,+ targets_file: Optional[str] = None,+ spec_file: Optional[str] = None,+ adhoc_codesign_tool: Optional[str] = None,+) -> list[tuple[str, str]]:+ additional_labels = load_focused_targets_output_paths(persisted_targets_file)+ if targets_file and spec_file:+ raise Exception(+ "Only one of a targets file or spec file is supported, not both!"+ )+ elif targets_file:+ scrub_handler = _should_scrub_with_targets_file(targets_file, additional_labels)+ elif spec_file:+ scrub_handler = _should_scrub_with_spec_file(spec_file, additional_labels)+ else:+ scrub_handler = _always_scrub++ shutil.copy2(input_file, output_file)+ # Make it RE-compatible+ make_path_user_writable(output_file)++ results = []+ with open(output_file, "r+b") as f:+ header, offset = load_header(f, 0)+ if not header.is_valid:+ raise MachOException("Invalid macho format!")+ lc_linkedit, lc_symtab = load_commands(f, offset, header.n_cmds)+ if lc_linkedit is None:+ return []+ if lc_symtab is None:+ raise MachOException("LC_SYMTAB command not found")+ if lc_symtab.strtab_size == 0 or lc_symtab.n_symbols == 0:+ return []+ if lc_linkedit.file_size == 0:+ raise MachOException("LC_SEGMENT_64 command for string table not found")+ f.seek(lc_symtab.strtab_offset)+ """+ ld64 deliberately burns the first byte with the space character, so that zero is never a+ valid string index and writes 0x00 at offset 1, so that it's always the empty string.+ The code for this in ld64 is in LinkEditClassic.hpp (StringPoolAtom::StringPoolAtom).+ """+ if f.read(1) != b"\x20":+ raise MachOException("First character in the string table is not a space")+ if f.read(1) != b"\x00":+ raise MachOException("Second character in the string table is not a NUL")++ symbols = load_debug_symbols(f, lc_symtab.symtab_offset, lc_symtab.n_symbols)+ results = _scrub(f, lc_symtab.strtab_offset, symbols, scrub_handler)++ if adhoc_codesign_tool:+ subprocess.run(+ [adhoc_codesign_tool, "--binary", output_file],+ check=True,+ )++ return results
@@ -0,0 +1,330 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import pathlib+import unittest+from tempfile import NamedTemporaryFile+from typing import Optional+from unittest.mock import call, patch++import importlib_resources as resources++from .scrubber import (+ load_focused_targets_output_paths,+ scrub,+ should_scrub_with_focused_targets_output_paths,+)++FAKE_PATH = "fake/path"+++class Test(unittest.TestCase):+ def test_no_focused_targets(self):+ results, _ = _get_scrubber_results(targets_json_file_path=None)+ for _, rewrite_path in results:+ # We expect all paths to be scrubbed+ self.assertEqual(rewrite_path.strip(), FAKE_PATH)++ def test_empty_focused_targets(self):+ results, _ = _get_scrubber_results(+ targets_json_file_path="focused_targets_empty.json"+ )+ for _, rewrite_path in results:+ # We expect all paths to be scrubbed+ self.assertEqual(rewrite_path.strip(), FAKE_PATH)++ def test_focused_targets(self):+ with resources.as_file(+ _get_test_resource_file("focused_targets.json")+ ) as targets_json_file:+ output_paths = load_focused_targets_output_paths(str(targets_json_file))++ results, _ = _get_scrubber_results(+ targets_json_file_path="focused_targets.json"+ )++ focused_paths = []+ scrubbed_paths = []++ for orig_path, rewrite_path in results:+ for output_path in output_paths:+ if output_path in orig_path:+ # Ensure we didn't scrub the path+ focused_paths.append(orig_path)+ self.assertEqual(orig_path, rewrite_path)+ else:+ # Ensure we scrubbed the path+ scrubbed_paths.append(orig_path)+ self.assertEqual(rewrite_path.strip(), FAKE_PATH)++ self.assertEqual(+ focused_paths,+ [+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__Foo__/libFoo.a(Foo.mm.o)",+ ],+ )+ self.assertEqual(+ scrubbed_paths,+ [+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/AppDelegate.m.o",+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/RootViewController.m.o",+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/main.m.o",+ ],+ )++ def test_spec_targets(self):+ focused_paths, scrubbed_paths = _get_focused_and_scrubbed_paths(+ spec_json_file_path="focused_spec.json"+ )++ self.assertEqual(+ focused_paths,+ [+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__Foo__/libFoo.a(Foo.mm.o)",+ ],+ )+ self.assertEqual(+ scrubbed_paths,+ [+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/AppDelegate.m.o",+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/RootViewController.m.o",+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/main.m.o",+ ],+ )++ @patch("subprocess.run")+ def test_codesigning(self, subprocess):+ subprocess.return_value = [0, 0]+ results, output_file = _get_scrubber_results(+ spec_json_file_path="focused_spec.json",+ adhoc_codesign_tool="/usr/fake/codesign",+ )+ expected_calls = [+ call(+ [+ "/usr/fake/codesign",+ "--binary",+ output_file,+ ],+ check=True,+ ),+ ]+ subprocess.assert_has_calls(expected_calls)++ def test_load_focused_targets_output_paths(self):+ with resources.as_file(+ _get_test_resource_file("focused_targets.json")+ ) as targets_json_file:+ output_paths = load_focused_targets_output_paths(str(targets_json_file))++ self.assertEqual(+ output_paths, {"fbobjc/buck2/samples/focused_debugging/__Foo__"}+ )++ def test_spec_targets_regex_all(self):+ focused_paths, scrubbed_paths = _get_focused_and_scrubbed_paths(+ spec_json_file_path="focused_spec_regex_all.json"+ )+ self.assertEqual(+ focused_paths,+ [+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/AppDelegate.m.o",+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/RootViewController.m.o",+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/main.m.o",+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__Foo__/libFoo.a(Foo.mm.o)",+ ],+ )+ self.assertEqual(+ scrubbed_paths,+ [],+ )++ def test_spec_targets_regex_none(self):+ focused_paths, scrubbed_paths = _get_focused_and_scrubbed_paths(+ spec_json_file_path="focused_spec_regex_none.json"+ )++ self.assertEqual(+ focused_paths,+ [],+ )+ self.assertEqual(+ scrubbed_paths,+ [+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/AppDelegate.m.o",+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/RootViewController.m.o",+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/main.m.o",+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__Foo__/libFoo.a(Foo.mm.o)",+ ],+ )++ def test_should_scrub_with_focused_targets_output_paths(self):+ focused_targets_output_paths = {+ "fbobjc/some/path/__foo__",+ "xplat/some/path/__foo__",+ }+ self.assertEqual(+ True,+ should_scrub_with_focused_targets_output_paths(+ focused_targets_output_paths,+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/some/path/__baz__/libbar.a(baz.mm.o)",+ ),+ )+ self.assertEqual(+ True,+ should_scrub_with_focused_targets_output_paths(+ focused_targets_output_paths,+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/some/path/__baz__/__objects__/baz.mm.o",+ ),+ )+ self.assertEqual(+ True,+ should_scrub_with_focused_targets_output_paths(+ focused_targets_output_paths,+ "buck-out/v2/gen/fbsource/fbobjc/some/path/__baz__/__objects__/56628b5feecfab0a/baz.mm.o",+ ),+ )+ self.assertEqual(+ False,+ should_scrub_with_focused_targets_output_paths(+ focused_targets_output_paths,+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/some/path/__foo__/libbar.a(baz.mm.o)",+ ),+ )+ self.assertEqual(+ False,+ should_scrub_with_focused_targets_output_paths(+ focused_targets_output_paths,+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/some/path/__foo__/__objects__/baz.mm.o",+ ),+ )+ self.assertEqual(+ False,+ should_scrub_with_focused_targets_output_paths(+ focused_targets_output_paths,+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/some/path/__foo__/lib.a",+ ),+ )+ self.assertEqual(+ False,+ should_scrub_with_focused_targets_output_paths(+ focused_targets_output_paths,+ "buck-out/v2/gen/fbsource/fbobjc/some/path/__foo__/56628b5feecfab0a/lib.a",+ ),+ )+ self.assertEqual(+ False,+ should_scrub_with_focused_targets_output_paths(+ focused_targets_output_paths,+ "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/some/path/__foo__/__objects__/bar.o",+ ),+ )+ self.assertEqual(+ False,+ should_scrub_with_focused_targets_output_paths(+ focused_targets_output_paths,+ "xplat/some/path/foo/lib/prebuilt_lib.a(baz.m.o)",+ ),+ )+ self.assertEqual(+ True,+ should_scrub_with_focused_targets_output_paths(+ focused_targets_output_paths,+ "xplat/some/path/fooo/prebuilt_lib.a(baz.m.o)",+ ),+ )+ self.assertEqual(+ True,+ should_scrub_with_focused_targets_output_paths(+ focused_targets_output_paths,+ "/tmp/lto.tmp",+ ),+ )+ self.assertEqual(+ True,+ should_scrub_with_focused_targets_output_paths(+ focused_targets_output_paths,+ "/",+ ),+ )+++def _get_focused_and_scrubbed_paths(+ targets_json_file_path: Optional[str] = None,+ spec_json_file_path: Optional[str] = None,+ adhoc_codesign_tool: Optional[str] = None,+) -> (list[str], list[str]):+ results, _ = _get_scrubber_results(+ targets_json_file_path=targets_json_file_path,+ spec_json_file_path=spec_json_file_path,+ adhoc_codesign_tool=adhoc_codesign_tool,+ )++ focused_paths = []+ scrubbed_paths = []++ for orig_path, rewrite_path in results:+ if rewrite_path.strip() == FAKE_PATH:+ scrubbed_paths.append(orig_path)+ elif orig_path == rewrite_path:+ focused_paths.append(orig_path)+ else:+ raise Exception(+ f"Rewrite path is neither the fake path nor the original path: {rewrite_path}"+ )++ return (focused_paths, scrubbed_paths)+++@patch(+ "apple.tools.selective_debugging.scrubber.make_path_user_writable",+ return_value=None,+)+def _get_scrubber_results(+ make_path_user_writable_mock,+ targets_json_file_path: Optional[str] = None,+ spec_json_file_path: Optional[str] = None,+ adhoc_codesign_tool: Optional[str] = None,+) -> tuple[list[tuple[str, str]], str]:+ with resources.as_file(_get_test_resource_file("HelloWorld")) as test_binary_file:+ with NamedTemporaryFile() as out_file:+ if targets_json_file_path:+ with resources.as_file(+ _get_test_resource_file(targets_json_file_path)+ ) as targets_json_file:+ return (+ scrub(+ str(test_binary_file),+ out_file.name,+ None,+ targets_file=str(targets_json_file),+ adhoc_codesign_tool=adhoc_codesign_tool,+ ),+ out_file.name,+ )+ elif spec_json_file_path:+ with resources.as_file(+ _get_test_resource_file(spec_json_file_path),+ ) as spec_json_file:+ return (+ scrub(+ str(test_binary_file),+ out_file.name,+ None,+ spec_file=str(spec_json_file),+ adhoc_codesign_tool=adhoc_codesign_tool,+ ),+ out_file.name,+ )+ else:+ return scrub(str(test_binary_file), out_file.name, None), out_file.name+++def _get_test_resource_file(name) -> pathlib.Path:+ path = resources.files(__package__).joinpath(f"test_resources/{name}")+ return path
@@ -0,0 +1,115 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import json+import re+from dataclasses import dataclass, field+++@dataclass+class BuildTargetPatternOutputPathMatcher:+ pattern: str+ output_path: str = field(init=False)++ def __post_init__(self) -> None:+ _, package_and_name = self.pattern.split("//")+ if package_and_name.endswith("..."):+ # recursive pattern+ output_path, _ = package_and_name.split("...")+ elif package_and_name.endswith(":"):+ # package pattern+ package, _ = package_and_name.split(":")+ # This assumes the output path created by buck2, which if+ # modified, would break this logic.+ output_path = f"{package}/__"+ else:+ # target pattern+ package, name = package_and_name.split(":")+ # This assumes the output path created by buck2, which if+ # modified, would break this logic.+ output_path = f"{package}/__{name}__"++ self.output_path = output_path++ def match_path(self, debug_file_path: str) -> bool:+ return self.output_path in debug_file_path+++@dataclass+class Spec:+ spec_path: str+ include_build_target_patterns: list[BuildTargetPatternOutputPathMatcher] = field(+ init=False+ )+ include_regular_expressions: list[re.Pattern[str]] = field(init=False)+ exclude_build_target_patterns: list[BuildTargetPatternOutputPathMatcher] = field(+ init=False+ )+ exclude_regular_expressions: list[re.Pattern[str]] = field(init=False)++ def __post_init__(self) -> None:+ with open(self.spec_path) as f:+ data = json.load(f)++ self.include_build_target_patterns = [+ BuildTargetPatternOutputPathMatcher(entry)+ for entry in data["include_build_target_patterns"]+ ]+ self.include_regular_expressions = [+ re.compile(_sanitize_regex_pattern(entry))+ for entry in data["include_regular_expressions"]+ ]+ self.exclude_build_target_patterns = [+ BuildTargetPatternOutputPathMatcher(entry)+ for entry in data["exclude_build_target_patterns"]+ ]+ self.exclude_regular_expressions = [+ re.compile(_sanitize_regex_pattern(entry))+ for entry in data["exclude_regular_expressions"]+ ]++ def scrub_debug_file_path(self, debug_file_path: str) -> bool:+ if self.include_build_target_patterns or self.include_regular_expressions:+ is_included = _path_matches_pattern_or_expression(+ debug_file_path,+ self.include_build_target_patterns,+ self.include_regular_expressions,+ )+ else:+ is_included = True++ # If the path is included (and not excluded), do not scrub+ return not (+ is_included+ and not _path_matches_pattern_or_expression(+ debug_file_path,+ self.exclude_build_target_patterns,+ self.exclude_regular_expressions,+ )+ )+++def _sanitize_regex_pattern(pattern: str) -> str:+ double_slash_index = pattern.find("//")+ return pattern[double_slash_index + 1 :] if double_slash_index != -1 else pattern+++def _path_matches_pattern_or_expression(+ debug_file_path: str,+ patterns: list[BuildTargetPatternOutputPathMatcher],+ expressions: list[re.Pattern[str]],+) -> bool:+ for pattern in patterns:+ if pattern.match_path(debug_file_path):+ return True+ for expression in expressions:+ if expression.search(debug_file_path):+ return True+ return False
@@ -0,0 +1,104 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import json+import unittest+from tempfile import NamedTemporaryFile++from .spec import BuildTargetPatternOutputPathMatcher, Spec++FAKE_PATH = "fake/path"+++class Test(unittest.TestCase):+ def test_build_target_pattern_matcher(self):+ target = BuildTargetPatternOutputPathMatcher("cell//foo:bar")+ self.assertTrue(target.match_path("foo/__bar__"))+ self.assertFalse(target.match_path("foo/__baz__"))++ package = BuildTargetPatternOutputPathMatcher("cell//foo:")+ self.assertTrue(package.match_path("foo/__bar__"))+ self.assertTrue(package.match_path("foo/__baz__"))+ self.assertFalse(target.match_path("foo/bar/__baz__"))++ recursive = BuildTargetPatternOutputPathMatcher("cell//foo/...")+ self.assertTrue(recursive.match_path("foo/__bar__"))+ self.assertTrue(recursive.match_path("foo/bar/__baz__"))+ self.assertFalse(recursive.match_path("bar/__baz__"))++ def test_spec_with_includes(self):+ test_spec = _base_spec()+ test_spec["include_build_target_patterns"] = [+ "cell//foo:",+ ]++ spec = _get_spec(test_spec)++ # We expect to not scrub anything with "foo/__"+ self.assertFalse(spec.scrub_debug_file_path("foo/__bar__"))+ self.assertFalse(spec.scrub_debug_file_path("foo/__baz__"))+ self.assertTrue(spec.scrub_debug_file_path("foo/bar/__baz__"))++ def test_spec_with_include_regex(self):+ test_spec = _base_spec()+ test_spec["include_regular_expressions"] = [+ "foo",+ ]++ spec = _get_spec(test_spec)++ # We expect to not scrub anything with "foo"+ self.assertFalse(spec.scrub_debug_file_path("foo/__bar__"))+ self.assertFalse(spec.scrub_debug_file_path("foo/__baz__"))+ self.assertTrue(spec.scrub_debug_file_path("bar/bar/__baz__"))++ def test_spec_with_exclude_regex(self):+ test_spec = _base_spec()+ test_spec["exclude_regular_expressions"] = [+ "foo",+ ]++ spec = _get_spec(test_spec)++ # We expect to scrub anything with "foo"+ self.assertTrue(spec.scrub_debug_file_path("foo/__bar__"))+ self.assertTrue(spec.scrub_debug_file_path("foo/__baz__"))+ self.assertFalse(spec.scrub_debug_file_path("bar/bar/__baz__"))++ def test_spec_with_both(self):+ test_spec = _base_spec()+ test_spec["include_build_target_patterns"] = [+ "cell//foo:",+ ]+ test_spec["exclude_regular_expressions"] = [+ "bar",+ ]++ spec = _get_spec(test_spec)++ # We expect to scrub anything with "bar", and not scrub anything with "foo/__"+ self.assertTrue(spec.scrub_debug_file_path("foo/__bar__"))+ self.assertFalse(spec.scrub_debug_file_path("foo/__baz__"))+ self.assertTrue(spec.scrub_debug_file_path("bar/bar/__baz__"))+++def _get_spec(test_spec) -> Spec:+ with NamedTemporaryFile(mode="w+") as tmp:+ json.dump(test_spec, tmp)+ tmp.flush()++ return Spec(tmp.name)+++def _base_spec() -> dict[str, list[str]]:+ return {+ "include_build_target_patterns": [],+ "include_regular_expressions": [],+ "exclude_build_target_patterns": [],+ "exclude_regular_expressions": [],+ }
binary file changed (absent → 40096 bytes)
@@ -0,0 +1,8 @@+{+ "include_build_target_patterns": [+ "//fbobjc/buck2/samples/focused_debugging:Foo"+ ],+ "include_regular_expressions": [],+ "exclude_build_target_patterns": [],+ "exclude_regular_expressions": []+}
@@ -0,0 +1,6 @@+{+ "include_build_target_patterns": [],+ "include_regular_expressions": ["fbsource//fbobjc/buck2/samples/focused_debugging:*"],+ "exclude_build_target_patterns": [],+ "exclude_regular_expressions": []+}
@@ -0,0 +1,6 @@+{+ "include_build_target_patterns": [],+ "include_regular_expressions": ["fbsource//fbobjc/buck2/samples/focused_debugging:*"],+ "exclude_build_target_patterns": [],+ "exclude_regular_expressions": ["//fbobjc/buck2/samples/focused_debugging:*"]+}
@@ -0,0 +1,5 @@+{+ "targets": [+ "//fbobjc/buck2/samples/focused_debugging:Foo"+ ]+}
@@ -0,0 +1,4 @@+{+ "targets": [+ ]+}
@@ -0,0 +1,13 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict+++class MachOException(Exception):+ pass
@@ -0,0 +1,11 @@+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("apple_workflows")++source_listing()++python_binary(+ name = "signing_context_tree_postprocessor",+ main = "main.py",+ visibility = ["PUBLIC"],+)
@@ -0,0 +1,96 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import argparse+import json+import os+from pathlib import Path++_FORMAT_VERSION = 1+++def _flatten_signing_contexts_from_signing_context_tree(+ current_path, signing_context_tree, flattened_contexts+):+ inner_contexts = signing_context_tree.get("inner_signing_contexts", {})+ for inner_rel_path, inner_signing_context_tree in inner_contexts.items():+ inner_path = os.path.join(current_path, inner_rel_path)+ # Process inner bundles first (i.e., inside out) for consistency with codesigning manifest tree+ _flatten_signing_contexts_from_signing_context_tree(+ current_path=inner_path,+ signing_context_tree=inner_signing_context_tree,+ flattened_contexts=flattened_contexts,+ )++ signing_context_path = signing_context_tree.get("signing_context")+ if signing_context_path:+ with open(signing_context_path, "r") as signing_context_file:+ signing_context = json.load(signing_context_file)++ signing_context_version = signing_context["version"]+ if signing_context_version != _FORMAT_VERSION:+ raise RuntimeError(+ f"Expected format version {_FORMAT_VERSION} but got {signing_context_version}"+ )+ if len(signing_context) > 1:+ # Skip inclusion of empty contexts+ processed_signing_context = dict(signing_context)+ processed_signing_context.pop("version")+ processed_signing_context["path"] = current_path+ flattened_contexts.append(processed_signing_context)+++def _args_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description="Tool which postprocesses a signing context tree to include all information inline."+ )+ parser.add_argument(+ "--signing-context-tree",+ metavar="<signing-context-tree.json>",+ type=Path,+ required=True,+ help="Path to the preprocessed signing context.",+ )+ parser.add_argument(+ "--output",+ metavar="<output.json>",+ type=Path,+ required=True,+ help="Path to the postprocessed file.",+ )++ return parser+++def _main() -> None:+ args_parser = _args_parser()+ args = args_parser.parse_args()++ with open(args.signing_context_tree, "r") as signing_context_tree_file:+ signing_context_tree = json.load(signing_context_tree_file)++ flattened_contexts = []+ _flatten_signing_contexts_from_signing_context_tree(+ current_path="",+ signing_context_tree=signing_context_tree,+ flattened_contexts=flattened_contexts,+ )++ with open(args.output, "w") as output_file:+ json.dump(+ {+ "version": _FORMAT_VERSION,+ "provisioned_bundles": flattened_contexts,+ },+ output_file,+ indent=4,+ )+++if __name__ == "__main__":+ _main()
@@ -0,0 +1,63 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++import argparse+import os+import shutil+from pathlib import Path+++def _args_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description="""+ Tool for combining multiple dsym bundles into a single one for Universal Binaries when the+ split_arch_dsym is enabled.+ """+ )+ parser.add_argument("--dsym-bundle", action="append", type=str)+ parser.add_argument("--arch", action="append", type=str)+ parser.add_argument(+ "--output",+ type=Path,+ required=True,+ help="Path where the output bundle should be written to",+ )++ return parser+++def _main() -> None:+ args = _args_parser().parse_args()++ output_dwarf_path = os.path.join(args.output, "Contents/Resources/DWARF")+ os.makedirs(output_dwarf_path)++ if len(args.arch) != len(args.dsym_bundle):+ raise Exception(+ f"Need to specify an architecture for every dsym bundle, archs:{args.arch}, dsyms:{args.dsym_bundle}"+ )+ for i in range(len(args.dsym_bundle)):+ dwarf_files_dir = os.path.join(args.dsym_bundle[i], "Contents/Resources/DWARF")+ dwarf_files = os.listdir(dwarf_files_dir)+ for dwarf_file in dwarf_files:+ shutil.copy2(+ os.path.join(dwarf_files_dir, dwarf_file),+ os.path.join(output_dwarf_path, f"{dwarf_file}.{args.arch[i]}"),+ )++ # pick one of the Info.plist and copy it to the output bundle.+ shutil.copy2(+ os.path.join(args.dsym_bundle[0], "Contents/Info.plist"),+ os.path.join(args.output, "Contents/Info.plist"),+ )+++if __name__ == "__main__":+ _main()
@@ -0,0 +1,96 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import argparse+import os+import shutil+import string++BINARY_TARGET_TEMPLATE = string.Template(+ """ .binaryTarget(name: "$name", path: "$path")"""+)++PACKAGE_TEMPLATE = string.Template(+ """// swift-tools-version:6.0++import PackageDescription++let package = Package(+ name: "$name",+ products: [+ .library(+ name: "$name",+ targets: [$targets]),+ ],+ targets: [+$binary_targets,+ ]+)+"""+)++FRAMEWORKS_SUBDIR = "Frameworks"+++def _main() -> None:+ parser = argparse.ArgumentParser(+ description="""+ Tool which accepts a list of XCFramework binaries to generate+ an SPM package that wraps them all.+ """+ )+ parser.add_argument(+ "--xcframework",+ action="append",+ nargs=2,+ required=True,+ help="Name and path to an XCFramework to include.",+ )+ parser.add_argument(+ "--output-path",+ action="store",+ required=True,+ help="Output dir to write package inside",+ )+ parser.add_argument(+ "--package-name",+ action="store",+ required=True,+ help="Name to use for package in Package.swift",+ )+ args = parser.parse_args()++ os.mkdir(args.output_path)+ os.mkdir(os.path.join(args.output_path, FRAMEWORKS_SUBDIR))++ binary_targets = []+ targets = []++ for framework in args.xcframework:+ name, path = framework+ relative_path = os.path.join(FRAMEWORKS_SUBDIR, os.path.basename(path))+ package_path = os.path.join(args.output_path, relative_path)+ shutil.copytree(path, package_path, symlinks=True)+ binary_targets.append(+ BINARY_TARGET_TEMPLATE.substitute({"name": name, "path": relative_path})+ )+ targets.append(f'"{name}"')++ swift_source = PACKAGE_TEMPLATE.substitute(+ {+ "name": args.package_name,+ "targets": ", ".join(targets),+ "binary_targets": ",\n".join(binary_targets),+ }+ )+ with open(os.path.join(args.output_path, "Package.swift"), "w") as package_swift:+ package_swift.write(swift_source)+++if __name__ == "__main__":+ _main()
@@ -0,0 +1,67 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import argparse+import subprocess+import sys+++def _filter_files(args):+ # Filter out any arg that starts with '-'. Also filter out passed arg+ # pairs like '-framework Cocoa'. Assumes that other args are files that+ # should be passed to libtool.+ # Rationale: There's no way of checking if an arg is intended to be a file.+ # Having a filter that checks if a file with a given path exists will+ # silently remove the arg in the event of an error where arg is a file and+ # the file does not exist.+ filtered_args = []+ skip_next = False+ for arg in args:+ if skip_next:+ skip_next = False+ continue+ if arg.startswith("-"):+ if arg == "-framework":+ skip_next = True+ continue+ filtered_args.append(arg)+ return filtered_args+++def _main() -> None:+ parser = argparse.ArgumentParser(+ description="""+ Tool which accepts a list of link argments and passes only the+ files to `libtool` to create a static archive of only those+ files for distribuion.+ """+ )+ # the libtool executable that is passed in can be mulitple args+ # i.e. it can be a run.sh wrapper followed by a supplementary arg+ # hence nargs="+"+ parser.add_argument(+ "--libtool", nargs="+", action="extend", required=True, help="path to libtool"+ )+ parser.add_argument("--output", required=True, help="path to output")+ parser.add_argument("args", nargs=argparse.REMAINDER)++ args = parser.parse_args()+ file_args = _filter_files(args.args)+ result = subprocess.run(+ args.libtool + ["-static", "-o", args.output] + file_args,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ encoding=sys.stdout.encoding,+ )+ print(result.stdout, file=sys.stdout, end="")+ print(result.stderr, file=sys.stderr, end="")+ sys.exit(result.returncode)+++if __name__ == "__main__":+ _main()
@@ -0,0 +1,459 @@+#!/usr/bin/env python3+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import argparse+import json+import os+import pathlib+import re+import shlex+import shutil+import subprocess+import sys++from writable import make_dir_recursively_writable, make_path_user_writable++_RE_TMPDIR_ENV_VAR = "TMPDIR"+_FILE_WRITE_FAILURE_MARKER = "could not write"+++def _expand_args(command):+ for arg in command:+ if arg.startswith("@"):+ with open(arg[1:]) as argsfile:+ return [line.rstrip() for line in argsfile.readlines()]++ return []+++def _get_modulemap(args):+ for i in range(len(args)):+ if args[i].startswith("-explicit-swift-module-map-file"):+ if args[i + 1].startswith("-Xfrontend"):+ path = args[i + 2]+ else:+ path = args[i + 1]++ with open(path.strip()) as modulemap:+ return json.load(modulemap)++ return None+++def _get_modulename(args):+ return args[args.index("-module-name") + 1]+++def _get_modules(command):+ args = _expand_args(command)+ modules = set()+ modules.add(_get_modulename(args))+ modulemap = _get_modulemap(args)+ if modulemap is None:+ return modules++ for entry in modulemap:+ # We only remove prefixes from first party modules.+ if "sdk_deps" in entry.get("clangModulePath", ""):+ pass+ elif "sdk_deps" in entry.get("modulePath", ""):+ pass+ else:+ modules.add(entry["moduleName"])++ return modules+++def _remove_swiftinterface_module_prefixes(command):+ interface_path = command[command.index("-emit-module-interface-path") + 1]+ modules = _get_modules(command)+ pattern = re.compile(r"(\w+)\.([\w.]+)")++ def replace_module_prefixes(match):+ if match.group(1) in modules:+ return match.group(2)+ else:+ return match.group(0)++ with open(interface_path, "r+") as f:+ interface = f.read()+ f.seek(0)+ f.write(pattern.sub(replace_module_prefixes, interface))+ f.truncate()+++def _make_path_user_writable(path: str) -> None:+ # Ensure the path is writable by the user. This is required for Swift+ # Incremental Remote Actions, where this path may or may not be+ # pre-populated from a previous action. We need to check because we won't+ # know if we have these paths populated until runtime.+ if "INSIDE_RE_WORKER" not in os.environ:+ return++ if not os.path.exists(path):+ return++ backup_path = f"{path}.bak"+ shutil.move(path, backup_path)+ if os.path.isdir(backup_path):+ shutil.copytree(backup_path, path)+ make_dir_recursively_writable(path)+ # Remove the original dir. Unlinking its files needs write+ # permission on parent dir+ for dirpath, _dirnames, _filenames in os.walk(backup_path):+ make_path_user_writable(dirpath)+ shutil.rmtree(backup_path)+ else:+ shutil.copy2(backup_path, path)+ pathlib.Path(backup_path).unlink()+ make_path_user_writable(path)+++def _rewrite_dependency_file(command, out_path):+ if not out_path:+ raise RuntimeError("-emit-dependencies requires -dependencies-file-output")++ # The compiler will output d files in Makefile format with abolute paths,+ # Buck expects line separated relative paths with no input prefix.+ output_file_map_path = command[command.index("-output-file-map") + 1]+ with open(output_file_map_path) as f:+ output_file_map = json.load(f)++ deps_file_path = output_file_map[""]["dependencies"]+ with open(deps_file_path, encoding="utf-8") as f:+ for line in f:+ # We have multiple entries for the supplementary outputs of the+ # compilation action. We have two cases we care about:+ # 1. swiftmodule output+ # 2. object file output+ # Other supplemenatary outputs like swiftsourceinfo are not+ # tracked.+ output, inputs = line.split(" : ")+ if output.endswith(".swiftmodule") or output.endswith(".o"):+ dependencies = shlex.split(inputs)+ break++ # Sanity check that we only track relative paths+ relative_paths = []+ for path in dependencies:+ if "/usr/lib/swift/host/" in path:+ # We don't track toolchain internal paths.+ continue+ elif path.startswith("/"):+ # This can occur for Xcode toolchain plugins like libSwiftUIMacros.dylib+ print(f"Dependency file contains absolute path: {path}", file=sys.stderr)+ else:+ relative_paths.append(os.path.normpath(path))++ _make_path_user_writable(out_path)+ with open(out_path, "w") as f:+ f.write("\n".join(sorted(relative_paths)))+ f.write("\n")+++def _get_output_file_map(args):+ try:+ i = args.index("-output-file-map")+ filename = args[i + 1]+ except (ValueError, IndexError):+ raise RuntimeError("Failed to find -output-file-map in args")++ with open(filename) as f:+ return json.load(f)+++def _get_serialized_diagnostics_frontend_flag(args):+ for a in args:+ if a.startswith("-serialize-diagnostics-path="):+ return a+ return None+++def _get_serialized_diagnostics_path(args):+ # The diagnostics can be specified via frontend args or in the output file+ # map.+ frontend_arg = _get_serialized_diagnostics_frontend_flag(args)+ if frontend_arg:+ return frontend_arg.split("=")[1]++ output_file_map = _get_output_file_map(args)+ module_entries = output_file_map.get("", {})+ if "diagnostics" in module_entries:+ return module_entries["diagnostics"]+ else:+ raise RuntimeError("Failed to find diagnostics in output file map")+++def _parse_wrapper_args(+ allargs: list[str],+) -> tuple[list[str], argparse.ArgumentParser]:+ driver_args = []+ wrapper_args = []+ i = 0+ while i < len(allargs):+ arg = allargs[i]+ if arg == "-Xwrapper":+ if i == len(allargs) - 1:+ raise RuntimeError("Missing argument to -Xwrapper")++ wrapper_args.append(allargs[i + 1])+ i += 2+ else:+ driver_args.append(arg)+ i += 1++ parser = argparse.ArgumentParser()+ parser.add_argument(+ "-dependencies-file-output",+ help="Path to write Buck format dependencies file to",+ )+ parser.add_argument(+ "-ignore-errors",+ action="store_true",+ help="Used to ignore errors during index store generation",+ )+ parser.add_argument(+ "-json-error-output-path",+ help="Path to write error output in JSON format",+ )+ parser.add_argument(+ "-remove-module-prefixes",+ action="store_true",+ help="Hack to remove module prefixes from swiftinterface output",+ )+ parser.add_argument(+ "-serialized-diagnostics-to-json",+ help="Path to serialized diagnostics to JSON transformer",+ )+ parser.add_argument(+ "-skip-incremental-outputs",+ action="store_true",+ help="Hack to skip writing incremental outputs to avoid cache invalidation",+ )+ parser.add_argument(+ "--writable-incremental-paths",+ nargs="*",+ help="Paths that should be made writable for incremental compilation",+ )+ parser.add_argument(+ "--no-file-prefix-map",+ action="store_true",+ help="Don't use -file-prefix-map or -coverage-prefix-map options",+ )+ parsed_args = parser.parse_args(wrapper_args)++ if (+ parsed_args.json_error_output_path+ and not parsed_args.serialized_diagnostics_to_json+ ):+ raise RuntimeError(+ "-json-error-output-path requires -serialized-diagnostics-to-json to transform the serialized diagnostics."+ )++ return driver_args, parsed_args+++def main():+ env = os.environ.copy()+ if "INSIDE_RE_WORKER" in env and _RE_TMPDIR_ENV_VAR in env:+ # Use $TMPDIR for the module cache location. This+ # will be set to a unique location for each RE action+ # which will avoid sharing modules across RE actions.+ # This is necessary as the inputs to the modules will+ # be transient and can be removed at any point, causing+ # module validation errors to fail builds.+ # https://github.com/llvm/llvm-project/blob/main/clang/lib/Driver/ToolChains/Clang.cpp#L3709+ env["CLANG_MODULE_CACHE_PATH"] = os.path.join(+ env[_RE_TMPDIR_ENV_VAR], "buck-module-cache"+ )+ else:+ # For local actions use a shared module cache location.+ # This should be safe to share across the other local+ # compilation actions.+ env["CLANG_MODULE_CACHE_PATH"] = "/tmp/buck-module-cache"++ # Separate the driver args from the wrapper args+ command, wrapper_args = _parse_wrapper_args(sys.argv[1:])++ # Use relative paths for debug information and index information,+ # so we generate relocatable files.+ #+ # We need to use the path where the action is run (both locally and on RE),+ # which is not known when we define the action.+ if not wrapper_args.no_file_prefix_map:+ command += [+ # Macro expansions get materialized in the temporary directory, which+ # varies between local and remote actions. For local actions this will+ # be a subdir of the CWD, so this needs to be the first map entry.+ # We also need this prefix for the clang module cache path if we are+ # not using explicit modules with remote actions.+ "-file-prefix-map",+ f"{env.get(_RE_TMPDIR_ENV_VAR, '/tmp').rstrip('/')}=/tmp",+ "-file-prefix-map",+ f"{os.getcwd()}/=",+ "-file-prefix-map",+ f"{os.getcwd()}=.",+ ]++ # Apply a coverage prefix map for the current directory+ # to make file path metadata relocatable stripping+ # the current directory from it.+ #+ # This overrides -file-prefix-map.+ command += [+ "-coverage-prefix-map",+ f"{os.getcwd()}=.",+ ]++ if wrapper_args.skip_incremental_outputs:+ command = _process_skip_incremental_outputs(command)++ writable_args = ["-emit-objc-header-path", "-emit-module-path"]++ for arg in writable_args:+ if arg in command:+ idx = command.index(arg)+ file_path = command[idx + 1]+ _make_path_user_writable(file_path)++ if wrapper_args.writable_incremental_paths:+ for file_path in wrapper_args.writable_incremental_paths:+ _make_path_user_writable(file_path)+ output_file_map_path = command[command.index("-output-file-map") + 1]+ with open(output_file_map_path) as f:+ output_file_map = json.load(f)+ for value in output_file_map.values():+ for subkey in [+ "swift-dependencies",+ "dependencies",+ "emit-module-dependencies",+ "emit-module-diagnostics",+ "diagnostics",+ "object",+ ]:+ maybe_path = value.get(subkey, None)+ if maybe_path:+ _make_path_user_writable(maybe_path)++ # Ensure the directories referenced by the output file map exist.+ # This can happen for Swift Incremental mode where there's no+ # previous incremental action available+ if "-output-file-map" in command:+ with open(command[command.index("-output-file-map") + 1]) as f:+ for entry in json.load(f).values():+ for maybe_path in entry.values():+ if isinstance(maybe_path, str) and os.path.dirname(maybe_path):+ os.makedirs(os.path.dirname(maybe_path), exist_ok=True)++ result = subprocess.run(+ command,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ encoding=sys.stdout.encoding,+ env=env,+ )++ print(result.stdout, file=sys.stdout, end="")+ print(result.stderr, file=sys.stderr, end="")++ if wrapper_args.json_error_output_path:+ _make_path_user_writable(wrapper_args.json_error_output_path)+ with open(wrapper_args.json_error_output_path, "w") as json_out:+ # Don't bother running the diagnostics deserializer if compilation+ # succeeded as the output will never be used.+ if result.returncode == 0 or wrapper_args.ignore_errors:+ json_out.write("[]")+ else:+ # Get the serialized diagnostics output from the output file map.+ serialized_diags = _get_serialized_diagnostics_path(command)++ # Convert the diagnostics to JSON for the Buck error handler.+ subprocess.run(+ [wrapper_args.serialized_diagnostics_to_json, serialized_diags],+ stdout=json_out,+ check=True,+ )++ if result.returncode == 0:+ # The Swift compiler will return an exit code of 0 and warn when it+ # cannot write auxiliary files. Detect and error so that the action+ # is not cached.+ failed_write = (+ _FILE_WRITE_FAILURE_MARKER in result.stdout+ or _FILE_WRITE_FAILURE_MARKER in result.stderr+ )+ if failed_write:+ print(+ "Detected Swift compiler file write error but compiler exited with code 0, failing command..."+ )+ sys.exit(1)++ # Rewrite .d files for the format that Buck requires.+ if "-emit-dependencies" in command:+ _rewrite_dependency_file(command, wrapper_args.dependencies_file_output)++ # https://github.com/swiftlang/swift/issues/56573+ if wrapper_args.remove_module_prefixes:+ _remove_swiftinterface_module_prefixes(command)++ if wrapper_args.ignore_errors:+ sys.exit(0)+ else:+ sys.exit(result.returncode)+++_SWIFT_FILES_ARGSFILE = "_swift_srcs"+++def _process_skip_incremental_outputs(command):+ output_file_map = command[command.index("-output-file-map") + 1]+ output_dir = os.path.dirname(os.path.dirname(output_file_map))++ module_swiftdeps = (+ f"{output_dir}/__swift_incremental__/swiftdeps/module-build-record.priors"+ )+ output_file_map_content = {+ "": {+ "swift-dependencies": module_swiftdeps,+ },+ }++ swift_files = _get_swift_files_to_compile(command)+ for swift_file in swift_files:+ file_name = swift_file.split("/")[-1]+ output_artifact = f"{output_dir}/__swift_incremental__/objects/{file_name}.o"+ swiftdeps_artifact = (+ f"{output_dir}/__swift_incremental__/swiftdeps/{file_name}.swiftdeps"+ )+ output_file_map_content[swift_file] = {+ "object": output_artifact,+ "swift-dependencies": swiftdeps_artifact,+ }++ with open(output_file_map, "w") as f:+ json.dump(output_file_map_content, f, indent=2)++ return command+++def _get_swift_files_to_compile(command):+ for arg in command:+ if arg.endswith(_SWIFT_FILES_ARGSFILE):+ path = arg[1:] # Remove leading @+ with open(path) as swift_files:+ return [+ line.rstrip().strip('"').strip("'")+ for line in swift_files.readlines()+ ]++ raise Exception(f"No {_SWIFT_FILES_ARGSFILE} found!")+++if __name__ == "__main__":+ main()
@@ -0,0 +1,162 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# pyre-strict++"""+Packages given input files into the correct format for an XCFramework, and generates+the required Info.plist.++Example Usage:+xcframework_maker.py --name FooKit --output_path /tmp/FooKit.xcframework \+ --framework_path ios-arm64 input/ios/FooKit.xcframework \+ --dsym_path ios-arm64 input/ios/dSYM \+ --framework_path ios-arm64_x86_64-simulator input/ios-simulator/FooKit.xcframework \+ --dsym_path ios-arm64_x86_64-simulator input/ios-simulator/dSYM +"""++import argparse+import plistlib+import shutil+from pathlib import Path+from typing import Any, Optional++# functions that take architecture specifiers as 'item'.+# Examples:+# ios-arm64_x86_64-simulator+# -> supported platform: ios+# -> supported architectures [arm64, x86_64]+# -> supported platform variant: simulator+# watchos-arm64_arm64_32+# -> supported platform: watchos+# -> supported architectures: [arm64, arm64_32]+# -> supported platform variant: None+++def _supported_architectures(item: str) -> list[str]:+ archs = []+ # order is important so that we can+ # consume 'arm64_32' first to prevent it+ # later matching arm64+ for arch in ["arm64_32", "arm64", "x86_64"]:+ if arch in item:+ archs.append(arch)+ item = item.replace(arch, "")+ return archs+++def _supported_platform(item: str) -> str:+ return item.split("-")[0]+++def _supported_platform_variant(item: str) -> Optional[str]:+ components = item.split("-")+ if len(components) > 2:+ return components[2]+ else:+ return None+++def _make_plist_entry(+ item: str, binary_path: str, library_path: str, dsym_path: Optional[str]+) -> dict[str, Any]:+ entry = {+ "BinaryPath": binary_path,+ "LibraryIdentifier": item,+ "LibraryPath": library_path,+ "SupportedArchitectures": _supported_architectures(item),+ "SupportedPlatform": _supported_platform(item),+ }+ variant = _supported_platform_variant(item)+ if variant is not None:+ entry["SupportedPlatformVariant"] = variant++ if dsym_path is not None:+ entry["DebugSymbolsPath"] = dsym_path++ return entry+++def _make_plist(+ items: list[str],+ binary_paths: list[str],+ library_path: str,+ dsym_paths: list[Optional[str]],+) -> bytes:+ d = {}+ d["AvailableLibraries"] = [+ _make_plist_entry(item, binary_path, library_path, dsym_path)+ for (item, binary_path, dsym_path) in zip(items, binary_paths, dsym_paths)+ ]+ d["CFBundlePackageType"] = "XFWK"+ d["XCFrameworkFormatVersion"] = "1.0"+ return plistlib.dumps(d)+++def _find_binary_path(framework_fullpath: str, binary_name: str) -> str:+ fullpath = Path(framework_fullpath)+ versioned_binary_paths = sorted(fullpath.glob("Versions/Current/" + binary_name))+ if len(versioned_binary_paths) > 0:+ return versioned_binary_paths[-1].relative_to(fullpath.parents[0]).as_posix()+ return fullpath.name + "/" + binary_name+++def main() -> None:+ parser = argparse.ArgumentParser(description="Tool to make an xcframework bundle.")+ parser.add_argument("--output-path")+ parser.add_argument("--name")+ parser.add_argument("--framework-path", action="append", nargs="+")+ parser.add_argument(+ "--dsym-path", action="append", nargs="+", default=[], required=False+ )+ args = parser.parse_args()++ out_path = Path(args.output_path)+ out_path.mkdir(parents=True, exist_ok=False)++ plist_path = out_path / "Info.plist"+ items = [fp_args[0] for fp_args in args.framework_path]+ binary_paths = []+ dsym_path_map = {}++ for framework_path in args.framework_path:+ # args are structured like this+ # --framework_path ios-arm64 buck-out/path/to/MyPkg.framework++ framework_arch = framework_path[0]+ framework_fullpath = framework_path[1]+ framework_basename = Path(framework_fullpath).name++ shutil.copytree(+ framework_fullpath,+ out_path / framework_arch / framework_basename,+ symlinks=True,+ dirs_exist_ok=False,+ )++ binary_paths.append(_find_binary_path(framework_fullpath, args.name))++ for dsym_path in args.dsym_path:+ dsym_arch = dsym_path[0]+ dsym_fullpath = dsym_path[1]+ shutil.copytree(+ dsym_fullpath,+ out_path / dsym_arch / "dSYMs" / (args.name + ".framework.dSYM"),+ symlinks=True,+ dirs_exist_ok=False,+ )+ dsym_path_map[dsym_arch] = "dSYMs"++ dsym_paths = [dsym_path_map.get(arch) for arch in items]++ library_path = args.name + ".framework"+ plist_path.write_bytes(_make_plist(items, binary_paths, library_path, dsym_paths))+++if __name__ == "__main__":+ main()
@@ -0,0 +1,286 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load("@prelude//apple:apple_bundle_destination.bzl", "AppleBundleDestination", "bundle_relative_path_for_destination")+load("@prelude//apple:apple_bundle_types.bzl", "AppleBundleInfo", "ApplePackageExtension")+load("@prelude//apple:apple_common.bzl", "apple_common")+load("@prelude//apple:apple_package_config.bzl", "IpaCompressionLevel")+load("@prelude//apple:apple_rules_impl_utility.bzl", "get_apple_bundle_toolchain_attr")+load("@prelude//apple:apple_sdk.bzl", "get_apple_sdk_name")+load("@prelude//apple:apple_swift_stdlib.bzl", "should_copy_swift_stdlib")+load("@prelude//apple:debug.bzl", "AppleDebuggableInfo")+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftToolchainInfo")+load("@prelude//utils:arglike.bzl", "ArgLike")++# Produced by the `apple_app_symbols` target. It carries the App Store `<UUID>.symbols`+# directory and the Swift stdlib dir.+AppleAppSymbolsInfo = provider(+ fields = {+ "swift_support_dir": provider_field(Artifact | None, default = None),+ "symbols_dir": provider_field(Artifact),+ },+)++def apple_ipa_package_impl(ctx: AnalysisContext) -> list[Provider]:+ ipa_package = _get_ipa_contents(ctx)+ return [DefaultInfo(default_output = ipa_package)]++def apple_ipa_package_attribs():+ attribs = {+ "bundle": attrs.dep(providers = [AppleBundleInfo]),+ "ext": attrs.enum(ApplePackageExtension.values(), default = "ipa"),+ "include_app_symbols": attrs.bool(default = False),+ "labels": attrs.list(attrs.string(), default = []),+ "package_name": attrs.option(attrs.string(), default = None),+ "_app_symbols": attrs.option(attrs.dep(providers = [AppleAppSymbolsInfo]), default = None),+ "_apple_toolchain": get_apple_bundle_toolchain_attr(),+ "_ipa_compression_level": attrs.enum(IpaCompressionLevel.values()),+ }+ attribs.update(apple_common.apple_tools_arg())+ return attribs++_IPA_PACKAGE_FORWARDED_FIELDS = [+ "bundle",+ "ext",+ "include_app_symbols",+ "package_name",+ "_ipa_compression_level",+ "compatible_with",+ "exec_compatible_with",+ "target_compatible_with",+ "default_target_platform",+ "within_view",+ "visibility",+]++def make_apple_ipa_package_target(apple_ipa_package_rule, **kwargs) -> [None, str]:+ ipa_package_kwargs = {+ "labels": ["generated"],+ }+ for field_name in _IPA_PACKAGE_FORWARDED_FIELDS:+ ipa_package_kwargs[field_name] = kwargs.get(field_name)++ # Only define the symbols target when app symbols are requested, either when set to+ # True or we have a select to evaluate.+ if kwargs.get("include_app_symbols"):+ app_symbols_target_name = kwargs["name"] + "__AppSymbols_Private"+ apple_app_symbols_rule(+ name = app_symbols_target_name,+ bundle = kwargs.get("bundle"),+ include_app_symbols = kwargs.get("include_app_symbols"),+ labels = ["generated"],+ exec_compatible_with = ["config//os:macos"],+ compatible_with = kwargs.get("compatible_with"),+ target_compatible_with = kwargs.get("target_compatible_with"),+ default_target_platform = kwargs.get("default_target_platform"),+ within_view = kwargs.get("within_view"),+ visibility = kwargs.get("visibility"),+ )+ ipa_package_kwargs["_app_symbols"] = ":{}".format(app_symbols_target_name)++ ipa_package_target_name = kwargs["name"] + "__IPA_Package_Private"+ apple_ipa_package_rule(name = ipa_package_target_name, **ipa_package_kwargs)++ return ":{}".format(ipa_package_target_name)++def _get_ipa_contents(ctx: AnalysisContext) -> Artifact:+ bundle = ctx.attrs.bundle+ app = bundle[DefaultInfo].default_outputs[0]++ contents = {+ paths.join("Payload", app.basename): app,+ }++ apple_bundle_info = bundle[AppleBundleInfo]+ swift_needed = (not apple_bundle_info.skip_copying_swift_stdlib) and should_copy_swift_stdlib(app.extension)++ app_symbols_info = ctx.attrs._app_symbols[AppleAppSymbolsInfo] if ctx.attrs._app_symbols else None+ if ctx.attrs.include_app_symbols and app_symbols_info != None:+ # App symbols requested: the macOS-only apple_app_symbols target already+ # produced the Swift stdlib dir (computed once, there) and the populated+ # Symbols/ dir. Copy both in; no Mac-only action runs in this rule.+ if swift_needed:+ contents[paths.join("SwiftSupport", get_apple_sdk_name(ctx))] = app_symbols_info.swift_support_dir+ contents["Symbols"] = app_symbols_info.symbols_dir+ else:+ if swift_needed:+ contents[paths.join("SwiftSupport", get_apple_sdk_name(ctx))] = _get_swift_support_dir(ctx, app, apple_bundle_info)++ # watchOS IPAs require a top-level (possibly empty) Symbols/ dir to exist.+ if apple_bundle_info.contains_watchapp:+ contents["Symbols"] = _empty_symbols_dir(ctx)++ return ctx.actions.copied_dir(+ "__unzipped_ipa_contents__",+ contents,+ has_content_based_path = False,+ )++def _empty_symbols_dir(ctx) -> Artifact:+ symbols_dir = ctx.actions.declare_output("__symbols__", dir = True, has_content_based_path = False)+ ctx.actions.run(+ cmd_args(["mkdir", "-p", symbols_dir.as_output()]),+ category = "watchos_symbols_dir",+ )+ return symbols_dir++def _apple_app_symbols_impl(ctx: AnalysisContext) -> list[Provider]:+ bundle = ctx.attrs.bundle+ app = bundle[DefaultInfo].default_outputs[0]+ apple_bundle_info = bundle[AppleBundleInfo]++ # When include_app_symbols resolves False for this configuration, produce an+ # empty dir (unconsumed by the IPA package, so its action never runs) and skip+ # the Swift stdlib work — the IPA package computes Swift support itself in that+ # path, so the stdlib tool is still only ever run once.+ if not ctx.attrs.include_app_symbols:+ symbols_dir = _empty_symbols_dir(ctx)+ return [+ DefaultInfo(default_output = symbols_dir),+ AppleAppSymbolsInfo(symbols_dir = symbols_dir),+ ]++ swift_support_dir = None+ if (not apple_bundle_info.skip_copying_swift_stdlib) and should_copy_swift_stdlib(app.extension):+ swift_support_dir = _get_swift_support_dir(ctx, app, apple_bundle_info)++ symbols_dir = _build_app_symbols_dir(ctx, swift_support_dir)+ return [+ DefaultInfo(default_output = symbols_dir),+ AppleAppSymbolsInfo(+ symbols_dir = symbols_dir,+ swift_support_dir = swift_support_dir,+ ),+ ]++def _build_app_symbols_dir(ctx, swift_support_dir) -> Artifact:+ # Emit one <UUID>.symbols per Mach-O slice from the bundle's dSYMs (and bundled+ # Swift stdlib dylibs).+ symbols_dir = ctx.actions.declare_output("__symbols__", dir = True, has_content_based_path = False)+ dsyms = ctx.attrs.bundle[AppleDebuggableInfo].dsyms++ script_lines = [+ cmd_args("set -euo pipefail"),+ cmd_args(symbols_dir, format = "mkdir -p {}"),+ ]+ symbol_inputs = []+ if dsyms:+ script_lines.append(+ cmd_args(+ ["symbols", "-arch", "all", "-symbolsPackageDir", symbols_dir] + dsyms,+ delimiter = " ",+ quote = "shell",+ )+ )+ symbol_inputs.extend(dsyms)+ if swift_support_dir != None:+ script_lines.append(+ cmd_args(+ [+ "symbols",+ "-arch",+ "all",+ "-symbolsPackageDir",+ symbols_dir,+ cmd_args(swift_support_dir, format = "{}/*"),+ "||",+ "echo",+ "'warning: swift stdlib symbols packaging failed'",+ ">&2",+ ],+ delimiter = " ",+ quote = "shell",+ )+ )+ symbol_inputs.append(swift_support_dir)++ script, _ = ctx.actions.write(+ "build_app_symbols.sh",+ script_lines,+ allow_args = True,+ has_content_based_path = False,+ )+ ctx.actions.run(+ cmd_args(["/bin/sh", script], hidden = symbol_inputs + [symbols_dir.as_output()]),+ category = "app_symbols_dir",+ )++ return symbols_dir++apple_app_symbols_rule = rule(+ impl = _apple_app_symbols_impl,+ attrs = {+ "bundle": attrs.dep(providers = [AppleBundleInfo, AppleDebuggableInfo]),+ "include_app_symbols": attrs.bool(default = False),+ "labels": attrs.list(attrs.string(), default = []),+ "_apple_toolchain": get_apple_bundle_toolchain_attr(),+ },+)++def _get_swift_support_dir(ctx, bundle_output: Artifact, bundle_info: AppleBundleInfo) -> Artifact:+ stdlib_tool = ctx.attrs._apple_toolchain[SwiftToolchainInfo].swift_stdlib_tool+ sdk_name = get_apple_sdk_name(ctx)++ # .app -> app+ # This is the way the input is expected.+ extension = bundle_output.extension[1:]+ swift_support_dir = ctx.actions.declare_output("__swift_dylibs__", dir = True, has_content_based_path = False)+ script, _ = ctx.actions.write(+ "build_swift_support.sh",+ [+ cmd_args("set -euo pipefail"),+ cmd_args(swift_support_dir, format = "mkdir -p {}"),+ cmd_args(+ [+ stdlib_tool,+ # If you're debugging, you can pass the '--verbose' flag here.+ "--copy",+ "--scan-executable",+ cmd_args(+ [+ bundle_output,+ bundle_relative_path_for_destination(AppleBundleDestination("executables"), sdk_name, extension, False),+ bundle_info.binary_name,+ ],+ delimiter = "/",+ ),+ _get_scan_folder_args(AppleBundleDestination("plugins"), bundle_output, sdk_name, extension),+ _get_scan_folder_args(AppleBundleDestination("extensionkit_extensions"), bundle_output, sdk_name, extension),+ _get_scan_folder_args(AppleBundleDestination("frameworks"), bundle_output, sdk_name, extension),+ _get_scan_folder_args(AppleBundleDestination("appclips"), bundle_output, sdk_name, extension),+ "--destination",+ swift_support_dir,+ ],+ delimiter = " ",+ quote = "shell",+ ),+ ],+ allow_args = True,+ has_content_based_path = False,+ )+ ctx.actions.run(+ cmd_args(["/bin/sh", script], hidden = [stdlib_tool, bundle_output, swift_support_dir.as_output()]),+ category = "copy_swift_stdlibs",+ )++ return swift_support_dir++def _get_scan_folder_args(dest: AppleBundleDestination, bundle_output: Artifact, sdk_name, extension) -> ArgLike:+ return cmd_args(+ [+ "--scan-folder",+ cmd_args(+ [+ bundle_output,+ bundle_relative_path_for_destination(dest, sdk_name, extension, False),+ ],+ delimiter = "/",+ ),+ ],+ )
@@ -0,0 +1,14 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_bundle.bzl", "apple_bundle_impl")++def apple_macos_bundle_impl(ctx: AnalysisContext) -> list[Provider]:+ # This rule is _equivalent_ to `apple_bundle` except it applies+ # an incoming macOS transition.+ return apple_bundle_impl(ctx)
@@ -0,0 +1,48 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//apple:apple_bundle_resources.bzl",+ "AppleBundleResourcePartListOutput", # @unused Used as a type+ "get_apple_bundle_resource_part_list",+)+load("@prelude//apple:apple_bundle_types.bzl", "AppleBundleResourceInfo")++def _extract_all_resources(part_list: AppleBundleResourcePartListOutput) -> list[Artifact]:+ all_resources = [resource_bundle_part.source for resource_bundle_part in part_list.resource_parts]+ all_resources.append(part_list.info_plist_part.source)+ return all_resources++def apple_resource_bundle_impl(ctx: AnalysisContext) -> list[Provider]:+ resource_output = get_apple_bundle_resource_part_list(ctx)++ all_resources = _extract_all_resources(resource_output)+ all_resources_json = {"resources": all_resources}+ all_resources_json_file = ctx.actions.declare_output("resources.json", has_content_based_path = False)+ all_resources_json_cmd_args = ctx.actions.write_json(+ all_resources_json_file,+ all_resources_json,+ with_inputs = True,+ pretty = True,+ )++ return [+ DefaultInfo(+ sub_targets = {+ "resources": [+ DefaultInfo(+ default_output = all_resources_json_file,+ other_outputs = [all_resources_json_cmd_args],+ )+ ],+ }+ ),+ AppleBundleResourceInfo(+ resource_output = resource_output,+ ),+ ]
@@ -0,0 +1,41 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++def _is_universal(platform: PlatformInfo, refs: struct) -> bool:+ universal = platform.configuration.constraints.get(refs.universal[ConstraintSettingInfo].label)+ return universal.label == refs.universal_enabled[ConstraintValueInfo].label if universal != None else False++def _apple_resource_transition_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> PlatformInfo:+ if attrs.skip_universal_resource_dedupe or not _is_universal(platform, refs):+ return platform+ else:+ cpu_constraint_label = refs.cpu[ConstraintSettingInfo].label+ filtered_constraints = {+ constraint_setting_label: constraint_setting_value+ for (constraint_setting_label, constraint_setting_value) in platform.configuration.constraints.items()+ if constraint_setting_label != cpu_constraint_label+ }+ return PlatformInfo(+ label = "apple_universal_deduped_resource",+ configuration = ConfigurationInfo(+ constraints = filtered_constraints,+ values = platform.configuration.values,+ ),+ )++apple_resource_transition = transition(+ impl = _apple_resource_transition_impl,+ refs = {+ "cpu": "config//cpu/constraints:cpu",+ "universal": "config//cpu/constraints:universal",+ "universal_enabled": "config//cpu/constraints:universal-enabled",+ },+ attrs = [+ "skip_universal_resource_dedupe",+ ],+)
@@ -0,0 +1,11 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# The file name used to store the user's selected debug path in selective debugging+# Will save to the root of app bundle+SELECTED_DEBUG_PATH_FILE_NAME = "SelectedDebugPaths.txt"
@@ -0,0 +1,350 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactInfo",+ "ArtifactInfoTag",+)+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo", "AppleToolsInfo")+load(+ "@prelude//linking:execution_preference.bzl",+ "LinkExecutionPreference",+ "LinkExecutionPreferenceDeterminatorInfo",+ "LinkExecutionPreferenceInfo", # @unused Used as a type+ "get_action_execution_attributes",+)+load(+ "@prelude//utils:build_target_pattern.bzl",+ "BuildTargetPattern", # @unused Used as a type+ "parse_build_target_pattern",+)+load("@prelude//utils:lazy.bzl", "lazy")++_SelectionCriteria = record(+ include_build_target_patterns = field(list[BuildTargetPattern], []),+ include_regular_expressions = field(list[regex], []),+ exclude_build_target_patterns = field(list[BuildTargetPattern], []),+ exclude_regular_expressions = field(list[regex], []),+)++AppleSelectiveDebuggingInfo = provider(+ # @unsorted-dict-items+ fields = {+ "scrub_binary": provider_field(typing.Callable),+ "filter": provider_field(typing.Callable),+ "scrub_selected_debug_paths_file": provider_field(typing.Callable),+ },+)++AppleSelectiveDebuggingFilteredDebugInfo = record(+ # Contains all artifacts, including those required for debugging (e.g., `.swiftmodule` files)+ infos = field(list[ArtifactInfo]),+ # Contains only artifacts for _selected_ targets, excluding any others+ selected_target_infos = field(list[ArtifactInfo]),+ swift_modules_labels = field(list[Label]),+ metadata = field(Artifact),+)++# The type of selective debugging json input to utilze.+SelectiveDebuggingJsonTypes = [+ # Use a targets json file containing all targets to include.+ "targets",+ # Use a spec json file specifying the targets to include+ # and exclude via build target patterns and regular expressions.+ "spec",+]++_SelectiveDebuggingJsonType = enum(*SelectiveDebuggingJsonTypes)++_LOCAL_LINK_THRESHOLD = 0.2++_OBJECT_FILE_EXTENSIONS = [+ ".o",+ ".a",+]++def _apple_skip_adhoc_resigning_scrubbed_frameworks_attr_value(bundle_ctx: AnalysisContext) -> bool:+ override_value = bundle_ctx.attrs._skip_adhoc_resigning_scrubbed_frameworks_override+ if override_value != None:+ # Override takes precedence over any other value+ return override_value++ skip = bundle_ctx.attrs.skip_adhoc_resigning_scrubbed_frameworks+ return skip if skip != None else bundle_ctx.attrs._skip_adhoc_resigning_scrubbed_frameworks_default++def _should_skip_adhoc_sign_after_scrubbing(bundle_ctx: AnalysisContext) -> bool:+ sdk_name = bundle_ctx.attrs._apple_toolchain[AppleToolchainInfo].sdk_name+ if bundle_ctx.attrs.extension == "framework" and "iphonesimulator" in sdk_name:+ # While scrubbing invalidates the code signature, the signature of frameworks+ # are generally not checked by the system (unless running against the hardened+ # runtime for macOS apps). Re-signing scrubbed frameworks can take non-trivial+ # time, so skip it if it's not needed.+ return _apple_skip_adhoc_resigning_scrubbed_frameworks_attr_value(bundle_ctx)+ return False++def _generate_metadata_json_object(is_any_selected_target_linked: bool) -> dict[str, typing.Any]:+ return {+ "contains_focused_targets": is_any_selected_target_linked,+ }++def apple_selective_debugging_impl(ctx: AnalysisContext) -> list[Provider]:+ json_type = _SelectiveDebuggingJsonType(ctx.attrs.json_type)++ # process inputs and provide them up the graph with typing+ include_build_target_patterns = [parse_build_target_pattern(pattern) for pattern in ctx.attrs.include_build_target_patterns]+ include_regular_expressions = [+ # TODO(nga): fancy is probably not needed here.+ regex(expression, fancy = True)+ for expression in ctx.attrs.include_regular_expressions+ ]+ exclude_build_target_patterns = [parse_build_target_pattern(pattern) for pattern in ctx.attrs.exclude_build_target_patterns]+ exclude_regular_expressions = [+ # TODO(nga): fancy is probably not needed here.+ regex(expression, fancy = True)+ for expression in ctx.attrs.exclude_regular_expressions+ ]++ scrubber = ctx.attrs._apple_tools[AppleToolsInfo].selective_debugging_scrubber++ targets_json_file = None+ cmd = cmd_args(scrubber)+ if json_type == _SelectiveDebuggingJsonType("targets"):+ targets_json_file = ctx.attrs.targets_json_file or ctx.actions.write_json("targets.json", {"targets": []}, has_content_based_path = False)++ # If a targets json file is not provided, write an empty json file:+ cmd.add("--targets-file")+ cmd.add(targets_json_file)+ elif json_type == _SelectiveDebuggingJsonType("spec"):+ json_data = {+ "exclude_build_target_patterns": ctx.attrs.exclude_build_target_patterns,+ "exclude_regular_expressions": ctx.attrs.exclude_regular_expressions,+ "include_build_target_patterns": ctx.attrs.include_build_target_patterns,+ "include_regular_expressions": ctx.attrs.include_regular_expressions,+ }+ spec_file = ctx.actions.write_json("selective_debugging_spec.json", json_data, has_content_based_path = False)+ cmd.add("--spec-file")+ cmd.add(spec_file)+ else:+ fail("Expected json_type to be either `targets` or `spec`.")++ selection_criteria = _SelectionCriteria(+ include_build_target_patterns = include_build_target_patterns,+ include_regular_expressions = include_regular_expressions,+ exclude_build_target_patterns = exclude_build_target_patterns,+ exclude_regular_expressions = exclude_regular_expressions,+ )++ def scrub_selected_debug_paths_file(inner_ctx: AnalysisContext, package_names: list[str], output_name: str) -> Artifact:+ # In the event that _SelectiveDebuggingJsonType was "spec", we expect that `package_names`+ # was already filtered as part of scrubbing the binary in the apple_bundle.+ #+ # See `_maybe_scrub_binary()` in apple_bundle.bzl+ if json_type != _SelectiveDebuggingJsonType("targets"):+ return inner_ctx.actions.write(output_name, sorted(set(package_names)), has_content_based_path = False)++ def scrub_selected_debug_paths_action(dynamic_ctx: AnalysisContext, artifacts, outputs):+ packages = [+ # "cell//path/to/some/thing:target" -> "path/to/some/thing"+ target.split("//")[1].split(":")[0]+ for target in artifacts[targets_json_file].read_json()["targets"]+ ]+ dynamic_ctx.actions.write(+ outputs.values()[0],+ sorted(set(filter(lambda p: p in packages, package_names))),+ )++ output = inner_ctx.actions.declare_output(output_name, has_content_based_path = False)+ inner_ctx.actions.dynamic_output(+ dynamic = [targets_json_file],+ inputs = [],+ outputs = [output.as_output()],+ f = scrub_selected_debug_paths_action,+ )++ return output++ def scrub_binary(+ inner_ctx,+ executable: Artifact,+ executable_link_execution_preference: LinkExecutionPreference,+ adhoc_codesign_tool: [RunInfo, None],+ focused_targets_labels: list[Label],+ identifier: None | str = None,+ ) -> Artifact:+ inner_cmd = cmd_args(cmd)+ subdir = "{}/".format(identifier) if identifier else ""+ output = inner_ctx.actions.declare_output("debug_scrubbed/{}{}".format(subdir, executable.short_path), has_content_based_path = False)++ action_execution_properties = get_action_execution_attributes(executable_link_execution_preference)++ # If we're provided a codesign tool, provider it to the scrubber binary so that it may sign+ # the binary after scrubbing.+ if adhoc_codesign_tool and (not _should_skip_adhoc_sign_after_scrubbing(inner_ctx)):+ inner_cmd.add(["--adhoc-codesign-tool", adhoc_codesign_tool])+ inner_cmd.add(["--input", executable])+ inner_cmd.add(["--output", output.as_output()])+ if len(focused_targets_labels) > 0:+ additional_labels_json = inner_ctx.actions.write_json(+ inner_ctx.attrs.name + ".additional_labels.json",+ {"targets": [label.raw_target() for label in focused_targets_labels]},+ has_content_based_path = False,+ )+ inner_cmd.add(["--persisted-targets-file", additional_labels_json])+ inner_ctx.actions.run(+ inner_cmd,+ category = "scrub_binary",+ identifier = output.short_path,+ prefer_local = action_execution_properties.prefer_local,+ prefer_remote = action_execution_properties.prefer_remote,+ local_only = action_execution_properties.local_only,+ force_full_hybrid_if_capable = action_execution_properties.full_hybrid,+ )+ return output++ def filter_debug_info(inner_ctx: AnalysisContext, debug_info: TransitiveSetIterator) -> AppleSelectiveDebuggingFilteredDebugInfo:+ artifact_infos = []+ selected_target_infos = []+ linked_targets = set()+ is_any_selected_target_linked = False+ is_using_spec = json_type == _SelectiveDebuggingJsonType("spec")+ selected_targets_contain_swift = False+ for infos in debug_info:+ for info in infos:+ is_swift_debug_info = ArtifactInfoTag("swift_debug_info") in info.tags+ is_label_included = _is_label_included(info.label, selection_criteria)++ is_any_selected_target_linked_when_using_spec = is_using_spec and is_any_selected_target_linked+ if not is_any_selected_target_linked_when_using_spec:+ # When using spec mode and there's already a selected target, there's no need+ # to continue the search whether a selected target is linked - we know at least+ # one is already linked. So, the if statement acts as a short-circuit for perf+ # reasons to avoid unnecessary work.+ #+ # In targets mode (i.e., non-spec mode), the full list of `linked_targets` must+ # be computed, as that value is used behind a dynamic output, so it's not possible+ # terminate the search early (as we cannot determine whether a selected target is linked+ # as the list of selected targets is stored in the targets JSON file, which is not available+ # at analysis time, only avail behind a dynamic output).+ debug_artifact_contains_object_code = lazy.is_any(+ lambda debug_artifact: debug_artifact.extension in _OBJECT_FILE_EXTENSIONS, info.artifacts+ )+ if debug_artifact_contains_object_code:+ if is_using_spec and is_label_included:+ is_any_selected_target_linked = True+ if not is_using_spec:+ # `linked_targets` only used in targets mode, avoid costs in all other modes+ linked_targets.add(info.label)++ if is_label_included:+ # `selected_target_infos` should only include targets explicitly selected by the user,+ # not anything included in addition to support the debugger (e.g., `.swiftmodule` files)+ selected_target_infos.append(info)+ if is_label_included or (selected_targets_contain_swift and is_swift_debug_info):+ # There might be a few ArtifactInfo corresponding to the same Label,+ # so to avoid overwriting, we need to preserve all artifacts.+ artifact_infos.append(info)+ selected_targets_contain_swift = selected_targets_contain_swift or ArtifactInfoTag("swift_debug_info") in info.tags++ if json_type == _SelectiveDebuggingJsonType("spec"):+ metadata_output = inner_ctx.actions.write_json(+ "selective_metadata_with_spec.json",+ _generate_metadata_json_object(is_any_selected_target_linked),+ pretty = True,+ has_content_based_path = False,+ )+ elif json_type == _SelectiveDebuggingJsonType("targets"):++ def generate_metadata_output(dynamic_ctx: AnalysisContext, artifacts, outputs):+ targets = artifacts[targets_json_file].read_json()["targets"]+ is_any_selected_target_linked_inner = False+ for target in targets:+ cell, package_with_target_name = target.split("//")+ package, target_name = package_with_target_name.split(":")++ is_any_selected_target_linked_inner = lazy.is_any(+ lambda linked_target: linked_target.cell == cell and linked_target.package == package and linked_target.name == target_name,+ linked_targets,+ )+ if is_any_selected_target_linked_inner:+ break++ dynamic_ctx.actions.write_json(+ outputs.values()[0],+ _generate_metadata_json_object(is_any_selected_target_linked_inner),+ pretty = True,+ )++ metadata_output = inner_ctx.actions.declare_output("selective_metadata_with_targets_file.json", has_content_based_path = False)+ inner_ctx.actions.dynamic_output(+ dynamic = [targets_json_file],+ inputs = [],+ outputs = [metadata_output.as_output()],+ f = generate_metadata_output,+ )+ else:+ fail("Unexpected type: {}".format(json_type))++ return AppleSelectiveDebuggingFilteredDebugInfo(+ infos = artifact_infos,+ selected_target_infos = selected_target_infos,+ swift_modules_labels = [],+ metadata = metadata_output,+ )++ def preference_for_links(links: list[Label], deps_preferences: list[LinkExecutionPreferenceInfo]) -> LinkExecutionPreference:+ # If any dependent links were run locally, prefer that the current link is also performed locally,+ # to avoid needing to upload the previous link.+ dep_prefered_local = lazy.is_any(lambda info: info.preference == LinkExecutionPreference("local"), deps_preferences)+ if dep_prefered_local:+ return LinkExecutionPreference("local")++ # If we're not provided a list of links, we can't make an informed determination.+ if not links:+ return LinkExecutionPreference("any")++ matching_links = filter(None, [link for link in links if _is_label_included(link, selection_criteria)])++ # If more than 20% of targets being linked are also downloaded for debugging, perform the+ # link locally, as we'd need to download the object files anyway (and can skip downloading the link output).+ # Otherwise, perform the link remotely, and we'll just download the debug data separately.+ if len(matching_links) / len(links) >= _LOCAL_LINK_THRESHOLD:+ return LinkExecutionPreference("local")+ return LinkExecutionPreference("remote")++ return [+ DefaultInfo(),+ AppleSelectiveDebuggingInfo(+ scrub_binary = scrub_binary,+ filter = filter_debug_info,+ scrub_selected_debug_paths_file = scrub_selected_debug_paths_file,+ ),+ LinkExecutionPreferenceDeterminatorInfo(preference_for_links = preference_for_links),+ ]++def _is_label_included(label: Label, selection_criteria: _SelectionCriteria) -> bool:+ # If no include criteria are provided, we then include everything, as long as it is not excluded.+ if selection_criteria.include_build_target_patterns or selection_criteria.include_regular_expressions:+ if not _check_if_label_matches_patterns_or_expressions(+ label, selection_criteria.include_build_target_patterns, selection_criteria.include_regular_expressions+ ):+ return False++ # If included (above snippet), ensure that this target is not excluded.+ return not _check_if_label_matches_patterns_or_expressions(+ label, selection_criteria.exclude_build_target_patterns, selection_criteria.exclude_regular_expressions+ )++def _check_if_label_matches_patterns_or_expressions(label: Label, patterns: list[BuildTargetPattern], expressions: list[regex]) -> bool:+ for pattern in patterns:+ if pattern.matches(label):+ return True+ for expression in expressions:+ if expression.match(str(label)):+ return True+ return False
@@ -0,0 +1,38 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")+load("@prelude//apple/user:apple_xcframework.bzl", "XCFrameworkInfo")+load("@prelude//utils:utils.bzl", "flatten")++def apple_spm_package_impl(ctx: AnalysisContext) -> list[Provider]:+ apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]++ spm_packager = apple_tools.spm_packager++ output_dir = ctx.actions.declare_output(ctx.attrs.name, dir = True, has_content_based_path = False)++ xcframework_binaries = [dep for dep in ctx.attrs.deps if dep.get(XCFrameworkInfo)]+ binary_args = flatten([["--xcframework", dep[XCFrameworkInfo].name, dep[DefaultInfo].default_outputs[0]] for dep in xcframework_binaries])++ spm_command = cmd_args(+ [+ spm_packager,+ "--output-path",+ output_dir.as_output(),+ "--package-name",+ ctx.attrs.package_name,+ ]+ + binary_args+ )++ ctx.actions.run(spm_command, category = "assemble_spm_package")++ return [+ DefaultInfo(default_output = output_dir),+ ]
@@ -0,0 +1,14 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_bundle.bzl", "apple_bundle_impl")++def apple_watchos_bundle_impl(ctx: AnalysisContext) -> list[Provider]:+ # This rule is _equivalent_ to `apple_bundle` except it applies+ # an incoming watchOS transition.+ return apple_bundle_impl(ctx)
@@ -0,0 +1,201 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_bundle_types.bzl", "AppleBundleInfo")+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")++# Metadata about XCFramework+XCFrameworkInfo = provider(+ fields = {+ # Name of supplied framework. For frameworks that define+ # modules this should be the name of the module+ "name": provider_field(str),+ },+)++def _get_any_framework_dep(framework_deps: [dict[str, Dependency], Dependency, None]) -> [Dependency, None]:+ if not type(framework_deps) == "dict":+ return framework_deps+ if len(framework_deps) == 0:+ return None+ return sorted(framework_deps.items())[0][1]++def _get_framework_name(ctx: AnalysisContext) -> str:+ if ctx.attrs.framework_name != None:+ return ctx.attrs.framework_name+ if ctx.attrs.framework_name_from_product_name:+ framework = _get_any_framework_dep(ctx.attrs.framework)+ if framework == None:+ fail("Cannot find framework name")+ return framework[AppleBundleInfo].binary_name+ fail("Cannot find framework name")++def apple_xcframework_impl(ctx: AnalysisContext) -> list[Provider]:+ apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]+ framework_name = _get_framework_name(ctx)++ xcframework_dir = ctx.actions.declare_output(framework_name + ".xcframework", dir = True, has_content_based_path = False)+ xcframework_command = cmd_args([+ apple_tools.xcframework_maker,+ "--output-path",+ xcframework_dir.as_output(),+ "--name",+ framework_name,+ ])++ for arch in ctx.attrs.framework:+ framework_dep = ctx.attrs.framework[arch]+ framework_paths = framework_dep[DefaultInfo].default_outputs+ if len(framework_paths) > 1:+ fail("xcframework's framework target {} must only produce one output".format(framework_dep.label))++ xcframework_command.add("--framework-path")+ xcframework_command.add(arch)+ xcframework_command.add(framework_paths[0])++ if ctx.attrs.include_dsym:+ dsym_dep = framework_dep[DefaultInfo].sub_targets["dsym"]+ dsym_path = dsym_dep[DefaultInfo].default_outputs+ xcframework_command.add("--dsym-path")+ xcframework_command.add(arch)+ xcframework_command.add(dsym_path)++ ctx.actions.run(xcframework_command, category = "apple_xcframework")+ return [+ DefaultInfo(default_output = xcframework_dir),+ XCFrameworkInfo(name = framework_name),+ ]++def _strip_os_sdk_and_runtime_constraints(platform: PlatformInfo, refs: struct) -> dict[TargetLabel, ConstraintValueInfo]:+ return {+ constraint_setting_label: constraint_setting_value+ for (constraint_setting_label, constraint_setting_value) in platform.configuration.constraints.items()+ if constraint_setting_label+ not in [+ refs.os[ConstraintSettingInfo].label,+ refs.sdk[ConstraintSettingInfo].label,+ refs.universal[ConstraintSettingInfo].label,+ refs.runtime[ConstraintSettingInfo].label,+ ]+ }++# provides a map of os-platform to cpu architectures+# so we can identify when universal binaries can be created instead of+# two separate frameworks+#+# e.g. input of ["ios-arm64", "iphonesimulator-x86_64", "iphonesimulator-arm64"]+# will produce {"ios": ["arm64"], "iphonesimulator": ["arm64", "x86_64"]}++def _normalize_platforms(platforms: list[str]) -> dict[str, list[str]]:+ result = {}+ for platform in platforms:+ plat_list = platform.split("-")+ plat_type = plat_list[0]+ plat_archs = plat_list[1:]+ previous_archs = result.get(plat_type, [])+ result[plat_type] = sorted(plat_archs + previous_archs)++ return result++def _apple_xcframework_framework_attrib_split_transition_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> dict[str, PlatformInfo]:+ result = {}++ new_platforms = _normalize_platforms(attrs.platforms).items()+ for os_value, cpu_values in new_platforms:+ updated_constraints = _strip_os_sdk_and_runtime_constraints(platform, refs)++ canonical_platform_suffix = ""++ if os_value == "macos":+ canonical_platform_prefix = "macos"+ updated_constraints[refs.os[ConstraintSettingInfo].label] = refs.macos[ConstraintValueInfo]+ elif os_value == "iphoneos":+ canonical_platform_prefix = "ios"+ updated_constraints[refs.os[ConstraintSettingInfo].label] = refs.ios[ConstraintValueInfo]+ updated_constraints[refs.sdk[ConstraintSettingInfo].label] = refs.ios_device_sdk[ConstraintValueInfo]+ elif os_value == "watchos":+ canonical_platform_prefix = "watchos"+ updated_constraints[refs.os[ConstraintSettingInfo].label] = refs.watchos[ConstraintValueInfo]+ updated_constraints[refs.sdk[ConstraintSettingInfo].label] = refs.watchos_device_sdk[ConstraintValueInfo]+ elif os_value == "iphonesimulator":+ canonical_platform_prefix = "ios"+ canonical_platform_suffix = "simulator"+ updated_constraints[refs.os[ConstraintSettingInfo].label] = refs.ios[ConstraintValueInfo]+ updated_constraints[refs.sdk[ConstraintSettingInfo].label] = refs.ios_simulator_sdk[ConstraintValueInfo]+ elif os_value == "watchossimulator":+ canonical_platform_prefix = "watchos"+ canonical_platform_suffix = "simulator"+ updated_constraints[refs.os[ConstraintSettingInfo].label] = refs.watchos[ConstraintValueInfo]+ updated_constraints[refs.sdk[ConstraintSettingInfo].label] = refs.watchos_simulator_sdk[ConstraintValueInfo]+ elif os_value == "maccatalyst":+ canonical_platform_prefix = "ios"+ canonical_platform_suffix = "maccatalyst"+ updated_constraints[refs.os[ConstraintSettingInfo].label] = refs.ios[ConstraintValueInfo]+ updated_constraints[refs.sdk[ConstraintSettingInfo].label] = refs.maccatalyst_sdk[ConstraintValueInfo]+ updated_constraints[refs.runtime[ConstraintSettingInfo].label] = refs.maccatalyst_runtime[ConstraintValueInfo]+ else:+ fail("Unsupported OS value {} in apple_xcframework() platforms.".format(os_value))++ cpu_constraint_name = refs.cpu[ConstraintSettingInfo].label++ if len(cpu_values) > 1:+ updated_constraints[refs.universal[ConstraintSettingInfo].label] = refs.universal_enabled[ConstraintValueInfo]+ elif cpu_values[0] == "arm64":+ updated_constraints[cpu_constraint_name] = refs.arm64[ConstraintValueInfo]+ elif cpu_values[0] == "x86_64":+ updated_constraints[cpu_constraint_name] = refs.x86_64[ConstraintValueInfo]+ else:+ fail("Unsupported CPU value {} in apple_xcframework().".format(cpu_values[0]))++ new_cfg = ConfigurationInfo(+ constraints = updated_constraints,+ values = platform.configuration.values,+ )++ canonical_platform_name = canonical_platform_prefix + "-" + "_".join(cpu_values)+ if len(canonical_platform_suffix) > 0:+ canonical_platform_name += "-" + canonical_platform_suffix++ result.update({+ canonical_platform_name: PlatformInfo(+ label = canonical_platform_name + "_transition",+ configuration = new_cfg,+ )+ })++ return result++framework_split_transition = transition(+ impl = _apple_xcframework_framework_attrib_split_transition_impl,+ refs = {+ "arm32": "config//cpu/constraints:arm32",+ "arm64": "config//cpu/constraints:arm64",+ "cpu": "config//cpu/constraints:cpu",+ "ios": "config//os/constraints:iphoneos",+ "ios_device_sdk": "config//os/sdk/apple/constraints:iphoneos",+ "ios_simulator_sdk": "config//os/sdk/apple/constraints:iphonesimulator",+ "maccatalyst_runtime": "config//runtime/constraints:maccatalyst",+ "maccatalyst_sdk": "config//os/sdk/apple/constraints:maccatalyst",+ "macos": "config//os/constraints:macos",+ "os": "config//os/constraints:os",+ "runtime": "config//runtime/constraints:runtime",+ "sdk": "config//os/sdk/apple/constraints:_",+ "swift_library_evolution": "config//features/apple/constraints:swift_library_evolution",+ "swift_library_evolution_enabled": "config//features/apple/constraints:swift_library_evolution_enabled",+ "universal": "config//cpu/constraints:universal",+ "universal_enabled": "config//cpu/constraints:universal-enabled",+ "watchos": "config//os/constraints:watchos",+ "watchos_device_sdk": "config//os/sdk/apple/constraints:watchos",+ "watchos_simulator_sdk": "config//os/sdk/apple/constraints:watchsimulator",+ "x86_64": "config//cpu/constraints:x86_64",+ },+ attrs = [+ "platforms",+ ],+ split = True,+)
@@ -0,0 +1,123 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++def _os_constraint_value(platform: PlatformInfo, refs: struct) -> [None, ConstraintValueInfo]:+ return platform.configuration.constraints.get(refs.os[ConstraintSettingInfo].label)++def _sdk_constraint_value(platform: PlatformInfo, refs: struct) -> [None, ConstraintValueInfo]:+ return platform.configuration.constraints.get(refs.sdk[ConstraintSettingInfo].label)++def _cpu_constraint_readable_value(platform: PlatformInfo, refs: struct) -> [None, str]:+ cpu = platform.configuration.constraints.get(refs.cpu[ConstraintSettingInfo].label)+ if cpu == None:+ return platform.label++ if cpu.label == refs.arm64[ConstraintValueInfo].label:+ return "arm64"+ elif cpu.label == refs.x86_64[ConstraintValueInfo].label:+ return "x86_64"+ else:+ return platform.label++def _universal_constraint_value(platform: PlatformInfo, refs: struct) -> [None, bool]:+ universal = platform.configuration.constraints.get(refs.universal[ConstraintSettingInfo].label)+ return universal.label == refs.universal_enabled[ConstraintValueInfo].label if universal != None else False++def _filter_incompatible_constraints(platform_name: str, constraints: dict[TargetLabel, ConstraintValueInfo]) -> dict[TargetLabel, ConstraintValueInfo]:+ filtered = dict()+ for constraint_setting_label, constraint_value_info in constraints.items():+ incompatible_constraint_name = "//cpu/x86" if platform_name == "arm64" else "//cpu/arm"+ if incompatible_constraint_name in str(constraint_value_info.label):+ continue+ filtered[constraint_setting_label] = constraint_value_info+ return filtered++def _cpu_split_transition_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> dict[str, PlatformInfo]:+ universal = attrs.universal if attrs.universal != None else _universal_constraint_value(platform, refs)+ os = _os_constraint_value(platform, refs)+ if not universal or os == None:+ # Don't do the splitting, since we don't know what OS type this is.+ return {_cpu_constraint_readable_value(platform, refs): platform}++ os_label = os.label+ sdk = _sdk_constraint_value(platform, refs)+ sdk_label = sdk.label if sdk != None else None++ cpu_name_to_cpu_constraint = {}+ if os_label == refs.ios[ConstraintValueInfo].label:+ if sdk == None or sdk_label == refs.ios_simulator_sdk[ConstraintValueInfo].label or sdk_label == refs.maccatalyst_sdk[ConstraintValueInfo].label:+ # default to simulator if SDK is not specified+ cpu_name_to_cpu_constraint["arm64"] = refs.arm64[ConstraintValueInfo]+ cpu_name_to_cpu_constraint["x86_64"] = refs.x86_64[ConstraintValueInfo]+ elif sdk_label == refs.ios_device_sdk[ConstraintValueInfo].label:+ return {"arm64": platform}+ else:+ fail("Unsupported SDK {} for IPhoneOS".format(sdk_label))+ elif os_label == refs.watchos[ConstraintValueInfo].label:+ if sdk == None or sdk_label == refs.watchos_simulator_sdk[ConstraintValueInfo].label:+ cpu_name_to_cpu_constraint["arm64"] = refs.arm64[ConstraintValueInfo]+ elif sdk_label == refs.watchos_device_sdk[ConstraintValueInfo].label:+ cpu_name_to_cpu_constraint["arm64"] = refs.arm64[ConstraintValueInfo]+ cpu_name_to_cpu_constraint["arm64_32"] = refs.arm64_32[ConstraintValueInfo]+ else:+ fail("Unsupported SDK {} for WatchOS".format(sdk_label))+ elif os_label == refs.macos[ConstraintValueInfo].label:+ cpu_name_to_cpu_constraint["arm64"] = refs.arm64[ConstraintValueInfo]+ cpu_name_to_cpu_constraint["x86_64"] = refs.x86_64[ConstraintValueInfo]+ else:+ fail("Unsupported OS: {}".format(os_label))++ cpu_constraint_name = refs.cpu[ConstraintSettingInfo].label+ base_constraints = {+ constraint_setting_label: constraint_value_info+ for (constraint_setting_label, constraint_value_info) in platform.configuration.constraints.items()+ if constraint_setting_label != cpu_constraint_name+ }++ new_configs = {}+ for platform_name, cpu_constraint in cpu_name_to_cpu_constraint.items():+ updated_constraints = dict(base_constraints)+ updated_constraints[cpu_constraint_name] = cpu_constraint+ updated_constraints = _filter_incompatible_constraints(platform_name, updated_constraints)++ new_configs[platform_name] = PlatformInfo(+ label = platform_name,+ configuration = ConfigurationInfo(+ constraints = updated_constraints,+ values = platform.configuration.values,+ ),+ )++ return new_configs++cpu_split_transition = transition(+ impl = _cpu_split_transition_impl,+ refs = {+ "arm32": "config//cpu/constraints:arm32",+ "arm64": "config//cpu/constraints:arm64",+ "arm64_32": "config//cpu/constraints:arm64_32",+ "cpu": "config//cpu/constraints:cpu",+ "ios": "config//os/constraints:iphoneos",+ "ios_device_sdk": "config//os/sdk/apple/constraints:iphoneos",+ "ios_simulator_sdk": "config//os/sdk/apple/constraints:iphonesimulator",+ "maccatalyst_sdk": "config//os/sdk/apple/constraints:maccatalyst",+ "macos": "config//os/constraints:macos",+ "os": "config//os/constraints:os",+ "sdk": "config//os/sdk/apple/constraints:_",+ "universal": "config//cpu/constraints:universal",+ "universal_enabled": "config//cpu/constraints:universal-enabled",+ "watchos": "config//os/constraints:watchos",+ "watchos_device_sdk": "config//os/sdk/apple/constraints:watchos",+ "watchos_simulator_sdk": "config//os/sdk/apple/constraints:watchsimulator",+ "x86_64": "config//cpu/constraints:x86_64",+ },+ attrs = [+ "universal",+ ],+ split = True,+)
@@ -0,0 +1,39 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Apply a constraint that sets -enable-testing in Swift compilation.+"""++def enable_testing_transition_impl(platform: PlatformInfo, refs: struct) -> PlatformInfo:+ enable_testing_config = refs.enable_testing_setting[ConstraintSettingInfo].label+ enable_testing_constraint = refs.enable_testing_value[ConstraintValueInfo]+ if enable_testing_config in platform.configuration.constraints:+ # Don't apply the transition more than once+ return platform++ updated_constraints = platform.configuration.constraints+ updated_constraints[enable_testing_config] = enable_testing_constraint+ new_cfg = ConfigurationInfo(+ constraints = updated_constraints,+ values = platform.configuration.values,+ )+ return PlatformInfo(+ label = platform.label + "-enable-testing",+ configuration = new_cfg,+ )++enable_testing_transition_refs = {+ "enable_testing_setting": "config//features/apple/constraints:swift_enable_testing",+ "enable_testing_value": "config//features/apple/constraints:swift_enable_testing_enabled",+}++enable_testing_transition = transition(+ impl = enable_testing_transition_impl,+ refs = enable_testing_transition_refs,+)
@@ -0,0 +1,76 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_target_sdk_version.bzl", "get_target_sdk_version_map")+load("@prelude//transitions:utils.bzl", "transition_utils")+load("@prelude//utils:expect.bzl", "expect")++"""+Transition from catalyst SDK to macOS SDK. Used for AppKit extension bundle rules.+Transforms both OS and SDK constraints.+Only sanity check for source configuration is done.+"""++def _macos_transition_impl(platform: PlatformInfo, refs: struct) -> PlatformInfo:+ # This functions operates in the following way:+ # - Start with all the constraints from the platform and filter out the constraints for OS and SDK.+ # - Always set the new OS constraint to macOS.+ # - If the old SDK constraint was macCatalyst, replace with the equivalent macOS constraint.+ # - Return a new platform with the updated constraints.+ constraint_os = refs.os[ConstraintSettingInfo]+ is_os_macos = platform.configuration.constraints[constraint_os.label] == refs.os_macos[ConstraintValueInfo]+ constraint_sdk = refs.sdk[ConstraintSettingInfo]+ is_sdk_macos = platform.configuration.constraints.get(constraint_sdk.label) == refs.sdk_macos[ConstraintValueInfo]+ if is_os_macos and is_sdk_macos:+ # Don't apply the transition more than once+ return platform++ updated_constraints = transition_utils.filtered_platform_constraints(platform, [constraint_os.label, constraint_sdk.label])++ # Update OS constraint+ updated_constraints[constraint_os.label] = refs.os_macos[ConstraintValueInfo]++ # Update SDK constraint+ old_sdk = transition_utils.get_constraint_value(platform, constraint_sdk)+ maccatalyst_sdk = refs.sdk_maccatalyst[ConstraintValueInfo]++ if old_sdk != None:+ expect(+ old_sdk.label == maccatalyst_sdk.label,+ "If present, SDK transitioned non-identically to macOS should be `macCatalyst`, got {}".format(old_sdk.label),+ )+ updated_constraints[constraint_sdk.label] = refs.sdk_macos[ConstraintValueInfo]++ constraint_target_sdk_version = refs.target_sdk_version[ConstraintSettingInfo]+ old_target_sdk_version = transition_utils.get_constraint_value(platform, constraint_target_sdk_version)+ if old_target_sdk_version != None:+ # Get last part of constraint as macCatalyst version+ maccatalyst_version = str(old_target_sdk_version.label).split("-")[-1]++ # Replace target-sdk-version constraint with macOS equivalent from mapping+ updated_constraints[constraint_target_sdk_version.label] = getattr(refs, maccatalyst_version)[ConstraintValueInfo]++ new_cfg = ConfigurationInfo(+ constraints = updated_constraints,+ values = platform.configuration.values,+ )+ return PlatformInfo(+ label = "macos_transition",+ configuration = new_cfg,+ )++refs = {+ "os": "config//os/constraints:os",+ "os_macos": "config//os/constraints:macos",+ "sdk": "config//os/sdk/apple/constraints:_",+ "sdk_maccatalyst": "config//os/sdk/apple/constraints:maccatalyst",+ "sdk_macos": "config//os/sdk/apple/constraints:macosx",+ "target_sdk_version": "config//version:constraint-setting-target-sdk-version",+}+refs.update(get_target_sdk_version_map())+macos_transition = transition(impl = _macos_transition_impl, refs = refs)
@@ -0,0 +1,91 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//apple:resource_groups.bzl",+ "ResourceGraphNode", # @unused Used as a type+ "ResourceGroupInfo",+ "create_resource_graph",+ "get_resource_graph_node_map_func",+)+load(+ "@prelude//cxx:groups.bzl",+ "compute_mappings",+ "create_group",+ "get_roots_from_mapping",+ "make_info_subtarget_providers",+ "parse_groups_definitions",+)+load(+ "@prelude//cxx:groups_types.bzl",+ "GroupMapping", # @unused Used as a type+)+load("@prelude//utils:utils.bzl", "flatten")++def resource_group_map_impl(ctx: AnalysisContext) -> list[Provider]:+ resource_groups = parse_groups_definitions(ctx.attrs.map, lambda root: root.label)++ resource_group_to_implicit_deps_mapping = {group: flatten([get_roots_from_mapping(mapping) for mapping in mappings]) for group, mappings in ctx.attrs.map}+ flattend_resource_group_deps = flatten(resource_group_to_implicit_deps_mapping.values())++ resource_graph = create_resource_graph(+ ctx = ctx,+ labels = [],+ deps = flattend_resource_group_deps,+ exported_deps = [],+ )+ resource_graph_node_map = get_resource_graph_node_map_func(resource_graph)()+ mappings = compute_mappings(+ groups_map = {+ group.name: create_group(+ group = group,+ # User provided mappings may contain entries that don't support+ # ResourceGraphInfo, which `create_resource_graph` removes above.+ # So make sure we remove them from the mappings too, otherwise+ # `compute_mappings` crashes on the inconsistency.+ mappings = filter(+ None,+ [_fixup_mapping_to_only_include_roots_in_the_map(m, resource_graph_node_map) for m in group.mappings],+ ),+ )+ for group in resource_groups+ },+ graph_map = resource_graph_node_map,+ )+ return [+ DefaultInfo(+ sub_targets = {+ "info": make_info_subtarget_providers(ctx, resource_groups, mappings),+ }+ ),+ ResourceGroupInfo(+ groups = resource_groups,+ groups_hash = hash(str(resource_groups)),+ mappings = mappings,+ # The consumer of this info may not have deps that cover that labels+ # referenced in our roots, so propagate them here.+ # NOTE(agallagher): We do this to maintain existing behavior here+ # but it's not clear if it's actually desirable behavior.+ resource_group_to_implicit_deps_mapping = resource_group_to_implicit_deps_mapping,+ ),+ ]++def _fixup_mapping_to_only_include_roots_in_the_map(mapping: GroupMapping, node_map: dict[Label, ResourceGraphNode]) -> GroupMapping | None:+ if not mapping.roots:+ return mapping++ filtered_roots = [root for root in mapping.roots if root in node_map]+ if not filtered_roots:+ return None++ return GroupMapping(+ roots = filtered_roots,+ traversal = mapping.traversal,+ filters = mapping.filters,+ preferred_linkage = mapping.preferred_linkage,+ )
@@ -0,0 +1,67 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Apply a constraint if the minimum_os_version attribute is set.+This overrides any existing target_sdk_version select.+"""++load("@prelude//apple:versions.bzl", "TARGET_SDK_VERSIONS")+load("@prelude//apple/user:enable_testing_transition.bzl", "enable_testing_transition_impl", "enable_testing_transition_refs")++def _target_sdk_version_transition_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> PlatformInfo:+ target_sdk_version = attrs.minimum_os_version+ if not target_sdk_version:+ return platform++ constraint_label = refs.version[ConstraintSettingInfo].label+ constraint_value = platform.configuration.constraints.get(constraint_label)+ version_provider = getattr(refs, target_sdk_version, None)+ if version_provider == None:+ fail("target sdk version {} is missing constraints".format(target_sdk_version))++ version_constraint = version_provider[ConstraintValueInfo]+ if constraint_value == version_constraint:+ return platform++ updated_constraints = platform.configuration.constraints+ updated_constraints[constraint_label] = version_constraint+ new_cfg = ConfigurationInfo(+ constraints = updated_constraints,+ values = platform.configuration.values,+ )+ return PlatformInfo(+ label = platform.label + "_target_sdk_version_" + target_sdk_version,+ configuration = new_cfg,+ )++def _target_sdk_version_and_enable_testing_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> PlatformInfo:+ platform_info = _target_sdk_version_transition_impl(platform, refs, attrs)+ platform_info = enable_testing_transition_impl(platform_info, refs)+ return platform_info++_target_sdk_version_transition_refs = {version: "@config//version:constraint-value-target-sdk-version-" + version for version in TARGET_SDK_VERSIONS} | {+ "version": "@config//version:constraint-setting-target-sdk-version"+}++_target_sdk_version_attrs = ["minimum_os_version"]++target_sdk_version_transition = transition(+ impl = _target_sdk_version_transition_impl,+ refs = _target_sdk_version_transition_refs,+ attrs = _target_sdk_version_attrs,+)++# apple_test requires both enable_testing and target_sdk_version+# applied as an incoming transition, so we chain the transitions+# in this implementation.+apple_test_target_sdk_version_transition = transition(+ impl = _target_sdk_version_and_enable_testing_impl,+ refs = enable_testing_transition_refs | _target_sdk_version_transition_refs,+ attrs = _target_sdk_version_attrs,+)
@@ -0,0 +1,84 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Transition from iOS to watchOS. Used for watchOS bundle rule.+Transforms both OS and SDK constraints.+Only sanity check for source configuration is done.+"""++load("@prelude//transitions:utils.bzl", "transition_utils")+load("@prelude//utils:expect.bzl", "expect")++def _watch_transition_impl(platform: PlatformInfo, refs: struct) -> PlatformInfo:+ # This functions operates in the following way:+ # - Start with all the constraints from the platform and filter out the constraints for OS and SDK.+ # - If the old OS constraint was iOS or watchOS, set the new constraint to be always watchOS.+ # - If the old SDK constraint was iOS, replace with the equivalent watchOS constraint.+ # - Return a new platform with the updated constraints.+ constraint_settings_to_remove = [+ refs.os[ConstraintSettingInfo].label,+ refs.sdk[ConstraintSettingInfo].label,+ ]+ # @oss-disable[end= ]: constraint_settings_to_remove.append(refs.memory_profiler[ConstraintValueInfo].setting.label)+ updated_constraints = transition_utils.filtered_platform_constraints(platform, constraint_settings_to_remove)++ # Update OS constraint+ old_os = transition_utils.get_constraint_value(platform, refs.os[ConstraintSettingInfo])+ watchos = refs.watchos[ConstraintValueInfo]+ ios = refs.ios[ConstraintValueInfo]+ if old_os != None:+ expect(+ old_os.label in [watchos.label, ios.label],+ "If present, OS transitioned non-identically to watchOS should be `iphoneos`, got {}".format(old_os.label),+ )+ updated_constraints[refs.os[ConstraintSettingInfo].label] = watchos++ # Update SDK constraint+ old_sdk = transition_utils.get_constraint_value(platform, refs.sdk[ConstraintSettingInfo])+ watchos_device_sdk = refs.watchos_device_sdk[ConstraintValueInfo]+ watchos_simulator_sdk = refs.watchos_simulator_sdk[ConstraintValueInfo]+ ios_device_sdk = refs.ios_device_sdk[ConstraintValueInfo]+ ios_simulator_sdk = refs.ios_simulator_sdk[ConstraintValueInfo]+ is_simulator = True+ if old_sdk != None:+ if old_sdk.label == watchos_simulator_sdk.label:+ pass+ elif old_sdk.label == watchos_device_sdk.label:+ is_simulator = False+ elif old_sdk.label == ios_simulator_sdk.label:+ pass+ elif old_sdk.label == ios_device_sdk.label:+ is_simulator = False+ else:+ fail("If present, SDK transitioned non-identically to watchOS should be either `iphoneos` or `iphonesimulator`, got {}".format(old_sdk.label))+ updated_constraints[refs.sdk[ConstraintSettingInfo].label] = watchos_simulator_sdk if is_simulator else watchos_device_sdk++ new_cfg = ConfigurationInfo(+ constraints = updated_constraints,+ values = platform.configuration.values,+ )+ return PlatformInfo(+ label = "watch_transition",+ configuration = new_cfg,+ )++watch_transition = transition(+ impl = _watch_transition_impl,+ refs = {+ "ios": "config//os/constraints:iphoneos",+ "ios_device_sdk": "config//os/sdk/apple/constraints:iphoneos",+ "ios_simulator_sdk": "config//os/sdk/apple/constraints:iphonesimulator",+ # @oss-disable[end= ]: "memory_profiler": "config//build_mode/apple/constraints:enable-memory-profiler-constraint-value",+ "os": "config//os/constraints:os",+ "sdk": "config//os/sdk/apple/constraints:_",+ "watchos": "config//os/constraints:watchos",+ "watchos_device_sdk": "config//os/sdk/apple/constraints:watchos",+ "watchos_simulator_sdk": "config//os/sdk/apple/constraints:watchsimulator",+ },+)
@@ -0,0 +1,103 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactTSet", # @unused Used as a type+)+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")++_AnalysisInput = record(+ argsfile = field(Artifact),+ identifier = field(int),+)++def get_required_reasons_validator_output(ctx, artifacts: ArtifactTSet) -> Artifact | None:+ if not ctx.attrs.validate_rrapi_usage:+ return None++ label_to_input_artifacts = _get_analysis_input_artifacts(ctx, artifacts)+ if not label_to_input_artifacts:+ return None++ required_reasons_tools = ctx.attrs._apple_toolchain[AppleToolchainInfo].required_reasons_tools+ label_to_analysis_artifacts = _analyze_artifacts(+ ctx,+ "required_reasons_usage",+ required_reasons_tools.analyzer,+ label_to_input_artifacts,+ )+ return _validate_analysis_artifacts(+ ctx,+ "required_reasons_usage",+ required_reasons_tools.validator,+ label_to_analysis_artifacts,+ )++def _get_analysis_input_artifacts(ctx, artifacts: ArtifactTSet) -> dict[Label, list[_AnalysisInput]]:+ underlying_tset = artifacts._tset+ if underlying_tset == None:+ return {}++ results = {}+ identifier = 0+ for infos in underlying_tset.traverse():+ for info in infos:+ argsfile = ctx.actions.write(+ "artifacts-{}.txt".format(identifier),+ info.artifacts,+ with_inputs = True,+ has_content_based_path = False,+ )+ results.setdefault(info.label, []).append(+ _AnalysisInput(argsfile = argsfile, identifier = identifier),+ )+ identifier += 1+ return results++def _analyze_artifacts(ctx, key: str, analysis_tool: RunInfo, label_to_artifacts: dict[Label, list[_AnalysisInput]]) -> dict[Label, list[Artifact]]:+ label_to_analysis = {}+ for label, inputs in label_to_artifacts.items():+ for input in inputs:+ output = ctx.actions.declare_output("{}_{}.json".format(key, input.identifier), has_content_based_path = False)+ ctx.actions.run(+ cmd_args([+ analysis_tool,+ "--artifacts",+ cmd_args(input.argsfile, format = "@{}"),+ "--output",+ output.as_output(),+ ]),+ category = "{}_analysis".format(key),+ identifier = "{}_{}".format(ctx.attrs.name, input.identifier),+ )+ label_to_analysis.setdefault(label, []).append(output)++ return label_to_analysis++def _validate_analysis_artifacts(ctx, key: str, validator_tool: RunInfo, label_to_artifacts: dict[Label, list[Artifact]]) -> Artifact:+ input_json = ctx.actions.write_json(+ "{}_validator_args.json".format(key),+ label_to_artifacts,+ with_inputs = True,+ has_content_based_path = False,+ )++ output = ctx.actions.declare_output("{}.json".format(key), has_content_based_path = False)+ ctx.actions.run(+ cmd_args([+ validator_tool,+ "--analysis-json-path",+ input_json,+ "--output",+ output.as_output(),+ ]),+ category = "{}_validate".format(key),+ identifier = ctx.attrs.name,+ )+ return output
@@ -0,0 +1,31 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# Tools used to validate Apple Required Reasons API (RRAPI) usage against the+# declared `.xcprivacy` privacy manifest. Whether they run is decided by the+# consuming rule.+RequiredReasonsToolsInfo = provider(+ fields = {+ # Consumes a target's own debug artifacts and emits a per-target+ # analysis JSON of the RRAPI symbols it references.+ "analyzer": provider_field(RunInfo),+ # Consumes the per-target analysis JSONs surviving in a bundle and+ # emits a single ValidationSpec result, applying the allowlist /+ # exemption checks.+ "validator": provider_field(RunInfo),+ },+)++def required_reasons_tools_impl(ctx: AnalysisContext) -> list[Provider]:+ return [+ DefaultInfo(),+ RequiredReasonsToolsInfo(+ analyzer = ctx.attrs.analyzer[RunInfo],+ validator = ctx.attrs.validator[RunInfo],+ ),+ ]
@@ -0,0 +1,125 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "make_artifact_tset",+ "stringify_artifact_label",+)+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")+load("@prelude//apple/swift:swift_types.bzl", "SwiftDependencyInfo")++# Backs the apple_bundle `[swiftmodule-change-analysis]` subtarget+def get_swiftmodule_change_analysis_output(ctx: AnalysisContext, deps: list[Dependency]) -> Artifact | None:+ apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]++ if apple_tools.swiftmodule_change_analysis == None:+ return None++ swiftmodule_change_analysis_tsets = [dep[SwiftDependencyInfo].swiftmodule_change_analysis_tset for dep in deps if SwiftDependencyInfo in dep]+ if not swiftmodule_change_analysis_tsets:+ return None++ tset = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ children = swiftmodule_change_analysis_tsets,+ )+ if tset._tset == None:+ return None++ label_to_artifacts = {}+ for infos in tset._tset.traverse():+ for info in infos:+ label_to_artifacts.setdefault(stringify_artifact_label(info.label), []).extend(info.artifacts)++ if not label_to_artifacts:+ return None++ manifest = ctx.actions.write_json(+ "swiftmodule_change_analysis/manifest.json",+ label_to_artifacts,+ # with_inputs = True here means any change to a dependency's+ # swiftmodule will re-trigger this action.+ with_inputs = True,+ has_content_based_path = False,+ )++ # Only populated when `apple.swift_dump_ast_subtarget_enabled` is set, so+ # this is `None` for the vast majority of builds. Ignored by the default+ # bootstrap tool; consumed by richer out-of-tree implementations (see+ # `apple.swiftmodule_change_analysis` buckconfig) that classify changes+ # via AST diffing instead of a raw `.swiftinterface` text diff.+ ast_dump_tsets = [dep[SwiftDependencyInfo].swift_ast_dump_tset for dep in deps if SwiftDependencyInfo in dep]+ ast_tset = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ children = ast_dump_tsets,+ )+ ast_manifest = None+ if ast_tset._tset != None:+ label_to_ast_artifacts = {}+ for infos in ast_tset._tset.traverse():+ for info in infos:+ if info.artifacts:+ label_to_ast_artifacts.setdefault(stringify_artifact_label(info.label), []).extend(info.artifacts)++ if label_to_ast_artifacts:+ ast_manifest = ctx.actions.write_json(+ "swiftmodule_change_analysis/ast_manifest.json",+ label_to_ast_artifacts,+ with_inputs = True,+ has_content_based_path = False,+ )++ # Not content-addressed, and `no_outputs_cleanup` below keeps this file+ # around across runs, so the checker can compare the current state+ # against what it saw the last time this action ran.+ state = ctx.actions.declare_output("swiftmodule_change_analysis/state.json", has_content_based_path = False)+ output = ctx.actions.declare_output("swiftmodule_change_analysis/differences.json", has_content_based_path = False)++ swiftmodule_change_analysis_tool = apple_tools.swiftmodule_change_analysis++ command = cmd_args([+ swiftmodule_change_analysis_tool,+ "--target",+ stringify_artifact_label(ctx.label),+ "--manifest",+ manifest,+ "--state",+ state.as_output(),+ "--output",+ output.as_output(),+ ])++ if ast_manifest:+ command.add("--ast-manifest", ast_manifest)++ # The manifest only bakes in each artifact's *path*; without also listing+ # them as hidden inputs here, Buck2 wouldn't know this action actually+ # depends on their content, and `metadata_path` below wouldn't include+ # their digests.+ command.add(cmd_args(hidden = [artifact for artifacts in label_to_artifacts.values() for artifact in artifacts]))++ ctx.actions.run(+ command,+ category = "swiftmodule_change_analysis",+ identifier = ctx.attrs.name,+ # prefer_local as only the local action will do anything useful+ prefer_local = True,+ allow_cache_upload = False,+ no_outputs_cleanup = True,+ # Buck2 already knows a content digest for every one of this+ # action's inputs (it needs one for its own caching); this hands+ # them to the tool as a `path -> digest` JSON file so it can compare+ # digests instead of reading and hashing `.swiftmodule` files itself.+ metadata_env_var = "SWIFTMODULE_CHANGE_ANALYSIS_METADATA",+ metadata_path = "swiftmodule_change_analysis/action_metadata.json",+ )++ return output
@@ -0,0 +1,47 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# All the target SDK versions currently in use.+TARGET_SDK_VERSIONS = [+ "1.0",+ "4.0",+ "7.0",+ "8.0",+ "9.0",+ "10.0",+ "10.10",+ "10.12",+ "10.13",+ "10.14",+ "10.15",+ "11.0",+ "11.3",+ "12.0",+ "12.1",+ "12.4",+ "13.0",+ "13.1",+ "13.3",+ "13.4",+ "14.0",+ "14.2",+ "15.0",+ "15.1",+ "15.2",+ "15.5",+ "16.0",+ "16.1",+ "16.3",+ "17.0",+ "17.2",+ "17.4",+ "18.0",+ "18.4",+ "26.0",+ "26.1",+]
@@ -0,0 +1,25 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# @oss-disable[end= ]: # Asset symbol hooks implemented in meta_only; open source gets no-op stubs.++# @oss-disable[end= ]: load("@prelude//apple/meta_only:meta_xcassets_asset_symbol_spec.bzl", _MetaXcassetsAssetSymbolSpec = "MetaXcassetsAssetSymbolSpec")+# @oss-disable[end= ]: load(+ # @oss-disable[end= ]: "@prelude//apple/meta_only:meta_xcassets_asset_symbol_usage.bzl",+ # @oss-disable[end= ]: _usage_providers_and_subtargets = "meta_xcassets_asset_symbol_usage_providers_and_subtargets",+# @oss-disable[end= ]: )+load("@prelude//cxx:cxx_sources.bzl", "CxxSrcWithFlags")++# @oss-disable[end= ]: MetaXcassetsAssetSymbolSpec = _MetaXcassetsAssetSymbolSpec+MetaXcassetsAssetSymbolSpec = record() # @oss-enable++def meta_xcassets_asset_symbol_usage_providers_and_subtargets(+ ctx: AnalysisContext, cxx_srcs: list[CxxSrcWithFlags], swift_srcs: list[CxxSrcWithFlags]+) -> (list[Provider], dict[str, list[Provider]]):+ # @oss-disable[end= ]: return _usage_providers_and_subtargets(ctx, cxx_srcs, swift_srcs)+ return [], {} # @oss-enable
@@ -0,0 +1,69 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_sdk.bzl", "get_apple_sdk_name")+load("@prelude//apple:apple_target_sdk_version.bzl", "get_min_deployment_version_for_node")+load("@prelude//apple:apple_utility.bzl", "get_apple_architecture", "has_apple_toolchain")+load(+ "@prelude//cxx:argsfiles.bzl",+ "CompileArgsfile", # @unused Used as a type+)+load(+ "@prelude//cxx:cxx_sources.bzl",+ "CxxSrcWithFlags", # @unused Used as a type+)+load("@prelude//cxx:xcode.bzl", "cxx_populate_xcode_attributes")+load("@prelude//ide_integrations/xcode:data.bzl", "XcodeDataInfoKeys")+load("@prelude//utils:expect.bzl", "expect")++def apple_populate_xcode_attributes(+ ctx, srcs: list[CxxSrcWithFlags], argsfiles: dict[str, CompileArgsfile], product_name: str, contains_swift_sources: bool = False+) -> dict[str, typing.Any]:+ data = cxx_populate_xcode_attributes(ctx = ctx, srcs = srcs, argsfiles = argsfiles, product_name = product_name)++ data[XcodeDataInfoKeys.CONTAINS_SWIFT_SOURCES] = contains_swift_sources++ if has_apple_toolchain(ctx):+ data[XcodeDataInfoKeys.ARCH] = get_apple_architecture(ctx)+ data[XcodeDataInfoKeys.SDK] = get_apple_sdk_name(ctx)+ data[XcodeDataInfoKeys.DEPLOYMENT_VERSION] = get_min_deployment_version_for_node(ctx)++ if hasattr(ctx.attrs, "swift_version"):+ swift_version = ctx.attrs.swift_version+ if swift_version != None:+ data[XcodeDataInfoKeys.SWIFT_VERSION] = swift_version++ apple_xcode_data_add_xctoolchain(ctx, data)+ return data++def apple_xcode_data_add_xctoolchain(ctx: AnalysisContext, data: dict[str, typing.Any]):+ _add_label_for_attr(ctx, "_apple_xctoolchain_bundle_id", "xctoolchain_bundle_id_target", data)+ _add_output_for_attr(ctx, "_apple_xctoolchain_bundle_id", "xctoolchain_bundle_id", data)+ _add_label_for_attr(ctx, "_apple_xctoolchain", "xctoolchain_bundle_target", data)++def _add_label_for_attr(ctx: AnalysisContext, attr_name: str, field_name: str, data: dict[str, typing.Any]):+ xctoolchain_dep = _get_attribute_with_output(ctx, attr_name)+ if xctoolchain_dep:+ data[field_name] = xctoolchain_dep.label++def _add_output_for_attr(ctx: AnalysisContext, attr_name: str, field_name: str, data: dict[str, typing.Any]):+ xctoolchain_dep = _get_attribute_with_output(ctx, attr_name)+ if xctoolchain_dep:+ default_info = xctoolchain_dep[DefaultInfo]+ expect(len(default_info.default_outputs) == 1, "Expected only one output, got {}", len(default_info.default_outputs))+ data[field_name] = default_info.default_outputs[0]++def _get_attribute_with_output(ctx: AnalysisContext, attr_name: str) -> [Dependency, None]:+ if hasattr(ctx.attrs, attr_name):+ dep = getattr(ctx.attrs, attr_name)+ default_info = dep[DefaultInfo]+ if len(default_info.default_outputs) > 0:+ # When there's no xctoolchain, there will be an empty `DefaultInfo`.+ # So, an empty `DefaultInfo` basically signifies that there's no xctoolchain.+ return dep+ return None
@@ -0,0 +1,37 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//cxx:cxx_library_utility.bzl", "cxx_attr_deps", "cxx_attr_exported_deps")+load(":apple_frameworks.bzl", "to_framework_name")++# Provider which helps to propagate the info if XCTest Swift support is needed up the target graph.+XCTestSwiftSupportInfo = provider(+ # @unsorted-dict-items+ fields = {+ "support_needed": provider_field(bool),+ # Value is unused, needed only to detect a provider type+ },+)++def xctest_swift_support_info(ctx: AnalysisContext, contains_swift_sources: bool, is_test_target: bool) -> XCTestSwiftSupportInfo:+ if contains_swift_sources and (is_test_target or _depends_on_xctest(ctx)):+ return XCTestSwiftSupportInfo(support_needed = True)+ else:+ return _inherited_xctest_swift_support_info(ctx)++def _inherited_xctest_swift_support_info(ctx: AnalysisContext) -> XCTestSwiftSupportInfo:+ all_deps = cxx_attr_deps(ctx) + cxx_attr_exported_deps(ctx)+ for dep in all_deps:+ if XCTestSwiftSupportInfo in dep:+ info = dep[XCTestSwiftSupportInfo]+ if info.support_needed:+ return info+ return XCTestSwiftSupportInfo(support_needed = False)++def _depends_on_xctest(ctx: AnalysisContext) -> bool:+ return "XCTest" in [to_framework_name(x) for x in ctx.attrs.frameworks]
@@ -0,0 +1,114 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//utils:expect.bzl", "expect")+load("@prelude//utils:type_defs.bzl", "is_list")+load(+ "@prelude//utils:utils.bzl",+ "flatten",+)++# Generic tag to provide more information about the artifact+ArtifactInfoTag = enum(+ # Describes artifacts required for debugging Swift code, including+ # swiftmodule files, swiftinterface files, clang modules and modulemaps.+ "swift_debug_info",+)++ArtifactInfo = record(+ label = field(Label),+ artifacts = field(list[Artifact]),+ tags = field(list[ArtifactInfoTag]),+)++def stringify_artifact_label(value: Label | str) -> str:+ if type(value) == "string":+ return value+ return str(value.raw_target())++def _get_artifacts(entries: list[ArtifactInfo]) -> list[Artifact]:+ return flatten([entry.artifacts for entry in entries])++_ArtifactTSet = transitive_set(+ args_projections = {+ "artifacts": _get_artifacts,+ },+)++ArtifactTSet = record(+ _tset = field([_ArtifactTSet, None], None),+)++# Simple empty `ArtifactTSet` that is shared to reduce memory usage.+EmptyArtifactTSet = ArtifactTSet()++def make_artifact_tset(+ actions: AnalysisActions,+ # Must be non-`None` if artifacts are passed in to `artifacts`.+ label: Label | None = None,+ artifacts: list[Artifact] = [],+ infos: list[ArtifactInfo] = [],+ children: list[ArtifactTSet] = [],+ tags: list[ArtifactInfoTag] = [],+) -> ArtifactTSet:+ expect(+ label != None or not artifacts,+ "must pass in `label` to associate with artifacts",+ )++ single_child = None # type: ArtifactTSet | None+ children_orig = children+ children = [] # type: list[_ArtifactTSet]+ for c in children_orig:+ # As a convenience for our callers, filter our `None` children.+ if c._tset != None:+ children.append(c._tset)+ single_child = c++ has_values = artifacts or infos+ if not has_values and not children:+ return EmptyArtifactTSet++ if not has_values and len(children) == 1:+ # If we have a single child, just return it+ # rather than allocating and retaining additional memory.+ return single_child++ # Build list of all non-child values.+ values = []+ if artifacts:+ values.append(ArtifactInfo(label = label, artifacts = artifacts, tags = tags))+ values.extend(infos)++ # We only build a `_ArtifactTSet` if there's something to package.+ kwargs = {}+ if values:+ kwargs["value"] = values+ if children:+ kwargs["children"] = children+ return ArtifactTSet(+ _tset = actions.tset(_ArtifactTSet, **kwargs),+ )++def project_artifacts(actions: AnalysisActions, tsets: ArtifactTSet | list[ArtifactTSet] = []) -> list[TransitiveSetArgsProjection]:+ """+ Helper to project a list of optional tsets.+ """++ if is_list(tsets):+ tset = make_artifact_tset(+ actions = actions,+ children = tsets,+ )+ else:+ tset = tsets++ if tset._tset == None:+ return []++ return [tset._tset.project_as_args("artifacts")]
@@ -0,0 +1,176 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load("@prelude//dist:dist_info.bzl", "DistInfo")+load("@prelude//utils:arglike.bzl", "ArgLike") # @unused Used as a type+load("@prelude//utils:expect.bzl", "expect")++# A group of artifacts.+ArtifactGroupInfo = provider(+ fields = {+ "artifacts": provider_field(typing.Any, default = None), # ["artifact"]+ },+)++ArtifactOutputs = record(+ # Single output. This is the artifact whose path would go into the resources+ # JSON when this artifact is used as a resource.+ default_output = field(Artifact),+ # Other artifacts which need to be present in order to run the resource as+ # an executable. This includes shared library dependencies and resources.+ nondebug_runtime_files = field(list[ArgLike]),+ # Other outputs that would be materialized if this artifact is the output of+ # a build, or generally in any context where a user might run this artifact+ # in a debugger.+ #+ # This is a superset of nondebug_runtime_files and also includes external+ # debuginfo.+ other_outputs = field(list[ArgLike]),+)++# Wrapper to support wrapping `Artifact`s referencing paths behind external+# symlinks.+ArtifactExt = record(+ artifact = field(Artifact),+ # If the `artifact` above is a symlink referencing an external path, this+ # is an optional sub-path to append when accessing the path.+ sub_path = field(str | None, None),+ # Returns the resolved path as a `cmd_arg()`, with the optional sub-path+ # appended.+ as_arg = field(typing.Callable),+ join = field(typing.Callable),+)++# A Provider that mirrors `DefaultInfo` for `Artifact` outputs, but allows+# specifying an `ArtifactExt` as it's default output.+DefaultOutputExt = provider(+ fields = dict(+ default_output = provider_field(ArtifactExt),+ ),+)++def single_artifact(dep: Artifact | Dependency) -> ArtifactOutputs:+ if isinstance(dep, Artifact):+ return ArtifactOutputs(+ default_output = dep,+ nondebug_runtime_files = [],+ other_outputs = [],+ )++ if DefaultInfo in dep:+ info = dep[DefaultInfo]+ expect(+ len(info.default_outputs) == 1,+ "expected exactly one default output from {} ({})".format(dep, info.default_outputs),+ )+ default_output = info.default_outputs[0]+ other_outputs = info.other_outputs++ dist_info = dep.get(DistInfo)+ nondebug_runtime_files = dist_info.nondebug_runtime_files if dist_info else other_outputs++ return ArtifactOutputs(+ default_output = default_output,+ nondebug_runtime_files = nondebug_runtime_files,+ other_outputs = other_outputs,+ )++ fail("unexpected dependency type: {}".format(type(dep)))++def unpack_artifacts(artifacts: list[Artifact | Dependency]) -> list[ArtifactOutputs]:+ """+ Unpack a heterogeneous list of Artifact and ArtifactGroupInfo into a list+ representing their outputs.+ """++ out = []++ for artifact in artifacts:+ if isinstance(artifact, Artifact):+ out.append(+ ArtifactOutputs(+ default_output = artifact,+ nondebug_runtime_files = [],+ other_outputs = [],+ )+ )+ continue++ if ArtifactGroupInfo in artifact:+ for artifact in artifact[ArtifactGroupInfo].artifacts:+ out.append(+ ArtifactOutputs(+ default_output = artifact,+ nondebug_runtime_files = [],+ other_outputs = [],+ )+ )+ continue++ out.append(single_artifact(artifact))++ return out++def unpack_artifact_map(artifacts: dict[str, Artifact | Dependency]) -> dict[str, ArtifactOutputs]:+ """+ Unpack a heterogeneous dict of Artifact and ArtifactGroupInfo into a dict+ representing their outputs.+ """++ out = {}++ for name, artifact in artifacts.items():+ if isinstance(artifact, Artifact):+ out[name] = ArtifactOutputs(+ default_output = artifact,+ nondebug_runtime_files = [],+ other_outputs = [],+ )+ continue++ if ArtifactGroupInfo in artifact:+ for artifact in artifact[ArtifactGroupInfo].artifacts:+ out[paths.join(name, artifact.short_path)] = ArtifactOutputs(+ default_output = artifact,+ nondebug_runtime_files = [],+ other_outputs = [],+ )+ continue++ out[name] = single_artifact(artifact)++ return out++def _as_arg(artifact: Artifact, sub_path: str | None) -> ArgLike:+ if sub_path == None:+ return artifact+ return cmd_args(artifact, format = "{{}}/{}".format(sub_path))++def artifact_ext(artifact: Artifact, sub_path: str | None = None) -> ArtifactExt:+ return ArtifactExt(+ artifact = artifact,+ sub_path = sub_path,+ as_arg = lambda: _as_arg(artifact, sub_path),+ join = lambda p: artifact_ext(+ artifact = artifact,+ sub_path = p if sub_path == None else paths.join(sub_path, p),+ ),+ )++def to_artifact_ext(src: Artifact | Dependency) -> ArtifactExt:+ if isinstance(src, Dependency):+ ext = src.get(DefaultOutputExt)+ if ext != None:+ return ext.default_output+ else:+ (src,) = src[DefaultInfo].default_outputs+ return artifact_ext(src)++def to_arglike(src: Artifact | Dependency) -> ArgLike:+ return to_artifact_ext(src).as_arg()
@@ -0,0 +1,34 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++def _equals(expected, actual, msg = None):+ if expected != actual:+ if msg == None:+ fail("expected: {}, got: {}".format(expected, actual))+ else:+ fail("{}: expected: {}, got: {}".format(msg, expected, actual))++def _true(condition, msg = None):+ if not condition:+ if msg != None:+ fail(msg)+ else:+ fail("Condition is not met")++def _false(condition, msg = None):+ if condition:+ if msg != None:+ fail(msg)+ else:+ fail("Condition is expected to be false")++asserts = struct(+ equals = _equals,+ true = _true,+ false = _false,+)
@@ -0,0 +1,9 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# The specs you are looking for have moved into the prelude/decls directory
@@ -0,0 +1,60 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++_ATTRS_VALIDATORS_NAME = "attrs_validators"++AttrsValidatorsInfo = provider(+ fields = {+ "func": typing.Callable[[AnalysisActions, Label, struct], dict[str, Artifact]],+ },+)++def get_attrs_validation_specs(ctx: AnalysisContext) -> list[ValidationSpec]:+ validators = getattr(ctx.attrs, _ATTRS_VALIDATORS_NAME, [])+ if not validators:+ return []++ specs = []+ for validator in validators:+ for name, output in validator[AttrsValidatorsInfo].func(ctx.actions, ctx.label, ctx.attrs).items():+ specs.append(ValidationSpec(name = name, validation_result = output))++ return specs++def _attrs_validators_arg():+ return {+ _ATTRS_VALIDATORS_NAME: attrs.option(+ attrs.list(attrs.dep(providers = [AttrsValidatorsInfo])),+ default = None,+ ),+ }++def _validation_specs_arg():+ return {+ "validation_specs": attrs.dict(+ attrs.string(),+ attrs.source(+ doc = """+ An artifact pointing to a JSON file that will be used in ValidationSpec.+ {+ "version": 1,+ "data": {+ "message": "What goes in stderr",+ "status": "success" | "failure",+ }+ } + """+ ),+ default = {},+ ),+ }++validation_common = struct(+ attrs_validators_arg = _attrs_validators_arg,+ validation_specs_arg = _validation_specs_arg,+)
@@ -0,0 +1,12 @@+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("build_infra")++source_listing()++# No-op in OSS.++config_setting(+ name = "arvr_mode",+ visibility = ["PUBLIC"],+)
@@ -0,0 +1,32 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Utils functions for working with `ctx.output.ensure/ensure_multiple` in bxl.+"""++def ensure_default_info(ctx: bxl.Context, default_info: DefaultInfo, with_other_outputs: bool = False) -> None:+ """+ Ensures all outputs of the given DefaultInfo.++ Parameters:+ - `ctx`: The bxl context.+ - `default_info`: The `DefaultInfo` to ensure.+ - `with_other_outputs`: Whether to also ensure the `other_outputs` of the `DefaultInfo`.++ Example:+ ```python+ load("@prelude//bxl:ensure.bxl", "ensure_default_info")+ def _impl(ctx):+ target = ctx.cli_args.target+ default_info = ctx.analysis(target).providers()[DefaultInfo].sub_targets["dwp"][DefaultInfo]+ ensure_default_info(ctx, default_info)+ ```+ """+ other_outputs = default_info.other_outputs or [] if with_other_outputs else []+ ctx.output.ensure_multiple(cmd_args(default_info.default_outputs, hidden = other_outputs))
@@ -0,0 +1,206 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Utils functions for working with bxl.Lazy objects.+"""++def catch_resolve_lazy_dict(bxl_ctx: bxl.Context, lazy_dict: dict[typing.Any, bxl.Lazy]) -> dict[typing.Any, bxl.Result]:+ """+ Resolves a dictionary of bxl.Lazy operations in parallel while capturing errors.++ Parameters:+ - `bxl_ctx`: BXL context+ - `lazy_dict`: Dictionary to resolve, where values must be `bxl.Lazy` instances++ Returns:+ A new dictionary preserving original keys, with values as `bxl.Result` objects.++ Example:+ ```python+ def _impl(ctx):+ lazy_dict = {+ "app": ctx.lazy.configured_targets("cell//:app"),+ "lib": ctx.lazy.configured_targets("cell//:lib")+ }++ # Batch resolve and process+ results = catch_resolve_lazy_dict(ctx, lazy_dict)+ for name, res in results.items():+ if res.is_ok():+ ctx.output.print(f"{name}: {res.unwrap()}")+ else:+ ctx.output.print(f"{name} failed: {res.unwrap_err()}")+ ```+ """+ keys = lazy_dict.keys()+ lazies = [lazy.catch() for lazy in lazy_dict.values()]+ values = bxl_ctx.lazy.join_all(lazies).resolve()+ return dict(zip(keys, values))++def batch_apply_lazy(bxl_ctx: bxl.Context, lazy_func: typing.Callable[[typing.Any], bxl.Lazy], args: list[typing.Any]) -> list[typing.Any]:+ """+ Applies a lazy function to a list of arguments, resolves them in parallel, and returns raw results.+ It will cause bxl fail immediately if any operation fails (no error catching).++ Parameters:+ - `bxl_ctx` (`bxl.Context`): The BXL context object.+ - `lazy_func` (`typing.Callable[[Any], bxl.Lazy]`): A function that takes a single argument and returns a `bxl.Lazy`+ (e.g., `ctx.lazy.analysis`, `ctx.lazy.configured_target_node`, or any other functon/lambda you defined).+ - `args` (`list[typing.Any]`): List of arguments to apply to `lazy_func`.++ Returns:+ - A list of resolved values. If any operation fails, the bxl script will fail.++ Example:+ ```python+ def _impl(ctx):+ targets = [+ "cell//:valid_target1",+ "cell//:valid_target2"+ ]++ # Resolve to all configured target nodes without error catching+ nodes = batch_apply_lazy(ctx, ctx.lazy.configured_target_node, targets)+ ctx.output.print(f"All configured target nodes: {nodes}")+ ```+ """+ lazies = [lazy_func(arg) for arg in args]+ return bxl_ctx.lazy.join_all(lazies).resolve()++def batch_apply_lazy_catch_each(bxl_ctx: bxl.Context, lazy_func: typing.Callable[[typing.Any], bxl.Lazy], args: list[typing.Any]) -> list[bxl.Result]:+ """+ Applies a lazy function to a list of arguments, resolves them in parallel, and returns individual `Result`+ objects for each operation. Errors are isolated per item.++ Parameters:+ - `bxl_ctx` (`bxl.Context`): The BXL context object.+ - `lazy_func` (`typing.Callable[[typing.Any], bxl.Lazy]`): A function that returns a `bxl.Lazy`+ (e.g., `ctx.lazy.analysis`, `ctx.lazy.configured_target_node`, or any other functon/lambda you defined)..+ - `args` (`list[typing.Any]`): List of arguments to apply to `lazy_func`.++ Returns:+ - `list[bxl.Result]`: A list of `Result` objects in the same order as `args`. Each `Result` can be+ `Ok(value)` or `Err(error)`.++ Example:+ ```python+ def _impl(ctx):+ targets = [+ "cell//:valid_target1",+ "cell//:valid_target2"+ "cell//:invalid_target1",+ ]++ # Resolve analyses with per-item error handling+ results = batch_apply_lazy_catch_each(ctx, ctx.lazy.configured_target_node, targets)++ for target, res in zip(targets, results):+ if res.is_ok():+ node = res.unwrap()+ ctx.output.print(f"Get configured target node for {target} SUCCESS: {node}")+ else:+ error = res.unwrap_err()+ ctx.output.print(f"Get configured target node for {target} FAILED: {error}")+ ```+ """+ lazies = [lazy_func(arg).catch() for arg in args] # Catch per item+ return bxl_ctx.lazy.join_all(lazies).resolve()++def batch_apply_lazy_catch_all(bxl_ctx: bxl.Context, lazy_func: typing.Callable[[typing.Any], bxl.Lazy], args: list[typing.Any]) -> bxl.Result:+ """+ Applies a lazy function to a list of arguments, joins them into a single batch operation, and resolves+ with a global error catch. Returns either all successes or the first error encountered.++ Parameters:+ - `bxl_ctx` (`bxl.Context`): The BXL context object.+ - `lazy_func` (`typing.Callable[[typing.Any], bxl.Lazy]`): A function that returns a `bxl.Lazy`+ (e.g., `ctx.lazy.analysis`, `ctx.lazy.configured_target_node`, or any other functon/lambda you defined)..+ - `args` (`list[typing.Any]`): List of arguments to apply to `lazy_func`.++ Returns:+ - `bxl.Result`:+ - `Ok(list)`: If all operations succeed, returns the list of resolved values.+ - `Err(error)`: If any operation fails, returns the first error encountered.++ Example:+ ```python+ def _impl(ctx):+ targets = [+ "cell//:valid_target1",+ "cell//:valid_target2"+ "cell//:invalid_target1",+ ]++ # Resolve as a single batch with global error handling+ batch_result = batch_apply_lazy_catch_all(ctx, ctx.lazy.configured_target_node, targets)++ if batch_result.is_ok():+ res = batch_result.unwrap()+ ctx.output.print(f"All succeeded: {len(res)}")+ else:+ error = batch_result.unwrap_err()+ ctx.output.print(f"Batch failed: {error}")+ ```+ """+ lazies = [lazy_func(arg) for arg in args]+ joined = bxl_ctx.lazy.join_all(lazies)+ return joined.catch().resolve() # Catch at batch level++def partition_results(results: list[bxl.Result]) -> (list[typing.Any], list[bxl.Error]):+ """+ Splits Results into successful values and errors.++ Parameters:+ - `results`: List of `bxl.Result` objects++ Returns:+ A tuple of two lists: `(successes, errors)`++ Example:+ ```python+ successes, errors = partition_results(results)+ ctx.output.print(f"Successes: {len(successes)}, Errors: {len(errors)}")+ ```+ """+ oks, errs = [], []+ for res in results:+ if res.is_ok():+ oks.append(res.unwrap())+ else:+ errs.append(res.unwrap_err())+ return oks, errs++def partition_results_dict(results_dict: dict[typing.Any, bxl.Result]) -> (dict[typing.Any, typing.Any], dict[typing.Any, bxl.Error]):+ """+ Splits a dictionary of `bxl.Result` into two dictionaries:+ - Successful key-value pairs (unwrapped values)+ - Errored key-value pairs (error objects)++ Parameters:+ - `results_dict`: Dictionary with values of type `bxl.Result`++ Returns:+ Tuple of `(success_dict, error_dict)` where:+ - `success_dict`: Original keys mapped to unwrapped `Ok` values+ - `error_dict`: Original keys mapped to `bxl.Error` objects++ Example:+ ```python+ results = {"app": res1, "lib": res2, "test": res3}+ successes, errors = split_results_dict_by_status(results)+ ```+ """+ success_dict = {}+ error_dict = {}+ for key, res in results_dict.items():+ if res.is_ok():+ success_dict[key] = res.unwrap()+ else:+ error_dict[key] = res.unwrap_err()+ return success_dict, error_dict
@@ -0,0 +1,11 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++CacheModeInfo = provider(+ fields = {"allow_cache_uploads": provider_field(typing.Any, default = None), "cache_bust_genrules": provider_field(typing.Any, default = None)}+)
@@ -0,0 +1,82 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Capabilities registration provider and tset for build graph propagation.++CapabilitiesRegistrationInfo is a provider that carries capability metadata+through the dependency graph via a transitive set (tset). Each library with+capability declarations creates a tset entry and merges it with its deps'+tsets. At binary build time, a manifest rule projects the final tset into+a support manifest JSON.+"""++def _project_as_manifest_json(entry):+ """Project a CapabilitiesRegistrationEntry to its manifest JSON representation."""+ result = {+ "kind": entry.kind,+ "style_id": entry.style_id,+ }+ if entry.props:+ result["props"] = entry.props+ if entry.features:+ result["features"] = entry.features+ return result++CapabilitiesRegistrationEntry = record(+ style_id = field(str),+ kind = field(str),+ props = field(dict[str, typing.Any], {}),+ features = field(dict[str, typing.Any], {}),+)++CapabilitiesRegistrationTSet = transitive_set(+ json_projections = {+ "manifest_entries": _project_as_manifest_json,+ },+)++CapabilitiesRegistrationInfo = provider(+ fields = {+ "tset": provider_field(CapabilitiesRegistrationTSet | None, default = None),+ }+)++def capabilities_registration_providers(ctx) -> list:+ """Collect CapabilitiesRegistrationInfo from deps and create tset entry if this target has registrations."""+ children = []+ for dep in ctx.attrs.deps + ctx.attrs.exported_deps:+ info = dep.get(CapabilitiesRegistrationInfo)+ if info and info.tset:+ children.append(info.tset)++ registrations = getattr(ctx.attrs, "capabilities_registrations", None)+ entries = []+ if registrations:+ for reg in registrations:+ entries.append(+ CapabilitiesRegistrationEntry(+ style_id = reg["style_id"],+ kind = reg["kind"],+ props = reg.get("props", {}),+ features = reg.get("features", {}),+ )+ )++ if not entries and not children:+ return []++ if entries:+ for entry in entries:+ tset = ctx.actions.tset(CapabilitiesRegistrationTSet, value = entry, children = children)+ children = [tset]+ tset = children[0]+ else:+ tset = ctx.actions.tset(CapabilitiesRegistrationTSet, children = children)++ return [CapabilitiesRegistrationInfo(tset = tset)]
@@ -0,0 +1,24 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# Default exec platform marker constraint value.+# This is the constraint value that gets injected into all execution platforms.+_DEFAULT_EXEC_PLATFORM_MARKER = "prelude//cfg/exec_platform/marker:is_exec_platform[true]"++def get_exec_platform_marker() -> str:+ """+ Get the exec platform marker constraint value target.++ This reads from buckconfig `[build].exec_platform_marker` and defaults to+ `prelude//cfg/exec_platform/marker:is_exec_platform[true]`.++ Returns:+ The target label string for the exec platform marker constraint value,+ unless the buckconfig doesn't exist, then `_DEFAULT_EXEC_PLATFORM_MARKER`.+ """+ return read_root_config("build", "exec_platform_marker", _DEFAULT_EXEC_PLATFORM_MARKER)
@@ -0,0 +1,38 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:native.bzl", prelude = "native")+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("build_infra")++source_listing()++# Execution platform marker constraint.+# This constraint is used to distinguish execution platforms from target platforms.+# When configuring exec deps, this marker will be present in the configuration,+# allowing modifiers with execution_modifier=False to skip applying.++# This constraint should be registered in the ExecutionPlatformRegistrationInfo++exec_platform_marker_constraint(+ name = "is_exec_platform",+ default = "false",+ values = [+ "true",+ "false",+ ],+ visibility = ["PUBLIC"],+)++# Export BUCK file for inclusion in prelude//:prelude filegroup+prelude.export_file(+ name = "buck_file",+ src = "BUCK",+ visibility = ["PUBLIC"],+)
@@ -0,0 +1,29 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Modifier aliases that can be used on the CLI, ex. after `--modifier=` or in `?`.++These aliases are ones we share between internal and OSS usages.+All constraints used in these aliases must also be available in OSS.+"""++# It's represented as a struct where the attribute name is the alias and the string+# for the attribute is the fully qualified target. Defining aliases in a struct+# helps enforce that the alias names do not contain any bad character we cannot use on CLI.+#+# We define aliases for modifiers here rather than reusing `alias` section of buckconfig for+# several reasons.+# 1. `alias` buckconconfig is not well-designed. It only supports aliases in a cell and not+# global aliases and users can override aliases in modefiles.+# 2. Modifier aliases can point to conditional modifiers, which `alias` buckconfig does not+# suppport.+# 3. It's unlikely a user has to ever define an alias twice in both the `alias` buckconfig+# and in modifier aliases because a modifier alias is a constraint value/config setting+# and those don't typically get built on CLI.+OSS_ALIASES = struct()
@@ -0,0 +1,32 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//cfg/modifier:types.bzl", "Modifier", "is_modifiers_match")++def verify_normalized_target(target: str):+ # Do some basic checks that target looks reasonably valid and normalized+ # Targets should always be fully qualified to improve readability.+ if "//" not in target or target.startswith("//") or ":" not in target:+ fail(+ "Must specify fully qualified target (ex. `cell//foo:bar`). Found `{}`".format(+ target,+ ),+ )++def verify_normalized_modifier(modifier: Modifier):+ if modifier == None:+ pass+ elif is_modifiers_match(modifier):+ # TODO(scottcao): Add a test case for this once `bxl_test` supports testing failures+ for key, sub_modifier in modifier.items():+ if key != "_type":+ verify_normalized_modifier(sub_modifier)+ elif isinstance(modifier, str):+ verify_normalized_target(modifier)+ else:+ fail("Found unexpected modifier `{}` type `{}`".format(modifier, type(modifier)))
@@ -0,0 +1,130 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//utils:buckconfig.bzl", "read_bool")+load("@prelude//utils:type_defs.bzl", "is_bool")+load(":types.bzl", "BuckconfigBackedModifierInfo", "ConditionalModifierInfo")++def _convert_to_conditional_modifier_infos(modifiers: list[Dependency]) -> list[ConditionalModifierInfo]:+ return [modifier[ConditionalModifierInfo] for modifier in modifiers]++def _platform_deps_to_conditional_modifier_infos(platform_deps: list[Dependency]) -> list[ConditionalModifierInfo]:+ result = []+ for dep in platform_deps:+ platform_info = dep[PlatformInfo]+ for constraint_setting, constraint_value_info in platform_info.configuration.constraints.items():+ result.append(+ ConditionalModifierInfo(+ inner = constraint_value_info,+ key = constraint_setting,+ )+ )+ return result++def _impl(ctx: AnalysisContext) -> list[Provider]:+ pre_platform_modifiers = _platform_deps_to_conditional_modifier_infos(ctx.attrs.pre_platform_platforms) + _convert_to_conditional_modifier_infos(+ ctx.attrs.pre_platform_modifiers+ )+ post_platform_modifiers = _platform_deps_to_conditional_modifier_infos(ctx.attrs.post_platform_platforms) + _convert_to_conditional_modifier_infos(+ ctx.attrs.post_platform_modifiers+ )+ pre_cli_modifiers = _platform_deps_to_conditional_modifier_infos(ctx.attrs.pre_cli_platforms) + _convert_to_conditional_modifier_infos(+ ctx.attrs.pre_cli_modifiers+ )++ return [+ DefaultInfo(),+ BuckconfigBackedModifierInfo(+ pre_platform_modifiers = pre_platform_modifiers, post_platform_modifiers = post_platform_modifiers, pre_cli_modifiers = pre_cli_modifiers+ ),+ ]++_buckconfig_backed_modifiers = rule(+ impl = _impl,+ is_configuration_rule = True,+ attrs = {+ "post_platform_modifiers": attrs.list(attrs.dep(providers = [ConditionalModifierInfo])),+ "post_platform_platforms": attrs.list(attrs.dep(providers = [PlatformInfo]), default = []),+ "pre_cli_modifiers": attrs.list(attrs.dep(providers = [ConditionalModifierInfo])),+ "pre_cli_platforms": attrs.list(attrs.dep(providers = [PlatformInfo]), default = []),+ "pre_platform_modifiers": attrs.list(attrs.dep(providers = [ConditionalModifierInfo])),+ "pre_platform_platforms": attrs.list(attrs.dep(providers = [PlatformInfo]), default = []),+ },+)++# Supports specifying one or more modifiers or platforms that can be enabled by a buckconfig.+BuckconfigBackedModifier = record(+ section = str,+ property = str,+ value = str | bool | None,+ modifiers = field(list[str], default = []),+ platforms = field(list[str], default = []),+ oncall = str,+)++IS_SET_VALUE = "__is_set__"++def _buckconfig_matches(entry: BuckconfigBackedModifier) -> bool:+ if is_bool(entry.value):+ return read_bool(entry.section, entry.property, required = False) == entry.value+ elif entry.value == IS_SET_VALUE:+ return read_config(entry.section, entry.property) != None+ else:+ return read_config(entry.section, entry.property) == entry.value++def _convert_to_modifiers(entries: list[BuckconfigBackedModifier]) -> list[str]:+ modifiers = []+ for entry in entries:+ if _buckconfig_matches(entry):+ modifiers += entry.modifiers+ return modifiers++def _convert_to_platforms(entries: list[BuckconfigBackedModifier]) -> list[str]:+ platforms = []+ for entry in entries:+ if _buckconfig_matches(entry):+ platforms += entry.platforms+ return platforms++def buckconfig_backed_modifiers(+ name: str, pre_platform: list[BuckconfigBackedModifier], post_platform: list[BuckconfigBackedModifier], pre_cli: list[BuckconfigBackedModifier]+):+ """+ Enable buckconfigs to become modifiers.+ We need this so that we can migrate `read_config`s to selects without having to worry about+ having all builds specifying these buckconfigs to specify modifiers for them instead.++ Buckconfigs are read from `toolchains` cell in order to identify buckconfigs+ specified in modefiles on CLI, as opposed to buckconfigs specified in .buckconfig files per cells.++ Each `BuckconfigBackedModifier` entry can specify `modifiers` (individual constraint value targets)+ and/or `platforms` (platform targets whose constraints are applied). At least one must be non-empty.++ Args:+ `pre_platform`: These modifiers apply before the legacy target+ platform, so they can get overriden by the legacy platform + every modifier specified.+ `post_platform`: These modifiers apply after the legacy target platform, so they can override+ the legacy platform but PACKAGE/target/CLI modifiers all override them.+ `pre_cli`: These modifiers apply before the CLI modifiers, so they can override PACKAGE+ and target modifiers but still can be overriden by CLI modifiers.++ """+ for entries in (pre_platform, post_platform, pre_cli):+ for entry in entries:+ if not entry.modifiers and not entry.platforms:+ fail("BuckconfigBackedModifier for {}.{} must specify at least one of `modifiers` or `platforms`".format(entry.section, entry.property))++ _buckconfig_backed_modifiers(+ name = name,+ pre_platform_modifiers = _convert_to_modifiers(pre_platform),+ post_platform_modifiers = _convert_to_modifiers(post_platform),+ pre_cli_modifiers = _convert_to_modifiers(pre_cli),+ pre_platform_platforms = _convert_to_platforms(pre_platform),+ post_platform_platforms = _convert_to_platforms(post_platform),+ pre_cli_platforms = _convert_to_platforms(pre_cli),+ )
@@ -0,0 +1,196 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ ":common.bzl",+ "apply_buckconfig_backed_modifiers",+ "get_and_insert_modifier_info",+ "json_to_tagged_modifiers",+ "modifier_to_refs",+ "resolve_alias",+ "resolve_configuration",+)+load(+ ":types.bzl",+ "BuckconfigBackedModifierInfo",+ "Modifier", # @unused+ "ModifierCliLocation",+ "ModifierTargetLocation",+ "TaggedModifiers",+)++PostConstraintAnalysisParams = record(+ legacy_platform = PlatformInfo | None,+ package_modifiers = list[TaggedModifiers],+ target_modifiers = list[Modifier],+ cli_modifiers = list[Modifier],+ extra_data = struct,+ configuring_exec_dep = bool,+)++def _get_buckconfig_backed_modifiers(extra_data: struct, configuring_exec_dep: bool) -> str | None:+ # If we are configuring an exec dep, we don't want to apply any modifiers from buckconfig.+ if configuring_exec_dep:+ return None+ return getattr(extra_data, "buckconfig_backed_modifiers", None)++def _has_buckconfig_backed_modifiers(refs: dict[str, ProviderCollection], target: str | None) -> bool:+ if not target:+ return False+ info = refs[target][BuckconfigBackedModifierInfo]+ return bool(info.pre_platform_modifiers or info.post_platform_modifiers or info.pre_cli_modifiers)++def cfg_constructor_pre_constraint_analysis(+ *,+ legacy_platform: PlatformInfo | None,+ # dict[str, typing.Any] is JSON dictionary form of `TaggedModifier` passed from buck2 core+ package_modifiers: list[dict[str, typing.Any]] | None,+ # typing.Any is JSON form of modifier+ target_modifiers: list[Modifier] | None,+ cli_modifiers: list[str],+ rule_name: str,+ aliases: struct,+ extra_data: struct,+ configuring_exec_dep: bool,+ **_kwargs,+) -> (list[str], PostConstraintAnalysisParams):+ """+ First stage of cfg constructor for modifiers.++ Args:+ legacy_platform:+ PlatformInfo from legacy target platform resolution, if one is specified+ package_modifiers:+ A list of modifiers specified from all parent PACKAGE files+ target_modifiers:+ A list of modifiers specified from buildfile via `metadata` attribute.+ cli_modifiers:+ modifiers specified from `--modifier` flag, `?modifier`, or BXL+ aliases:+ A struct that contains mapping of modifier aliases to modifier.+ extra_data:+ Some extra data that is for extra logging/validation for our internal modifier implementation.+ configuring_exec_dep (bool):+ Indicates whether this target is being configured as an execution dependency (exec_dep).+ When True, this flag enables the cfg_constructor to apply exec-specific modifier resolution logic.++ Returns `(refs, PostConstraintAnalysisParams)`, where `refs` is a list of fully qualified configuration+ targets we need providers for.+ """+ package_modifiers = package_modifiers or []+ target_modifiers = target_modifiers or []++ # Convert JSONs back to TaggedModifiers+ package_modifiers = [json_to_tagged_modifiers(modifier_json) for modifier_json in package_modifiers]++ # Filter PACKAGE modifiers based on rule name.+ # This only filters out PACKAGE modifiers from `extra_cfg_modifiers_per_rule` argument of `set_cfg_modifiers` function.+ package_modifiers = [+ tagged_modifiers for tagged_modifiers in package_modifiers if tagged_modifiers.rule_name == None or tagged_modifiers.rule_name == rule_name+ ]++ # Resolve all aliases in CLI modifiers+ cli_modifiers = [resolved_modifier for modifier in cli_modifiers for resolved_modifier in resolve_alias(modifier, aliases)]++ refs = []+ buckconfig_backed_modifiers = _get_buckconfig_backed_modifiers(extra_data, configuring_exec_dep)+ if buckconfig_backed_modifiers:+ refs.append(buckconfig_backed_modifiers)++ for tagged_modifiers in package_modifiers:+ for modifier in tagged_modifiers.modifiers:+ refs.extend(modifier_to_refs(modifier, tagged_modifiers.location))+ for modifier in target_modifiers:+ refs.extend(modifier_to_refs(modifier, ModifierTargetLocation()))+ for modifier in cli_modifiers:+ refs.extend(modifier_to_refs(modifier, ModifierCliLocation()))++ return refs, PostConstraintAnalysisParams(+ legacy_platform = legacy_platform,+ package_modifiers = package_modifiers,+ target_modifiers = target_modifiers,+ cli_modifiers = cli_modifiers,+ extra_data = extra_data,+ configuring_exec_dep = configuring_exec_dep,+ )++def cfg_constructor_post_constraint_analysis(*, refs: dict[str, ProviderCollection], params: PostConstraintAnalysisParams) -> PlatformInfo:+ """+ Second stage of cfg constructor for modifiers.++ Args:+ refs: a dictionary of fully qualified target labels for configuration targets with their providers+ params: `PostConstraintAnalysisParams` returned from first stage of cfg constructor++ Returns a PlatformInfo+ """++ buckconfig_backed_modifiers = _get_buckconfig_backed_modifiers(params.extra_data, params.configuring_exec_dep)+ if not (params.package_modifiers or params.target_modifiers or params.cli_modifiers or _has_buckconfig_backed_modifiers(refs, buckconfig_backed_modifiers)):+ # If there is no modifier and legacy platform is specified,+ # then return the legacy platform as is without changing the label or+ # configuration.+ return params.legacy_platform or PlatformInfo(+ # Empty configuration+ label = "<empty>",+ configuration = ConfigurationInfo(+ constraints = {},+ values = {},+ ),+ )++ constraint_setting_to_modifier_infos = {}++ if buckconfig_backed_modifiers:+ apply_buckconfig_backed_modifiers(+ constraint_setting_to_modifier_infos, refs[buckconfig_backed_modifiers][BuckconfigBackedModifierInfo].pre_platform_modifiers+ )++ if params.legacy_platform:+ for constraint_setting, constraint_value_info in params.legacy_platform.configuration.constraints.items():+ constraint_setting_to_modifier_infos[constraint_setting] = [constraint_value_info]++ if buckconfig_backed_modifiers:+ apply_buckconfig_backed_modifiers(+ constraint_setting_to_modifier_infos, refs[buckconfig_backed_modifiers][BuckconfigBackedModifierInfo].post_platform_modifiers+ )++ for tagged_modifiers in params.package_modifiers:+ for modifier in tagged_modifiers.modifiers:+ if modifier:+ get_and_insert_modifier_info(+ constraint_setting_to_modifier_infos = constraint_setting_to_modifier_infos,+ refs = refs,+ modifier = modifier,+ location = tagged_modifiers.location,+ )++ for modifier in params.target_modifiers:+ if modifier:+ get_and_insert_modifier_info(+ constraint_setting_to_modifier_infos = constraint_setting_to_modifier_infos,+ refs = refs,+ modifier = modifier,+ location = ModifierTargetLocation(),+ )++ if buckconfig_backed_modifiers:+ apply_buckconfig_backed_modifiers(+ constraint_setting_to_modifier_infos, refs[buckconfig_backed_modifiers][BuckconfigBackedModifierInfo].pre_cli_modifiers+ )++ for modifier in params.cli_modifiers:+ if modifier:+ get_and_insert_modifier_info(+ constraint_setting_to_modifier_infos = constraint_setting_to_modifier_infos,+ refs = refs,+ modifier = modifier,+ location = ModifierCliLocation(),+ )++ return resolve_configuration(constraint_setting_to_modifier_infos)
@@ -0,0 +1,310 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:asserts.bzl", "asserts")+load("@prelude//utils:graph_utils.bzl", "post_order_traversal")+load(":asserts.bzl", "verify_normalized_modifier")+load(":name.bzl", "cfg_name")+load(+ ":types.bzl",+ "ConditionalModifierInfo",+ "Modifier",+ "ModifierBuckconfigLocation",+ "ModifierCliLocation",+ "ModifierInfo",+ "ModifierLocation",+ "ModifierPackageLocation",+ "ModifierTargetLocation",+ "ModifiersMatchInfo",+ "TaggedModifiers",+ "is_modifiers_match",+)++# Key under which `set_cfg_modifiers()` writes its PACKAGE-level cfg modifiers+# (consumed by `set_cfg_constructor(key = MODIFIER_METADATA_KEY, ...)`). The+# string value collides with the historical per-target `metadata["buck.cfg_modifiers"]`+# key, which is no longer supported - per-target modifiers must use the first-class+# `modifiers` attribute.+MODIFIER_METADATA_KEY = "buck.cfg_modifiers"++_TARGET_LOCATION_STR = "`modifiers` attribute of target"+_CLI_LOCATION_STR = "command line"++def location_to_string(location: ModifierLocation) -> str:+ if isinstance(location, ModifierPackageLocation):+ return location.package_path+ if isinstance(location, ModifierTargetLocation):+ return _TARGET_LOCATION_STR+ if isinstance(location, ModifierCliLocation):+ return _CLI_LOCATION_STR+ if isinstance(location, ModifierBuckconfigLocation):+ return "buckconfig {}.{}".format(location.section, location.property)+ fail("Internal error. Unrecognized location type `{}` for location `{}`".format(type(location), location))++def get_tagged_modifiers(+ cfg_modifiers: list[Modifier], extra_cfg_modifiers_per_rule: dict[str, list[Modifier]], location: ModifierLocation+) -> list[TaggedModifiers]:+ for modifier in cfg_modifiers:+ verify_normalized_modifier(modifier)+ for _, modifiers in extra_cfg_modifiers_per_rule.items():+ for modifier in modifiers:+ verify_normalized_modifier(modifier)++ # Aggreggate all tagged modifiers in a PACKAGE in a single list.+ # Per-rule modifiers come the global modifiers so that they are processed later.+ return [+ TaggedModifiers(+ modifiers = cfg_modifiers,+ location = location,+ rule_name = None,+ ),+ ] + [+ TaggedModifiers(+ modifiers = modifiers,+ location = location,+ rule_name = rule_name,+ )+ for rule_name, modifiers in extra_cfg_modifiers_per_rule.items()+ ]++def get_constraint_setting(constraint_settings: set[TargetLabel], modifier: Modifier, location: ModifierLocation) -> TargetLabel:+ if len(constraint_settings) == 0:+ fail("`modifiers.match` cannot be empty. Found empty `modifiers.match` at `{}`".format(location_to_string(location)))+ if len(constraint_settings) > 1:+ fail(+ "A single modifier can only modify a single constraint setting.\n"+ + "Modifier `{}` from `{}` is found to modify the following constraint settings:\n".format(+ modifier,+ location_to_string(location),+ )+ + "\n".join([str(k) for k in constraint_settings]),+ )+ return list(constraint_settings)[0]++def get_modifier_info(refs: dict[str, ProviderCollection], modifier: Modifier, location: ModifierLocation) -> (TargetLabel, ModifierInfo) | None:+ # Gets a modifier info from a modifier based on providers from `refs`.+ if modifier == None:+ return None+ if is_modifiers_match(modifier):+ default = None+ modifiers_match_info = []+ constraint_settings = set()+ for key, sub_modifier in modifier.items():+ if key == "DEFAULT":+ if sub_modifier:+ default_constraint_setting, default = get_modifier_info(refs, sub_modifier, location)+ constraint_settings.add(default_constraint_setting)+ else:+ default = None+ elif key != "_type":+ cfg_info = refs[key][ConfigurationInfo]+ root_values = cfg_info.root_values+ if cfg_info.values or root_values:+ buckconfig_values = cfg_info.values | root_values+ soft_error(+ "starlark_config_setting_non_empty_buckconfig_values_in_conditional_modifier",+ "config_setting `{}` defines buckconfig values {} which are NOT supported in conditional modifiers.\n".format(key, buckconfig_values)+ + "These buckconfig values are being IGNORED.\n\n"+ + "Action required: Remove the `values` and `root_values` parameters from this config_setting {} and use only `constraint_values` instead.\n".format(+ key+ )+ + "Note: This may become a hard error in the future to prevent silent misconfiguration.",+ quiet = True,+ stack = False,+ )+ if sub_modifier:+ sub_constraint_setting, sub_modifier_info = get_modifier_info(refs, sub_modifier, location)+ constraint_settings.add(sub_constraint_setting)+ else:+ sub_modifier_info = None+ modifiers_match_info.append((cfg_info, sub_modifier_info))++ constraint_setting = get_constraint_setting(constraint_settings, modifier, location)++ return constraint_setting, ModifiersMatchInfo(+ default = default,+ selector = modifiers_match_info,+ )+ if isinstance(modifier, str):+ modifier_info = refs[modifier]+ if ConditionalModifierInfo in modifier_info:+ conditional_modifier_info = modifier_info[ConditionalModifierInfo]+ return conditional_modifier_info.key, conditional_modifier_info.inner+ cfg_info = modifier_info[ConfigurationInfo]+ asserts.true(len(cfg_info.constraints) == 1, "Modifier should only be a single constraint value. Found multiple or none in `{}`".format(modifier))+ fail(+ "Internal error: Modifer (`{}` type `{}`) with single constraint value should have ConditionalModifierInfo provider.".format(+ modifier_info, type(modifier_info)+ )+ )+ fail("Internal error: Found unexpected modifier `{}` type `{}`".format(modifier, type(modifier)))++def _is_subset(a: ConfigurationInfo, b: ConfigurationInfo) -> bool:+ for _constraint_setting, a_constraint_value in a.constraints.items():+ setting_info = a_constraint_value.setting+ b_constraint_value = b.get(setting_info)+ if a_constraint_value != b_constraint_value:+ return False+ return True++def resolve_modifier(cfg: ConfigurationInfo, modifier: ModifierInfo) -> ConstraintValueInfo | None:+ # Resolve the modifier and return the constraint value to add to the configuration, if there is one+ if modifier == None:+ return None+ if isinstance(modifier, ModifiersMatchInfo):+ for key, sub_modifier in modifier.selector:+ if _is_subset(key, cfg):+ # If constraints in key of the select are a subset of the constraints in the+ # current configuration, then it's a match.+ return resolve_modifier(cfg, sub_modifier)+ if modifier.default:+ return resolve_modifier(cfg, modifier.default)+ return None+ if isinstance(modifier, ConstraintValueInfo):+ return modifier+ fail("Internal error: Found unexpected modifier `{}` type `{}`".format(modifier, type(modifier)))++def resolve_configuration(constraint_setting_to_modifier_infos: dict[TargetLabel, list[ModifierInfo]]) -> PlatformInfo:+ # Modifiers are resolved in topological ordering of modifier selects. For example, if the CPU modifier+ # is a modifier_select on OS constraint, then the OS modifier must be resolved before the CPU modifier.+ # To determine this order, we first construct a dep graph of constraint settings based on the modifier+ # selects. Then we perform a post order traversal of the said graph.+ modifier_dep_graph = {+ constraint_setting: [dep for modifier_info in modifier_infos for dep in get_constraint_setting_deps(modifier_info)]+ for constraint_setting, modifier_infos in constraint_setting_to_modifier_infos.items()+ }++ # For topo-sort, we need to fill in empty edges for nodes that have no deps+ for deps in modifier_dep_graph.values():+ for dep in deps:+ if dep not in modifier_dep_graph:+ modifier_dep_graph[dep] = []++ constraint_setting_order = post_order_traversal(modifier_dep_graph)++ cfg = ConfigurationInfo(+ constraints = {},+ values = {},+ )++ for constraint_setting in constraint_setting_order:+ for modifier_info in constraint_setting_to_modifier_infos.get(constraint_setting) or ():+ constraint_value = resolve_modifier(cfg, modifier_info)+ if constraint_value:+ cfg.constraints[constraint_setting] = constraint_value++ name = cfg_name(cfg)+ return PlatformInfo(+ label = name,+ configuration = cfg,+ )++def modifier_to_refs(modifier: Modifier, location: ModifierLocation) -> list[str]:+ # Obtain a list of targets to analyze from a modifier.+ refs = []+ if modifier == None:+ pass+ elif is_modifiers_match(modifier):+ for key, sub_modifier in modifier.items():+ if key != "_type":+ if key != "DEFAULT":+ refs.append(key)+ refs.extend(modifier_to_refs(sub_modifier, location))+ elif isinstance(modifier, str):+ refs.append(modifier)+ else:+ fail("Internal error: Found unexpected modifier `{}` type `{}`".format(modifier, type(modifier)))+ return refs++def tagged_modifiers_to_json(tagged_modifiers: TaggedModifiers) -> dict[str, typing.Any]:+ return {+ "location": _location_to_json(tagged_modifiers.location),+ "modifiers": tagged_modifiers.modifiers,+ "rule_name": tagged_modifiers.rule_name,+ "_type": "TaggedModifiers",+ }++def _location_to_json(location: ModifierLocation) -> dict[str, str]:+ if isinstance(location, ModifierPackageLocation):+ return {"package_path": location.package_path, "_type": "ModifierPackageLocation"}+ if isinstance(location, ModifierTargetLocation):+ return {"_type": "ModifierTargetLocation"}+ fail("Internal error: unknown location `{}` with type `{}`".format(location, type(location)))++def json_to_tagged_modifiers(j: dict[str, typing.Any]) -> TaggedModifiers:+ if j["_type"] != "TaggedModifiers":+ fail("Internal error: `{}` is not a `TaggedModifiers`".format(j))+ return TaggedModifiers(+ location = _json_to_location(j["location"]),+ modifiers = j["modifiers"],+ rule_name = j["rule_name"],+ )++def _json_to_location(j: dict[str, str]) -> ModifierLocation:+ modifier_type = j.pop("_type")+ if modifier_type == "ModifierPackageLocation":+ return ModifierPackageLocation(package_path = j["package_path"])+ if modifier_type == "ModifierTargetLocation":+ return ModifierTargetLocation()+ fail("Internal error: cannot deserialize location `{}`".format(j))++def resolve_alias(modifier: Modifier, aliases: struct) -> list[Modifier]:+ if isinstance(modifier, ModifiersMatchInfo):+ fail("It should not be possible to specify a conditional modifier from command line")+ if ":" in modifier:+ # This is a target and not an alias+ return [modifier]+ resolved = getattr(aliases, modifier, None)+ if resolved:+ return resolved if isinstance(resolved, list) else [resolved]+ fail("Found invalid modifier alias `{}`. A list of valid modifier aliases is in buck2/cfg/experimental/alias.bzl".format(modifier))++def _get_constraint_setting_deps(modifier_info: ModifierInfo) -> list[TargetLabel]:+ deps = []+ if isinstance(modifier_info, ModifiersMatchInfo):+ for key, sub_modifier in modifier_info.selector:+ for constraint_setting in key.constraints:+ deps.append(constraint_setting)+ deps += _get_constraint_setting_deps(sub_modifier)+ if modifier_info.default:+ deps += _get_constraint_setting_deps(modifier_info.default)+ return deps++def get_constraint_setting_deps(modifier_info: ModifierInfo) -> list[TargetLabel]:+ # Get all constraint settings depended on by a modifier (from keys of `modifier_select`). The modifiers+ # for these constraint settings must be resolved before this modifier can be resolved.+ return dedupe(_get_constraint_setting_deps(modifier_info))++def add_to_constraint_setting_to_modifier_infos(+ constraint_setting_to_modifier_infos: dict[TargetLabel, list[ModifierInfo]], constraint_setting_label: TargetLabel, modifier_info: ModifierInfo+):+ modifier_infos = constraint_setting_to_modifier_infos.get(constraint_setting_label) or []+ modifier_infos.append(modifier_info)+ constraint_setting_to_modifier_infos[constraint_setting_label] = modifier_infos++def get_and_insert_modifier_info(+ constraint_setting_to_modifier_infos: dict[TargetLabel, list[ModifierInfo]],+ refs: dict[str, ProviderCollection],+ modifier: Modifier,+ location: ModifierLocation,+) -> (TargetLabel, ModifierInfo):+ constraint_setting_label, modifier_info = get_modifier_info(+ refs = refs,+ modifier = modifier,+ location = location,+ )+ add_to_constraint_setting_to_modifier_infos(constraint_setting_to_modifier_infos, constraint_setting_label, modifier_info)+ return (constraint_setting_label, modifier_info)++def apply_buckconfig_backed_modifiers(constraint_setting_to_modifier_infos: dict[TargetLabel, list[ModifierInfo]], modifiers: list[ConditionalModifierInfo]):+ for conditional_modifier_info in modifiers:+ add_to_constraint_setting_to_modifier_infos(+ constraint_setting_to_modifier_infos = constraint_setting_to_modifier_infos,+ constraint_setting_label = conditional_modifier_info.key,+ modifier_info = conditional_modifier_info.inner,+ )
@@ -0,0 +1,163 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(":types.bzl", "ConditionalModifierInfo", "Modifier", "ModifiersMatch", "ModifiersMatchInfo")++def _get_constraint_setting(constraint_settings: set[TargetLabel], modifier: ModifiersMatch) -> TargetLabel:+ if len(constraint_settings) == 0:+ fail("Conditional modifier cannot be empty. Found empty modifier `{}`".format(modifier))+ if len(constraint_settings) > 1:+ fail(+ "A single modifier can only modify a single constraint setting.\n"+ + "Modifier `{}` is found to modify the following constraint settings:\n".format(+ modifier,+ )+ + "\n".join([str(k) for k in constraint_settings]),+ )+ return list(constraint_settings)[0]++def _get_modifier_info(+ modifier: Modifier, key_to_provider: dict[str, ConfigurationInfo], value_to_provider: dict[str, ConditionalModifierInfo]+) -> ConditionalModifierInfo | None:+ """+ Converts a modifier to a provider based on providers for keys and values.+ """+ if modifier == None:+ return None++ if isinstance(modifier, str):+ return value_to_provider[modifier]++ default = None+ modifiers_match_info = []+ constraint_settings = set()++ for key, sub_modifier in modifier.items():+ if key == "DEFAULT":+ if sub_modifier:+ sub_modifier_info = _get_modifier_info(sub_modifier, key_to_provider, value_to_provider)+ constraint_settings.add(sub_modifier_info.key)+ default = sub_modifier_info.inner+ else:+ cfg_info = key_to_provider[key]+ if sub_modifier:+ sub_modifier_info = _get_modifier_info(sub_modifier, key_to_provider, value_to_provider)+ constraint_settings.add(sub_modifier_info.key)+ sub_modifier_info = sub_modifier_info.inner+ else:+ sub_modifier_info = None+ modifiers_match_info.append((cfg_info, sub_modifier_info))++ constraint_setting = _get_constraint_setting(constraint_settings, modifier)+ return ConditionalModifierInfo(+ key = constraint_setting,+ inner = ModifiersMatchInfo(+ default = default,+ selector = modifiers_match_info,+ ),+ )++def _impl(ctx: AnalysisContext) -> list[Provider]:+ key_to_provider = {k: dep.get(ConfigurationInfo) for k, dep in ctx.attrs._conditional_keys.items()}+ value_to_provider = {k: dep.get(ConditionalModifierInfo) for k, dep in ctx.attrs._conditional_values.items()}+ conditional_modifier_info = _get_modifier_info(ctx.attrs.modifier, key_to_provider, value_to_provider)+ return [DefaultInfo(), conditional_modifier_info]++_conditional_modifier = rule(+ impl = _impl,+ doc = """+ A `_conditional_modifier` rule instantiates a conditional modifier that can be set on a target.+ This is a private rule. You want to instantiate it through the `conditional_modifier` function wrapper.++ The conditional modifier allows one to express a modifier in a dictionary form similar to a select, where+ each key in the dictionary is a set of constraints to match on and each value in the dictionary is a modifier.++ For example, below is a modifier for expressing "msvc if windows else clang".++ ```python+ conditional_modifier(+ name = "clang-msvc",+ modifier = {+ "DEFAULT": "prelude//constraints/compiler:clang",+ "prelude//constraints/os:windows": "prelude//constraints/compiler:msvc",+ },+ )+ ```++ A conditional modifier can be nested similar to a nested select.++ ```python+ conditional_modifier(+ name = "clang-msvc-gcc",+ modifier = {+ "DEFAULT": {+ "DEFAULT": "prelude//constraints/compiler:clang",+ "prelude//constraints/os:linux": "prelude//constraints/compiler:gcc",+ },+ "prelude//constraints/os:windows": "prelude//constraints/compiler:msvc",+ },+ )+ ```++ A conditional modifier can also take in another conditional modifier. For example, the modifier from the+ previous example can also be expressed as follows.++ ```python+ conditional_modifier(+ name = "clang-msvc-gcc2",+ modifier = {+ "DEFAULT": ":clang-msvc":+ "prelude//constraints/os:linux": "prelude//constraints/compiler:gcc",+ }+ )+ ```+ """,+ attrs = {+ "modifier": attrs.any(doc = "A conditional modifier to set"),+ # _conditional_keys maps original modifier keys to resolved providers+ # We preserve the original key strings because they are matched against+ # unmodified strings in the conditional modifier. Deriving the expected+ # string from dep.label fails when cell aliases are used.+ "_conditional_keys": attrs.dict(attrs.string(), attrs.dep(providers = [ConfigurationInfo]), doc = "internal attribute"),+ # _conditional_values maps original modifier values to resolved providers.+ # Reasoning for using a dict is the same as for _conditional_keys.+ "_conditional_values": attrs.dict(attrs.string(), attrs.dep(providers = [ConditionalModifierInfo]), doc = "internal attribute"),+ },+ is_configuration_rule = True,+)++def _get_conditional_keys(modifier: ModifiersMatch) -> dict[str, str]:+ result = {k: k for k in modifier.keys() if k != "DEFAULT"}+ for v in modifier.values():+ if isinstance(v, dict):+ result.update(_get_conditional_keys(v))+ elif v and not isinstance(v, str):+ fail("`{}` is not a valid modifier".format(v))+ return result++def _get_conditional_values(modifier: ModifiersMatch) -> dict[str, str]:+ result = {}+ for v in modifier.values():+ if isinstance(v, dict):+ result.update(_get_conditional_values(v))+ elif isinstance(v, str):+ result[v] = v+ elif v:+ fail("`{}` is not a valid modifier".format(v))+ return result++def conditional_modifier(name: str, modifier: ModifiersMatch):+ _conditional_modifier(+ name = name,+ _conditional_keys = _get_conditional_keys(modifier),+ _conditional_values = _get_conditional_values(modifier),+ modifier = modifier,+ )++# Exported for testing purposes only. Do not use in production code.+get_modifier_info_for_testing = _get_modifier_info
@@ -0,0 +1,84 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Functions for constructing ConditionalModifierInfo for constraint rules.++This module provides utilities to create ConditionalModifierInfo instances+with proper handling of execution platform modifiers. When a constraint has+execution_modifier=False, its modifier will be wrapped in a conditional that+skips it when configuring exec deps.+"""++load(":types.bzl", "ConditionalModifierInfo", "ModifierInfo", "ModifiersMatchInfo")++def _maybe_wrap_for_exec_platform(+ constraint_value: ConstraintValueInfo, execution_modifier: bool, exec_platform_marker_configuration_info: ConfigurationInfo | None+) -> ModifierInfo:+ """+ When execution_modifier=False, wrap the constraint value in a conditional+ modifier that returns None (skips) when the exec platform marker+ (ovr_config//platform/execution/constraints:execution-platform-transitioned)+ is present in the configuration. This means modifiers with+ execution_modifier=False won't apply when configuring exec deps.++ Args:+ constraint_value: The constraint value to potentially wrap.+ execution_modifier: If True, the modifier applies to exec deps, so no wrapping needed.+ exec_platform_marker_configuration_info: The ConfigurationInfo for the exec platform marker.+ If None, no wrapping is done.++ Returns:+ Either the original constraint_value (if execution_modifier=True or no marker),+ or a ModifiersMatchInfo that conditionally skips on exec platforms.+ """+ if execution_modifier:+ # This modifier should apply on exec platforms, no wrapping needed+ return constraint_value++ if exec_platform_marker_configuration_info == None:+ # No marker constraint available (e.g., for the marker constraint itself)+ return constraint_value++ # Wrap in a conditional: when exec marker is present -> None (skip), otherwise -> apply+ return ModifiersMatchInfo(+ selector = [(exec_platform_marker_configuration_info, None)], # Skip when on exec platform+ default = constraint_value, # Apply on target platform+ )++def make_constraint_modifier_info(+ constraint_value: ConstraintValueInfo, key: TargetLabel, execution_modifier: bool, exec_platform_marker_configuration_info: ConfigurationInfo | None+) -> ConditionalModifierInfo:+ """+ Creates a ConditionalModifierInfo for a constraint value with proper+ handling of execution platform modifiers.++ When execution_modifier=False and exec_platform_marker_configuration_info is provided,+ the inner value will be wrapped in a ModifiersMatchInfo that causes the+ modifier to be skipped when configuring exec deps.++ Args:+ constraint_value: The constraint value this modifier represents.+ key: The constraint setting's target label (used as the modifier key).+ execution_modifier: Whether this modifier should apply on exec platforms.+ exec_platform_marker_configuration_info: The ConfigurationInfo for the exec platform marker.+ Pass None for the marker constraint itself to avoid cycles.++ Returns:+ A ConditionalModifierInfo with the appropriate inner value.+ """+ wrapped_inner = _maybe_wrap_for_exec_platform(+ constraint_value = constraint_value,+ execution_modifier = execution_modifier,+ exec_platform_marker_configuration_info = exec_platform_marker_configuration_info,+ )++ return ConditionalModifierInfo(+ inner = wrapped_inner,+ key = key,+ )
@@ -0,0 +1,70 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# This is an ordered dictionary of constraint setting target to an optional transform.+# The constraint settings listed below are used to name the configuration, where the first+# constraint settings are named first in the configuration. The transform, if specified,+# can change how the name appears in the configuration. By default, if there is no transform,+# we just use name of the constraint value in the configuration name. If transform is+# specified, the transform will be applied on the existing constraint value name to return a+# new string to be used in the configuration.+# @unsorted-dict-items+NAMED_CONSTRAINT_SETTINGS = {+ # TODO(scottcao): Add OSS constraints as well+ "ovr_config//build_mode/constraints:core_build_mode": (lambda label: str(label.sub_target[0])),+ "ovr_config//os/constraints:os": (lambda label: str(label.sub_target[0])),+ "ovr_config//cpu/constraints:cpu": None,+ "ovr_config//runtime/constraints:runtime": None,+ "ovr_config//runtime/constraints:runtime_version": None,+ "ovr_config//os/sdk/apple/constraints:_": (lambda label: str(label.sub_target[0])),+ "ovr_config//os/sdk/android/ndk/constraints:version": None,+ "ovr_config//os/version/android/constraints:api-level": (lambda label: "api" + str(label.name).split("-")[-1]),+ "ovr_config//toolchain/clang/constraints:clang-toolchain-version": (lambda label: "clang" + str(label.name)),+ "ovr_config//build_mode:sanitizer_type": (lambda label: str(label.sub_target[0])),+ "fbcode//fdo/constraints:fdo": (lambda label: str(label.name)),+ "ovr_config//build_mode/default_opt_cxx:default_opt_cxx_setting": (lambda label: "opt-by-default" if str(label.sub_target[0]) == "enabled" else None),+ "ovr_config//build_mode:arvr_mode": (lambda label: "arvr" if str(label.sub_target[0]) == "enabled" else None),+}++# A project's own constraint settings to name configurations by, after those+# above, by the names of their values: `named_constraint_settings` in the+# `cfg` section of its .buckconfig, a comma-separated list of (fully+# qualified) labels.+_PROJECT_NAMED_CONSTRAINT_SETTINGS = [+ setting.strip()+ for setting in (read_root_config("cfg", "named_constraint_settings") or "").split(",")+ if setting.strip()+]++# Mark all modifier generated configurations with a `cfg:` prefix.+# We do this so that we can easily recognize which configuration is generated+# by modifiers and query for it in Scuba.+_CFG_PREFIX = "cfg:"+_EMPTY_CFG_NAME = _CFG_PREFIX + "<empty>"++def cfg_name(cfg: ConfigurationInfo) -> str:+ """Derives a reasonable name for a ConfigurationInfo"""++ name_list = []+ constraints = {str(key): value for key, value in cfg.constraints.items()}+ for constraint_setting, transform in list(NAMED_CONSTRAINT_SETTINGS.items()) + [(s, None) for s in _PROJECT_NAMED_CONSTRAINT_SETTINGS]:+ constraint_name = None+ if constraint_setting in constraints:+ constraint_value_label = constraints[constraint_setting].label+ if transform:+ constraint_name = transform(constraint_value_label)+ else:+ constraint_name = str(constraint_value_label.name)+ if constraint_name:+ name_list.append(constraint_name)++ if len(name_list) == 0:+ name = _EMPTY_CFG_NAME+ else:+ name = _CFG_PREFIX + "-".join(name_list)+ return name
@@ -0,0 +1,66 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(":common.bzl", "get_tagged_modifiers", "tagged_modifiers_to_json")+load(":types.bzl", "Modifier", "ModifierPackageLocation") # @unused Used in type annotation++def set_cfg_modifiers(cfg_modifiers: list[Modifier] | None = None, extra_cfg_modifiers_per_rule: dict[str, list[Modifier]] | None = None):+ """+ Sets a configuration modifier for all targets under this PACKAGE file. This can only be called from a PACKAGE file context+ (e.g. a PACKAGE file or a bzl file transitively loaded by a PACKAGE file).++ Args:+ cfg_modifiers:+ A list of modifiers to set. The simplest modifier is a constraint value target.+ For example, to change the OS to linux in fbsource, this can be specified as `["ovr_config//os/constraints:linux"]`.+ extra_cfg_modifiers_per_rule:+ A dictionary of rule name to a list of modifiers to set. This is applied on top of modifiers from `cfg_modifiers` parameter+ if a target's rule name matches the key, so it can override any modifier from `cfg_modifiers` parameter in the same PACKAGE.+ For example, if this dictionary is `{"python_binary": ["ovr_config//os/constraints:macos"]}`,+ then all python_binary targets covered will have the macos constraint added to their configurations.+ """++ # To ensure that modifiers set in PACKAGE files are easily codemoddable+ # We want to enforce that `set_cfg_modifiers` is only invokable from a PACKAGE file and not a bzl file+ frame1 = call_stack_frame(1)+ if not _is_buck_tree_file(frame1.module_path):+ # Now check the old bzl file for `set_cfg_modifiers` in case it is invoked through that one.+ frame2 = call_stack_frame(2)+ if not (frame2 and frame1.module_path.endswith("fbcode/buck2/cfg/experimental/set_cfg_modifiers.bzl") and _is_buck_tree_file(frame2.module_path)):+ if not "third-party-buck" in frame2.module_path:+ fail("set_cfg_modifiers is only allowed to be used from a PACKAGE or BUCK_TREE file, not a bzl file.")++ cfg_modifiers = cfg_modifiers or []+ extra_cfg_modifiers_per_rule = extra_cfg_modifiers_per_rule or {}++ merged_modifier_jsons = get_parent_modifiers()++ # `get_parent_modifiers` returns immutable values. `list()` makes it mutable.+ merged_modifier_jsons = list(merged_modifier_jsons) if merged_modifier_jsons else []++ tagged_modifiers_list = get_tagged_modifiers(+ cfg_modifiers,+ extra_cfg_modifiers_per_rule,+ ModifierPackageLocation(package_path = _get_package_path()),+ )+ merged_modifier_jsons += [tagged_modifiers_to_json(tagged_modifiers) for tagged_modifiers in tagged_modifiers_list]++ set_modifiers(+ merged_modifier_jsons,+ )++def _get_package_path() -> str:+ """+ Returns the cell-relative path of the current PACKAGE file.+ Ex. `foo//bar/PACKAGE`+ """++ return "{}//{}/PACKAGE".format(get_cell_name(), get_base_path())++def _is_buck_tree_file(path: str) -> bool:+ return path.endswith(("/PACKAGE", "/BUCK_TREE")) or path in ("PACKAGE", "BUCK_TREE")
@@ -0,0 +1,81 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# TODO(scottcao): Annotate these types with comments once implementation is complete++# Metadata types for where cfg modifier is defined. We need to track this to give users error messages+# that include where the bad modifier comes from.++# Modifier defined in a PACKAGE file. We track path of that PACKAGE file.+ModifierPackageLocation = record(package_path = str)++# Modifier defined on the target in buildfile.+ModifierTargetLocation = record()++# Modifier specified via command line from the user+ModifierCliLocation = record()++# Modifier specified from buckconfig+ModifierBuckconfigLocation = record(+ section = str,+ property = str,+)++# This is a handy way of specifying a rust-style enum in Starlark.+ModifierLocation = ModifierPackageLocation | ModifierTargetLocation | ModifierCliLocation | ModifierBuckconfigLocation++# Modifier types as how they appear to the user via `set_cfg_modifier` or `cfg_modifier` function.++ModifiersMatch = dict[str, typing.Any]++Modifier = str | ModifiersMatch | None++TaggedModifiers = record(+ modifiers = list[Modifier],+ location = ModifierLocation,+ rule_name = str | None,+)++# Modifier types after analysis of configuration rules.+# There is an equivalent post-constraint-analysis type for every modifier type listed above.+# An "Info" is added to the type name to denote post-constraint-analysis version of the+# modifier type.++ModifiersMatchInfo = record(+ # should be list[(ConfigurationInfo, "ModifierInfo")] once recursive types are supported+ selector = list[(ConfigurationInfo, typing.Any)],+ default = typing.Any, # should be "ModifierInfo" | None with recursive types+)++ModifierInfo = ConstraintValueInfo | ModifiersMatchInfo | None++# A provider for conditional modifier used by cfg constructor function when constructing the+# configuration+ConditionalModifierInfo = provider(+ fields = {+ "inner": ModifierInfo,+ "key": TargetLabel,+ }+)++BuckconfigBackedModifierInfo = provider(+ fields = {+ "post_platform_modifiers": list[ConditionalModifierInfo],+ "pre_cli_modifiers": list[ConditionalModifierInfo],+ "pre_platform_modifiers": list[ConditionalModifierInfo],+ }+)++def is_modifiers_match(modifier: Modifier) -> bool:+ if modifier == None or isinstance(modifier, str):+ return False+ if isinstance(modifier, dict):+ if modifier["_type"] != "ModifiersMatch":+ fail("Found unknown dictionary `{}` for modifier".format(modifier))+ return True+ fail("Modifier should either be None, a string, or dict. Found `{}`".format(modifier))
@@ -0,0 +1,262 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup", "ScriptLanguage")+load("@prelude//utils:arglike.bzl", "ArgLike") # @unused: Used as a type++def command_alias_impl(ctx: AnalysisContext):+ target_os = ctx.attrs._target_os_type[OsLookup]++ if target_os.os == Os("fat_mac_linux") and len(ctx.attrs.platform_exe) > 0:+ base = {+ "Darwin": _get_os_base(ctx, Os("macos")),+ "Linux": _get_os_base(ctx, Os("linux")),+ }+ else:+ base = _get_os_base(ctx, target_os.os)++ output = command_alias(+ actions = ctx.actions,+ path = ctx.attrs.executable_name,+ target_os = target_os,+ base = base,+ args = cmd_args(ctx.attrs.args),+ env = ctx.attrs.env,+ labels = ctx.attrs.labels,+ )++ default_info = DefaultInfo(+ default_output = output.output.default_outputs[0],+ other_outputs = list(output.output.other_outputs) + ctx.attrs.resources,+ )++ # FIXME(JakobDegen): We should not accept `platform_exe` as meaning `run_using_single_arg`, but+ # there are things that depend on that+ #+ # FIXME(JakobDegen): It's easy to end up depending on either one of these behaviors. Life would+ # probably be easier if we just always went the `output.cmd` route+ if (+ output.maybe_directly_runnable == None+ or ctx.attrs.run_using_single_arg+ or ctx.attrs.executable_name != None+ or (len(ctx.attrs.platform_exe) > 0 and target_os.script == ScriptLanguage("sh"))+ ):+ run_info = RunInfo(args = output.cmd)+ else:+ run_info = RunInfo(args = output.maybe_directly_runnable)++ run_info_with_resources = RunInfo(+ args = cmd_args(run_info, hidden = ctx.attrs.resources),+ )++ return [default_info, run_info_with_resources]++def _get_os_base(ctx: AnalysisContext, os: Os) -> RunInfo:+ exe = ctx.attrs.platform_exe.get(os.value)+ if exe == None:+ exe = ctx.attrs.exe++ if exe == None:+ return RunInfo()++ if isinstance(exe, Artifact):+ return RunInfo(args = cmd_args(exe))++ run_info = exe.get(RunInfo)+ if run_info == None:+ run_info = RunInfo(+ args = exe[DefaultInfo].default_outputs,+ )++ return run_info++CommandAliasOutput = record(+ # A batch or sh script representing the command alias+ #+ # `DefaultInfo` instead of `Artifact` because the `other_outputs` will usually need to be+ # included as hidden somewhere+ output = DefaultInfo,+ # The output wrapped into a `cmd_args` in the obvious way+ cmd = cmd_args,+ # For some values of the arguments to `command_alias` it is possible to represent the+ # command_alias entirely within a `cmd_args`, without needing to write out a script. If that is+ # the case, those args are made available here.+ maybe_directly_runnable = cmd_args | None,+)++def command_alias(+ *,+ actions: AnalysisActions,+ # The path at which to write the output to, without an extension - that will be added+ path: str | None,+ # The target where this script should be able to run (this may actually be your exec platform)+ target_os: OsLookup,+ # Either the `RunInfo` to use, or in the case of a fat platform, the choice of `RunInfo`+ # depending on `uname`+ base: RunInfo | dict[str, RunInfo],+ args: cmd_args,+ env: dict[str, ArgLike],+ labels: list[str],+ has_content_based_path: bool = False,+) -> CommandAliasOutput:+ if path == "":+ fail("Path cannot be empty string")++ if path != None:+ # Custom paths are usually provided for binaries that are searched for with a particular+ # name. On Windows, the .bat extension is required, and well-behaved tools will respect the+ # PATHEXT environment variable (which contains that extension). On Unix, no extension is+ # expected for executables, and searches would likely fail if we added one.+ unix_trampoline_path = path+ windows_trampoline_path = path + ".bat"+ else:+ # Preserve the `.sh` extension in the default path, since many places have it hard-coded.+ unix_trampoline_path = "__command_alias_trampoline.sh"+ windows_trampoline_path = "__command_alias_trampoline.bat"++ if target_os.script == ScriptLanguage("sh"):+ trampoline, hidden = _command_alias_write_trampoline_unix(actions, unix_trampoline_path, base, args, env, has_content_based_path)+ elif target_os.script == ScriptLanguage("bat"):+ trampoline, hidden = _command_alias_write_trampoline_windows(actions, windows_trampoline_path, base, args, env, labels, has_content_based_path)+ else:+ fail("Unsupported script language: {}".format(target_os.script))++ if len(env) > 0 or isinstance(base, dict):+ maybe_directly_runnable = None+ else:+ maybe_directly_runnable = cmd_args(base.args, args)++ return CommandAliasOutput(+ output = DefaultInfo(+ default_output = trampoline,+ other_outputs = [hidden],+ ),+ cmd = cmd_args(trampoline, hidden = hidden),+ maybe_directly_runnable = maybe_directly_runnable,+ )++def _command_alias_write_trampoline_unix(+ actions: AnalysisActions, path: str, base: RunInfo | dict[str, RunInfo], args: cmd_args, env: dict[str, ArgLike], has_content_based_path: bool+) -> (Artifact, cmd_args):+ trampoline_args = cmd_args()+ trampoline_args.add("#!/usr/bin/env bash")+ trampoline_args.add("set -euo pipefail")++ if isinstance(base, dict):+ trampoline_args.add('case "$(uname)" in')+ for uname, run_info in base.items():+ trampoline_args.add(" {})".format(uname))+ _add_args_declaration_to_trampoline_args(trampoline_args, run_info, args)+ trampoline_args.add(" ;;")+ trampoline_args.add("esac")+ else:+ _add_args_declaration_to_trampoline_args(trampoline_args, base, args)++ # We can't use cwd relative paths (since we don't know the cwd when this script is run) and so+ # we instead use paths relative to the script itself. However, we can't just naively stick a+ # `$(...)` into `absolute_prefix`, since we must also shell quote paths, and that expression+ # would be shell quoted.+ #+ # Instead, we use `BUCK_COMMAND_ALIAS_ABSOLUTE_PREFIX/`, verbatim, as an absolute prefix on the+ # cmd_args, and then replace that with the actual path of the script at runtime+ #+ # Resolve symlinks first to handle execution via symlinks (e.g., in link-trees)+ trampoline_args.add(+ """+SCRIPT_PATH="$0"+if [ -L "$SCRIPT_PATH" ]; then+ TARGET="$(readlink "$SCRIPT_PATH")"+ SCRIPT_PATH="$(dirname "$SCRIPT_PATH")/$TARGET"+fi+""",+ )++ # Calculate the base path and process arguments with the resolved path.+ trampoline_args.add(+ """+BASE=$(cd -- "$(dirname "$SCRIPT_PATH")" >/dev/null 2>&1 ; pwd -P)+R_ARGS=()+for arg in "${ARGS[@]}"; do+ # Normalize Windows-style backslash path separators to forward slashes for+ # artifact paths (identified by the prefix placeholder). This handles the case+ # where Buck2 runs on Windows but this trampoline executes on Linux via RE.+ if [[ "$arg" == *BUCK_COMMAND_ALIAS_ABSOLUTE_PREFIX* ]]; then arg="${arg//\\\\//}"; fi+ R_ARGS+=("${arg//BUCK_COMMAND_ALIAS_ABSOLUTE_PREFIX/$BASE}")+done+""",+ )++ for k, v in env.items():+ # TODO(akozhevnikov): maybe check environment variable is not conflicting with pre-existing one+ trampoline_args.add(cmd_args("export ", k, "=", cmd_args(v, quote = "shell"), delimiter = ""))+ trampoline_args.add(cmd_args("export ", k, '="${', k, '//BUCK_COMMAND_ALIAS_ABSOLUTE_PREFIX/$BASE}"', delimiter = ""))++ trampoline_args.add('exec "${R_ARGS[@]}" "$@"')++ trampoline = actions.declare_output(path, has_content_based_path = has_content_based_path)+ trampoline_args = cmd_args(+ trampoline_args,+ relative_to = (trampoline, 1),+ absolute_prefix = "BUCK_COMMAND_ALIAS_ABSOLUTE_PREFIX/",+ )+ actions.write(+ trampoline.as_output(),+ trampoline_args,+ allow_args = True,+ is_executable = True,+ has_content_based_path = has_content_based_path,+ )++ return trampoline, trampoline_args++def _command_alias_write_trampoline_windows(+ actions: AnalysisActions, path: str, base: RunInfo, args: cmd_args, env: dict[str, ArgLike], labels: list[str], has_content_based_path: bool+) -> (Artifact, cmd_args):+ trampoline_args = cmd_args()+ trampoline_args.add("@echo off")++ if "close_stdin" in labels:+ # Avoids waiting for input on the "Terminate batch job (Y/N)?" prompt.+ # The prompt itself is unavoidable, but we can avoid having to wait for input.+ # This will call the same trampoline batch file with stdin disabled+ trampoline_args.add("if not defined STDIN_CLOSED (set STDIN_CLOSED=1 & CALL <NUL %0 %* & GOTO :EOF)")++ # Set BUCK_COMMAND_ALIAS_ABSOLUTE to the drive and full path of the script being created here+ # We use this below to prefix any artifacts being referenced in the script+ trampoline_args.add("set BUCK_COMMAND_ALIAS_ABSOLUTE=%~dp0")++ # Handle envs+ for k, v in env.items():+ # TODO(akozhevnikov): maybe check environment variable is not conflicting with pre-existing one+ trampoline_args.add(cmd_args(["set ", k, "=", v], delimiter = ""))++ # FIXME(JakobDegen): This should be batch quoting, not shell quoting+ cmd = cmd_args(cmd_args(base.args, args, quote = "shell"), "%*", delimiter = " ")++ trampoline_args.add(cmd)++ trampoline = actions.declare_output(path, has_content_based_path = has_content_based_path)+ trampoline_args = cmd_args(+ trampoline_args,+ relative_to = (trampoline, 1),+ absolute_prefix = "%BUCK_COMMAND_ALIAS_ABSOLUTE%/",+ )+ actions.write(+ trampoline.as_output(),+ trampoline_args,+ allow_args = True,+ is_executable = True,+ has_content_based_path = has_content_based_path,+ )++ return trampoline, trampoline_args++def _add_args_declaration_to_trampoline_args(trampoline_args: cmd_args, base: RunInfo, args: cmd_args):+ trampoline_args.add("ARGS=(")+ trampoline_args.add(cmd_args(base.args, args, quote = "shell"))+ trampoline_args.add(")")
@@ -0,0 +1,114 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:native.bzl", "native")++"""+Macros to help migrate from constraint_setting/constraint_value to the unified constraint() rule.++Usage:++ load("@prelude//configurations:constraint_alias.bzl", "constraint_with_aliases")++ # Simple case: all values get aliases with the same name+ constraint_with_aliases(+ name = "os",+ values = ["linux", "macos", "windows", "none"],+ default = "none",+ visibility = ["PUBLIC"],+ )+ # Creates:+ # - constraint(name = "os", values = [...], default = "none")+ # - configuration_alias(name = "linux", actual = ":os[linux]")+ # - configuration_alias(name = "macos", actual = ":os[macos]")+ # - etc.++ # Custom aliases: map old target names to new subtarget values+ constraint_with_aliases(+ name = "cgo_enabled",+ values = ["true", "false"],+ default = "false",+ aliases = {+ "cgo_enabled_true": "true",+ "cgo_enabled_false": "false",+ },+ visibility = ["PUBLIC"],+ )+ # Creates:+ # - constraint(name = "cgo_enabled", values = ["true", "false"], default = "false")+ # - configuration_alias(name = "cgo_enabled_true", actual = ":cgo_enabled[true]")+ # - configuration_alias(name = "cgo_enabled_false", actual = ":cgo_enabled[false]")+"""++def constraint_with_aliases(+ name: str, values: list[str], default: str, visibility: list[str] = ["PUBLIC"], aliases: dict[str, str] | None = None, execution_modifier: bool = False+):+ """+ Creates a unified constraint rule with backwards-compatible configuration aliases.++ Args:+ name: The name of the constraint setting+ values: List of constraint values+ default: The default value (must be in values)+ visibility: Visibility for the constraint and aliases+ aliases: Optional mapping of alias target names to value names.+ If None, creates aliases for all values using the value name as the alias name.+ Example: {"old_name": "new_value"} creates alias "old_name" pointing to ":name[new_value]"+ execution_modifier: If True, enables exec modifier resolution for this constraint.+ """+ native.constraint(+ name = name,+ values = values,+ default = default,+ visibility = visibility,+ execution_modifier = execution_modifier,+ )++ if aliases == None:+ # Default: create aliases for all values with the same name+ for value in values:+ native.configuration_alias(+ name = value,+ actual = ":{}[{}]".format(name, value),+ visibility = visibility,+ )+ else:+ # Custom aliases: use the provided mapping+ for alias_name, value in aliases.items():+ native.configuration_alias(+ name = alias_name,+ actual = ":{}[{}]".format(name, value),+ visibility = visibility,+ )++def generate_constraint_aliases(constraint_name: str, aliases: dict[str, str] | list[str], visibility: list[str] = ["PUBLIC"]):+ """+ Generates configuration aliases for an existing constraint.++ Args:+ constraint_name: The name of the constraint setting (without leading colon)+ aliases: Either a list of value names (aliases will have the same name),+ or a dict mapping alias names to value names.+ visibility: Visibility for the aliases+ """+ if type(aliases) == type([]):+ # List of values: alias name equals value name+ for value in aliases:+ native.configuration_alias(+ name = value,+ actual = ":{}[{}]".format(constraint_name, value),+ visibility = visibility,+ )+ else:+ # Dict mapping alias names to values+ for alias_name, value in aliases.items():+ native.configuration_alias(+ name = alias_name,+ actual = ":{}[{}]".format(constraint_name, value),+ visibility = visibility,+ )
@@ -0,0 +1,211 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//cfg/modifier:constraint_modifier_info.bzl", "make_constraint_modifier_info")+load("@prelude//cfg/modifier:types.bzl", "ConditionalModifierInfo")+load(":util.bzl", "util")++_ExecutionModifierInfo = provider(+ fields = {+ "execution_modifier": bool,+ }+)++def config_setting_impl(ctx):+ subinfos = [util.constraint_values_to_configuration(ctx.attrs.constraint_values)]+ subinfos.append(+ util.configuration_info(+ constraints = {},+ values = ctx.attrs.values,+ root_values = ctx.attrs.root_values,+ )+ )+ cfg_info = util.configuration_info_union(subinfos)+ providers = [DefaultInfo(), cfg_info]+ if len(ctx.attrs.constraint_values) == 1:+ # When only have one constraint, we return an additional ConditionalModifierInfo provider for+ # conditional modifier+ conditional_modifier_info = ctx.attrs.constraint_values[0][ConditionalModifierInfo]+ providers.append(conditional_modifier_info)+ return providers++def constraint_setting_impl(ctx):+ return [+ DefaultInfo(),+ ConstraintSettingInfo(label = ctx.label.raw_target()),+ # In order for the constraint_value to access the execution modifier info, we need to provide an additional provider here.+ _ExecutionModifierInfo(execution_modifier = ctx.attrs.execution_modifier),+ ]++def constraint_value_impl(ctx):+ constraint_value = ConstraintValueInfo(+ setting = ctx.attrs.constraint_setting[ConstraintSettingInfo],+ label = ctx.label.raw_target(),+ )+ execution_modifier_info = ctx.attrs.constraint_setting[_ExecutionModifierInfo]++ return [+ DefaultInfo(),+ constraint_value,+ # Provide `ConfigurationInfo` from `constraint_value` so it could be used as select key.+ ConfigurationInfo(+ constraints = {+ constraint_value.setting.label: constraint_value,+ },+ values = {},+ ),+ make_constraint_modifier_info(+ constraint_value = constraint_value,+ key = constraint_value.setting.label,+ execution_modifier = execution_modifier_info.execution_modifier,+ exec_platform_marker_configuration_info = ctx.attrs._exec_platform_marker[ConfigurationInfo],+ ),+ ]++def constraint_impl(ctx):+ # Validate values are unique and non-empty+ values = ctx.attrs.values++ min_values = 1 if ctx.attrs.allow_trivial_constraint else 2+ if len(values) < min_values:+ if ctx.attrs.allow_trivial_constraint:+ fail("constraint() rule must have at least one value.")+ else:+ fail(+ "constraint() rule must have at least two values. "+ + "A single-value constraint has no selectivity: it can't express a choice between alternatives "+ + "(e.g., 'linux' vs 'macos', 'enabled' vs 'disabled'), which is the whole point of a constraint. "+ + "If you don't need to select between alternatives, you likely don't need a constraint at all.\n\n"+ + "Set allow_trivial_constraint = True only if your constraint legitimately has just one value "+ + "most of the time and may temporarily gain alternatives (e.g., versioned packages "+ + "that pick up an extra value during an upgrade and drop it once the upgrade lands).",+ )++ default = ctx.attrs.default++ # Value-name reservations:+ # - 'DEFAULT' is always reserved, to avoid visual confusion with the special `[default]` subtarget.+ # - 'default' is allowed only when it is itself the default value, in which case it coincides with the+ # `[default]` subtarget added below. Otherwise `[default]` would be ambiguous, so it is rejected.+ seen = set()+ for v in values:+ if v == "DEFAULT":+ fail("'DEFAULT' is a reserved keyword and cannot be used as a constraint value. Use a different name to avoid confusion.")+ if v == "default" and default != "default":+ fail(+ "'default' can be used as a constraint value only when it is also the default value "+ + "(i.e. default = \"default\"); otherwise ':{}[default]' is ambiguous between the value ".format(ctx.label.name)+ + "named 'default' and the default value '{}'.".format(default),+ )+ if v in seen:+ fail("Duplicate value '{}' in constraint()".format(v))+ seen.add(v)++ # Validate default is one of the declared values.+ if default not in seen:+ fail("default value '{}' must be one of the declared values: {}".format(default, values))++ # Main target provides the constraint setting+ main_label = ctx.label.raw_target()+ constraint_setting = ConstraintSettingInfo(+ label = main_label,+ default = main_label.with_sub_target(default),+ )++ # exec_platform_marker_constraint() and constraint() rule both use this impl,+ # but only constraint() has this attribute.+ exec_platform_marker_configuration_info = None+ if hasattr(ctx.attrs, "_exec_platform_marker"):+ exec_platform_marker_configuration_info = ctx.attrs._exec_platform_marker[ConfigurationInfo]++ execution_modifier = False+ if hasattr(ctx.attrs, "execution_modifier"):+ execution_modifier = ctx.attrs.execution_modifier++ # Create subtargets for each value+ sub_targets = {}+ for value_name in values:+ # Create a constraint value for this subtarget+ constraint_value = ConstraintValueInfo(+ setting = constraint_setting,+ label = main_label.with_sub_target(value_name),+ )++ sub_targets[value_name] = [+ DefaultInfo(),+ constraint_value,+ ConfigurationInfo(+ constraints = {+ main_label: constraint_value,+ },+ values = {},+ ),+ make_constraint_modifier_info(+ constraint_value = constraint_value,+ key = main_label,+ execution_modifier = execution_modifier,+ exec_platform_marker_configuration_info = exec_platform_marker_configuration_info,+ ),+ ]++ # Add 'default' subtarget that aliases to the actual default value+ sub_targets["default"] = sub_targets[default]++ # Validate and register user-defined aliases.+ # Each alias becomes an additional subtarget pointing to an existing value's providers.+ reserved_keywords = ["default", "DEFAULT"]+ aliases = ctx.attrs.aliases+ for alias_name, alias_value in aliases.items():+ if alias_name in reserved_keywords:+ fail("alias '{}' is a reserved keyword and cannot be used as a constraint alias.".format(alias_name))+ if alias_name in seen:+ fail("alias '{}' conflicts with a declared constraint value.".format(alias_name))+ if alias_value not in seen:+ fail("alias '{}' targets value '{}' which is not declared in values: {}".format(alias_name, alias_value, values))+ sub_targets[alias_name] = sub_targets[alias_value]++ return [+ DefaultInfo(sub_targets = sub_targets),+ constraint_setting,+ ]++def platform_impl(ctx):+ subinfos = [dep[PlatformInfo].configuration for dep in ctx.attrs.deps] + [util.constraint_values_to_configuration(ctx.attrs.constraint_values)]+ return [+ DefaultInfo(),+ PlatformInfo(+ label = str(ctx.label.raw_target()),+ # TODO(nga): current behavior is the last constraint value for constraint setting wins.+ # This allows overriding constraint values from dependencies, and moreover,+ # it allows overriding constraint values from constraint values listed+ # in the same `constraint_values` attribute earlier.+ # If this is intentional, state it explicitly.+ # Otherwise, fix it.+ configuration = util.configuration_info_union(subinfos),+ ),+ ]++def configuration_alias_impl(ctx: AnalysisContext) -> list[Provider]:+ return ctx.attrs.actual.providers++# TODO(cjhopman): Update the attributes for these ruletypes to declare the types of providers that they expect in their references.+extra_attributes = {+ "platform": {+ "constraint_values": attrs.list(attrs.dep(providers = [ConstraintValueInfo]), default = []),+ },+}++implemented_rules = {+ "config_setting": config_setting_impl,+ "configuration_alias": configuration_alias_impl,+ "constraint": constraint_impl,+ "constraint_setting": constraint_setting_impl,+ "constraint_value": constraint_value_impl,+ "exec_platform_marker_constraint": constraint_impl,+ "platform": platform_impl,+}
@@ -0,0 +1,43 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++def _configuration_info(constraints, values, root_values = None):+ return ConfigurationInfo(+ constraints = constraints,+ values = values,+ root_values = root_values or {},+ )++def _configuration_info_union(infos):+ if len(infos) == 0:+ return _configuration_info(+ constraints = {},+ values = {},+ )+ if len(infos) == 1:+ return infos[0]+ constraints = {k: v for info in infos for (k, v) in info.constraints.items()}+ values = {k: v for info in infos for (k, v) in info.values.items()}+ root_values = {k: v for info in infos for (k, v) in info.root_values.items()}+ return _configuration_info(+ constraints = constraints,+ values = values,+ root_values = root_values,+ )++def _constraint_values_to_configuration(values):+ return _configuration_info(+ constraints = {info[ConstraintValueInfo].setting.label: info[ConstraintValueInfo] for info in values},+ values = {},+ )++util = struct(+ configuration_info = _configuration_info,+ configuration_info_union = _configuration_info_union,+ constraint_values_to_configuration = _constraint_values_to_configuration,+)
@@ -0,0 +1,73 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++def make_content_based_dist(ctx: AnalysisContext, name: str, exe: Artifact, copies: dict = {}, symlinks: dict = {}) -> (Artifact, Artifact):+ """+ Package a relocatable executable that depends on adjacent files into a single+ content-based directory, so it is self-contained at a content-addressed+ buck-out path. A content change re-hashes the whole directory to a new path+ while the old one persists -- the property that lets a long-running `buck2+ run` binary survive concurrent rebuilds.++ `exe` is COPIED into the directory. Its self-relative lookups -- an `$ORIGIN`+ RPATH, a `current_exe`-relative `.resources.json`, an inplace-PAR+ `$(dirname $(readlink -f $0))`-relative `#link-tree`, etc. -- only resolve+ inside the directory if the exe physically lives there; a symlinked exe would+ resolve them against its realpath instead. Entries in `copies` are laid out+ as real bytes (use for small generated files the bundle should own, e.g. a+ relocatable resource DB); entries in `symlinks` are symlinks to their source+ artifacts (use for large dependencies, to avoid duplicating bytes).++ THE IMMUTABILITY CONTRACT IS PER-ENTRY: the bundle's content hash captures+ copied entries' BYTES but only symlinked entries' TARGET PATHS. A COPIED+ entry is therefore always trample-safe. A SYMLINKED entry is trample-safe+ IFF its target artifact is itself content-based (immutable path); a+ symlink to a config-based artifact keeps pointing at a path whose bytes a+ rebuild rewrites in place -- without re-hashing this bundle. Callers must+ route mutable inputs through `copies` (or make them content-based) when+ they need whole-bundle immutability.++ `copies` and `symlinks` are dicts of path-in-dir (string, relative to the+ result directory) to a bound `artifact`.++ Returns `(bundle_dir, exe)` where `exe` is the copied exe projected back out+ of the bundle, for use as a `RunInfo` command and/or `DefaultInfo` output.+ """+ # Feature-detected (getattr, not a static reference) so this module still+ # LOADS under a buck2 that predates `assembled_dir` (D107250277) -- the+ # static type-checker rejects unknown globals/methods at module-load time,+ # which would break every rust_binary analysis on older binaries. Reaching+ # this function without the API (i.e. actually opting a target in) is a+ # hard, explicit error instead.+ entry_ctors = getattr(__buck2_builtins__, "assembled_dir", None)+ make_assembled_dir = getattr(ctx.actions, "assembled_dir", None)+ if entry_ctors == None or make_assembled_dir == None:+ fail(+ "content-based dist bundles require a buck2 with " + "`ctx.actions.assembled_dir` (D107250277); this buck2 predates it",+ )++ exe_rel = exe.short_path+ contents = {exe_rel: entry_ctors.copy(exe)}++ # Duplicate destinations would silently overwrite dict entries here --+ # including the exe's own entry -- before `assembled_dir`'s non-overlap+ # validation ever sees them. Reject them loudly instead.+ for path, artifact in copies.items():+ if path in contents:+ fail("make_content_based_dist: duplicate bundle destination `{}` (copies)".format(path))+ contents[path] = entry_ctors.copy(artifact)+ for path, artifact in symlinks.items():+ if path in contents:+ fail("make_content_based_dist: duplicate bundle destination `{}` (symlinks)".format(path))+ contents[path] = entry_ctors.symlink(artifact)+ bundle = make_assembled_dir(+ name + "__dist",+ contents = contents,+ has_content_based_path = True,+ )+ return (bundle, bundle.project(exe_rel))
@@ -0,0 +1,53 @@+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("build_infra")++source_listing()++config_setting(+ name = "x86_64",+ constraint_values = [+ "prelude//cpu/constraints:cpu[x86_64]",+ ],+ visibility = ["PUBLIC"],+)++config_setting(+ name = "x86_32",+ constraint_values = [+ "prelude//cpu/constraints:cpu[x86_32]",+ ],+ visibility = ["PUBLIC"],+)++config_setting(+ name = "arm64",+ constraint_values = [+ "prelude//cpu/constraints:cpu[arm64]",+ ],+ visibility = ["PUBLIC"],+)++config_setting(+ name = "arm32",+ constraint_values = [+ "prelude//cpu/constraints:cpu[arm32]",+ ],+ visibility = ["PUBLIC"],+)++config_setting(+ name = "wasm32",+ constraint_values = [+ "prelude//cpu/constraints:cpu[wasm32]",+ ],+ visibility = ["PUBLIC"],+)++config_setting(+ name = "riscv64",+ constraint_values = [+ "prelude//cpu/constraints:cpu[riscv64]",+ ],+ visibility = ["PUBLIC"],+)
@@ -0,0 +1,30 @@+load("@prelude//configurations:constraint_alias.bzl", "constraint_with_aliases")+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("build_infra")++source_listing()++# Used by open source projects to support `prelude//`++constraint_with_aliases(+ name = "cpu",+ aliases = {+ "arm32": "arm32",+ "arm64": "arm64",+ "x86_32": "x86_32",+ "x86_64": "x86_64",+ },+ default = "unspecified",+ values = [+ "x86_64",+ "x86_32",+ "arm64",+ "arm64_32",+ "arm32",+ "wasm32",+ "riscv64",+ "unspecified",+ ],+ visibility = ["PUBLIC"],+)
@@ -0,0 +1,85 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(":csharp_providers.bzl", "DllDepTSet", "DllReference", "DotNetLibraryInfo", "generate_target_tset_children")+load(":toolchain.bzl", "CSharpToolchainInfo")++def csharp_library_impl(ctx: AnalysisContext) -> list[Provider]:+ toolchain = ctx.attrs._csharp_toolchain[CSharpToolchainInfo]++ # Automatically set the output dll_name to this target's name if the caller did not specify a+ # custom name.+ dll_name = "{}.dll".format(ctx.attrs.name) if not ctx.attrs.dll_name else ctx.attrs.dll_name++ # Declare that this rule will produce a dll.+ library = ctx.actions.declare_output(dll_name, has_content_based_path = False)++ # Create a command invoking a wrapper script that calls csc.exe to compile the .dll.+ cmd = [toolchain.csc]++ # Add caller specified compiler flags.+ cmd.append(ctx.attrs.compiler_flags)++ # Set the output target as a .NET library.+ cmd.append("/target:library")+ cmd.append(+ cmd_args(+ library.as_output(),+ format = "/out:{}",+ )+ )++ # Don't include any default .NET framework assemblies like "mscorlib" or "System" unless+ # explicitly requested with `/reference:{}`. This flag also stops injection of other+ # default compiler flags.+ cmd.append("/noconfig")++ # Don't reference mscorlib.dll unless asked for. This is required for targets that target+ # embedded platforms such as Silverlight or WASM. (Originally for Buck1 compatibility.)+ cmd.append("/nostdlib")++ # Don't search any paths for .NET libraries unless explicitly referenced with `/lib:{}`.+ cmd.append("/nosdkpath")++ # Let csc know the directory path where it can find system assemblies. This is the path+ # that is searched by `/reference:{libname}` if `libname` is just a DLL name.+ cmd.append(cmd_args(toolchain.framework_dirs[ctx.attrs.framework_ver], format = "/lib:{}"))++ # Add a `/reference:{name}` argument for each dependency.+ # Buck target refs should be absolute paths and system assemblies just the DLL name.+ child_deps = generate_target_tset_children(ctx.attrs.deps, ctx)+ deps_tset = ctx.actions.tset(DllDepTSet, children = child_deps)++ cmd.append(deps_tset.project_as_args("reference"))++ # Specify the C# source code files that should be compiled into this target.+ # NOTE: This must happen after /out and /target!+ cmd.append(ctx.attrs.srcs)++ # Run the C# compiler to produce the output artifact.+ ctx.actions.run(cmd, category = "csharp_compile")++ return [+ DefaultInfo(default_output = library),+ DotNetLibraryInfo(+ name = ctx.attrs.dll_name,+ object = library,+ dll_deps = ctx.actions.tset(DllDepTSet, value = DllReference(reference = library), children = child_deps),+ ),+ ]++def prebuilt_dotnet_library_impl(ctx: AnalysisContext) -> list[Provider]:+ # Prebuilt libraries are just passed through since they are already built.+ return [+ DefaultInfo(default_output = ctx.attrs.assembly),+ DotNetLibraryInfo(+ name = ctx.attrs.name,+ object = ctx.attrs.assembly,+ dll_deps = ctx.actions.tset(DllDepTSet, value = DllReference(reference = ctx.attrs.assembly)),+ ),+ ]
@@ -0,0 +1,63 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# Stores a reference to a Buck .NET DLL target (`Artifact`) or the name of an assembly dll (`str`)+# that can be found in the .NET framework SDK directory+DllReference = record(+ # `str` -> Path to a .NET framework DLL on the local machine.+ # `Artifact` -> Buck target dependency.+ reference = field([Artifact, str]),+)++def _args_for_dll_reference(dllref: DllReference) -> cmd_args:+ """Projects values in a `DllDepTSet` to csc.exe /reference:{dllname} arguments."""+ return cmd_args(dllref.reference, format = "/reference:{}")++# A transitive set of DLL references required to build a .NET library.+#+# The transitive set attribute `value` references the outputting assembly, and the children are a+# list of the dependencies required to build it.+DllDepTSet = transitive_set(+ args_projections = {+ # Projects "/reference:{}" arguments for `csc.exe`.+ "reference": _args_for_dll_reference,+ },+)++def generate_target_tset_children(deps: list[typing.Any], ctx: AnalysisContext) -> list[DllDepTSet]:+ """Convert a C# target's dependencies list into an array of transitive dependencies."""++ tset_children = []++ if deps:+ for dep in deps:+ if isinstance(dep, str):+ # Name of a .NET framework DLL (eg "System.Drawing.dll").+ tset_children.append(+ ctx.actions.tset(DllDepTSet, value = DllReference(reference = dep)),+ )+ else:+ # Buck target dependency (eg "//buck/path/to:foobar").+ # Adds all of the dependencies of the Buck target dependency to the tset.+ tset_children.append(dep.get(DotNetLibraryInfo).dll_deps)++ return tset_children++DotNetLibraryInfo = provider(+ doc = "Information about a .NET library and its dependencies",+ fields = {+ # A tset of DLLs (System or Buck targets) this library depends on. The+ # `.value` is a reference to the outputting assembly artifact, and the+ # children are the dependencies required to build it.+ "dll_deps": provider_field(DllDepTSet),+ # The output file name of the library.+ "name": provider_field(str),+ # The generated .dll artifact that will need to be linked into an .exe.+ "object": provider_field(Artifact),+ },+)
@@ -0,0 +1,14 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++CSharpToolchainInfo = provider(+ fields = [+ "csc",+ "framework_dirs",+ ]+)
@@ -0,0 +1,282 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactInfo",+ "make_artifact_tset",+)+load(+ "@prelude//cxx:cxx_toolchain_types.bzl",+ "CxxToolchainInfo",+ "LinkerType",+)+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference")+load(+ "@prelude//linking:link_info.bzl",+ "Archive",+ "ArchiveContentsType",+ "ArchiveLinkable",+ "DepMetadata",+ "LinkArgs",+ "LinkInfo", # @unused Used as a type+ "ObjectsLinkable",+ "SharedLibLinkable",+)+load(+ ":link_types.bzl",+ "CxxLinkResultType",+ "LinkOptions",+ "link_options",+)++# The link recipe is encoded as one JSON string of pure scalars/counts plus two+# flat streams (flags and artifacts) that both sides walk in the same traversal+# order. Encoding each linkable as nested attr tuples instead costs the daemon+# ~1KiB of coerced-attr nodes per linkable, which dominates buck2 memory on+# large link-group graphs (measured ~1GiB retained on a 14-target fbcode dev+# cohort); the artifacts must remain real `attrs.source()` values for input+# tracking, but everything else can live in the string.+#+# The anon target identity therefore hashes (recipe, flags, artifacts), which+# discriminates exactly like the nested encoding, except that external debug+# info labels are no longer part of the identity: deserialization always+# discarded them, so they only served to split otherwise-identical identities.++_LINK_ARGS_FLAGS_TAG = 0+_LINK_ARGS_INFOS_TAG = 1++_LINKABLE_ARCHIVE_TAG = 0+_LINKABLE_OBJECTS_TAG = 1+_LINKABLE_SHARED_TAG = 2++def _encode_linkable(linkable, artifacts: list[Artifact]):+ if isinstance(linkable, ArchiveLinkable):+ artifacts.append(linkable.archive.artifact)+ artifacts.extend(linkable.archive.external_objects)+ return [+ _LINKABLE_ARCHIVE_TAG,+ len(linkable.archive.external_objects),+ linkable.archive.archive_contents_type.value,+ linkable.link_whole,+ linkable.linker_type.value,+ linkable.supports_lto,+ ]++ if isinstance(linkable, ObjectsLinkable):+ artifacts.extend(linkable.objects)+ return [+ _LINKABLE_OBJECTS_TAG,+ len(linkable.objects),+ linkable.link_whole,+ linkable.linker_type.value,+ ]++ if isinstance(linkable, SharedLibLinkable):+ artifacts.append(linkable.lib)+ return [+ _LINKABLE_SHARED_TAG,+ linkable.link_without_soname,+ ]++ fail('cannot serialize linkable "{}"'.format(str(linkable)))++def _encode_link_info(info: LinkInfo, flags: list, artifacts: list[Artifact]):+ external_debug_artifacts = []+ if info.external_debug_info._tset != None:+ external_debug_infos = []+ for tset_infos in info.external_debug_info._tset.traverse():+ external_debug_infos.extend(tset_infos)+ for artifact_info in dedupe(external_debug_infos):+ external_debug_artifacts.extend(artifact_info.artifacts)++ flags.extend(info.pre_flags)+ flags.extend(info.post_flags)+ linkables = [_encode_linkable(linkable, artifacts) for linkable in info.linkables]+ artifacts.extend(external_debug_artifacts)++ return [+ len(info.pre_flags),+ len(info.post_flags),+ linkables,+ len(external_debug_artifacts),+ [m.version for m in info.metadata],+ ]++def _anon_link_flags(values: list) -> list:+ result = []+ for value in values:+ if isinstance(value, TransitiveSetArgsProjection) and value.projection_name == "linker_flags":+ # Anonymous attrs accept resolved macros, but not transitive-set projections.+ for shared_flags in value.transitive_set.traverse(ordering = "postorder"):+ result.extend(shared_flags.linker_flags)+ else:+ result.append(value)+ return result++def serialize_anon_attrs(output: str, result_type: CxxLinkResultType, opts: LinkOptions) -> dict[str, typing.Any]:+ # Anonymous links cannot run distributed ThinLTO (its dynamic outputs are+ # unsupported in anon targets; every anonymous caller disables it), and the+ # encoding relies on that: `LinkInfo.name` is not serialized, and dist+ # ThinLTO planning is the one consumer that reads it.+ if opts.enable_distributed_thinlto:+ fail("anonymous links do not support distributed ThinLTO")++ recipe = []+ flags = []+ artifacts = []+ for link in opts.links:+ if link.flags != None:+ link_flags = _anon_link_flags(link.flags)+ recipe.append([_LINK_ARGS_FLAGS_TAG, len(link_flags)])+ flags.extend(link_flags)+ elif link.infos != None:+ recipe.append([_LINK_ARGS_INFOS_TAG, [_encode_link_info(info, flags, artifacts) for info in link.infos]])+ else:+ fail("cannot serialize link args")++ return dict(+ links_recipe = json.encode(recipe),+ links_flags = flags,+ links_artifacts = artifacts,+ output = output,+ import_library = opts.import_library,+ link_execution_preference = opts.link_execution_preference.value,+ dwp_execution_preference = opts.dwp_execution_preference.value if opts.dwp_execution_preference != None else None,+ enable_distributed_thinlto = opts.enable_distributed_thinlto,+ identifier = opts.identifier,+ category_suffix = opts.category_suffix,+ result_type = result_type.value,+ allow_cache_upload = opts.allow_cache_upload,+ )++def _decode_linkable(spec, artifacts, artifact_cursor: list[int]) -> typing.Any:+ kind = spec[0]++ if kind == _LINKABLE_ARCHIVE_TAG:+ _, num_external_objects, archive_contents_type, link_whole, linker_type, supports_lto = spec+ archive_artifact = artifacts[artifact_cursor[0]]+ external_objects = artifacts[artifact_cursor[0] + 1 : artifact_cursor[0] + 1 + num_external_objects]+ artifact_cursor[0] += 1 + num_external_objects+ return ArchiveLinkable(+ archive = Archive(+ artifact = archive_artifact,+ external_objects = external_objects,+ archive_contents_type = ArchiveContentsType(archive_contents_type),+ ),+ link_whole = link_whole,+ linker_type = LinkerType(linker_type),+ supports_lto = supports_lto,+ )++ if kind == _LINKABLE_OBJECTS_TAG:+ _, num_objects, link_whole, linker_type = spec+ objects = artifacts[artifact_cursor[0] : artifact_cursor[0] + num_objects]+ artifact_cursor[0] += num_objects+ return ObjectsLinkable(+ objects = objects,+ link_whole = link_whole,+ linker_type = LinkerType(linker_type),+ )++ if kind == _LINKABLE_SHARED_TAG:+ _, link_without_soname = spec+ lib = artifacts[artifact_cursor[0]]+ artifact_cursor[0] += 1+ return SharedLibLinkable(+ lib = lib,+ link_without_soname = link_without_soname,+ )++ fail("Invalid linkable kind: {}".format(kind))++def _decode_link_info(actions: AnalysisActions, label: Label, spec, flags, flag_cursor: list[int], artifacts, artifact_cursor: list[int]) -> LinkInfo:+ num_pre_flags, num_post_flags, linkable_specs, num_external_debug_artifacts, metadata = spec++ pre_flags = flags[flag_cursor[0] : flag_cursor[0] + num_pre_flags]+ post_flags = flags[flag_cursor[0] + num_pre_flags : flag_cursor[0] + num_pre_flags + num_post_flags]+ flag_cursor[0] += num_pre_flags + num_post_flags++ linkables = [_decode_linkable(linkable_spec, artifacts, artifact_cursor) for linkable_spec in linkable_specs]++ external_debug_artifacts = artifacts[artifact_cursor[0] : artifact_cursor[0] + num_external_debug_artifacts]+ artifact_cursor[0] += num_external_debug_artifacts++ return LinkInfo(+ name = None,+ pre_flags = pre_flags,+ post_flags = post_flags,+ linkables = linkables,+ external_debug_info = make_artifact_tset(+ actions = actions,+ infos = [ArtifactInfo(label = label, artifacts = external_debug_artifacts, tags = [])] if external_debug_artifacts else [],+ ),+ metadata = [DepMetadata(version = v) for v in metadata],+ )++def deserialize_anon_attrs(actions: AnalysisActions, label: Label, attrs: struct) -> (str, CxxLinkResultType, LinkOptions):+ flag_cursor = [0]+ artifact_cursor = [0]+ links = []+ for entry in json.decode(attrs.links_recipe):+ if entry[0] == _LINK_ARGS_FLAGS_TAG:+ num_flags = entry[1]+ links.append(LinkArgs(flags = attrs.links_flags[flag_cursor[0] : flag_cursor[0] + num_flags]))+ flag_cursor[0] += num_flags+ elif entry[0] == _LINK_ARGS_INFOS_TAG:+ links.append(+ LinkArgs(+ infos = [_decode_link_info(actions, label, spec, attrs.links_flags, flag_cursor, attrs.links_artifacts, artifact_cursor) for spec in entry[1]]+ )+ )+ else:+ fail("Invalid link args kind: {}".format(entry[0]))++ if flag_cursor[0] != len(attrs.links_flags) or artifact_cursor[0] != len(attrs.links_artifacts):+ fail(+ "anon link recipe did not consume its flag/artifact streams exactly (flags {}/{}, artifacts {}/{})".format(+ flag_cursor[0],+ len(attrs.links_flags),+ artifact_cursor[0],+ len(attrs.links_artifacts),+ )+ )++ opts = link_options(+ links = links,+ import_library = attrs.import_library,+ link_execution_preference = LinkExecutionPreference(attrs.link_execution_preference),+ dwp_execution_preference = LinkExecutionPreference(attrs.dwp_execution_preference) if attrs.dwp_execution_preference != None else None,+ category_suffix = attrs.category_suffix,+ identifier = attrs.identifier,+ enable_distributed_thinlto = attrs.enable_distributed_thinlto,+ allow_cache_upload = attrs.allow_cache_upload,+ )++ result_type = CxxLinkResultType(attrs.result_type)++ return (attrs.output, result_type, opts)++# The attributes -- and their serialized types -- that can be passed to an+# anonymous link. See the module docblock for the stream encoding contract.+ANON_ATTRS = {+ "allow_cache_upload": attrs.bool(),+ "category_suffix": attrs.string(),+ "dwp_execution_preference": attrs.option(attrs.enum(LinkExecutionPreference.values()), default = None),+ "enable_distributed_thinlto": attrs.bool(),+ "identifier": attrs.option(attrs.string(), default = None),+ "import_library": attrs.option(attrs.source(), default = None),+ "link_execution_preference": attrs.enum(LinkExecutionPreference.values()),+ "links_artifacts": attrs.list(attrs.source(), default = []),+ "links_flags": attrs.list(attrs.arg(), default = []),+ "links_recipe": attrs.string(default = "[]"),+ "output": attrs.string(),+ "result_type": attrs.enum(CxxLinkResultType.values()),+ "separate_debug_info": attrs.bool(default = False),+ "_cxx_toolchain": attrs.dep(providers = [CxxToolchainInfo]),+}
@@ -0,0 +1,155 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//cxx:cxx_toolchain_types.bzl", "LinkerInfo", "LinkerType")+load("@prelude//linking:link_info.bzl", "Archive", "ArchiveContentsType")+load("@prelude//utils:argfile.bzl", "at_argfile")+load("@prelude//utils:utils.bzl", "value_or")+load(":cxx_context.bzl", "get_cxx_toolchain_info")++def archive_flags(archiver_type: str, linker_type: LinkerType, use_archiver_flags: bool, symbol_table: bool, thin: bool) -> list[str]:+ if not use_archiver_flags:+ return []++ if archiver_type == "windows":+ if thin:+ fail("'windows' archiver doesn't support thin archives")+ return ["/Brepro", "/d2threads1"]+ elif archiver_type == "windows_clang":+ return ["/llvmlibthin"] if thin else []+ elif archiver_type == "amdclang":+ # amdclang can be used to create archives with --emit-static-lib, so let's+ # prefer to let the toolchain define the args instead of hardcoding them here.+ return []+ flags = ""++ # Operate in quick append mode, so that objects with identical basenames+ # won't overwrite one another.+ flags += "q"++ # Suppress warning about creating a new archive.+ flags += "c"++ # Run ranlib to generate symbol index for faster linking if requested.+ flags += "s" if symbol_table else "S"++ # Generate thin archives.+ if thin:+ flags += "T"++ # GNU archivers support generating deterministic archives.+ if linker_type == LinkerType("gnu"):+ flags += "D"++ return [flags]++_ARCHIVE_ENV = {"ZERO_AR_DATE": "1"}++# Create a static library from a list of object files.+def _archive(+ ctx: AnalysisContext, name: str, args: cmd_args, thin: bool, prefer_local: bool, allow_cache_upload: bool, force_disable_content_based_path: bool = False+) -> Artifact:+ toolchain = get_cxx_toolchain_info(ctx)+ has_content_based_path = (toolchain.linker_info.supports_content_based_paths_for_archiving == True) and not force_disable_content_based_path+ archive_output = ctx.actions.declare_output(name, has_content_based_path = has_content_based_path)+ command = cmd_args(toolchain.linker_info.archiver)+ archiver_type = toolchain.linker_info.archiver_type+ command.add(+ archive_flags(+ archiver_type,+ toolchain.linker_info.type,+ toolchain.linker_info.use_archiver_flags,+ toolchain.linker_info.archive_symbol_table,+ thin,+ )+ )+ if archiver_type == "windows" or archiver_type == "windows_clang":+ command.add([cmd_args(archive_output.as_output(), format = "/OUT:{}")])+ elif archiver_type == "amdclang":+ command.add(["-o", archive_output.as_output()])+ else:+ command.add([archive_output.as_output()])++ if toolchain.linker_info.archiver_supports_argfiles:+ shell_quoted_args = cmd_args(args, quote = "shell")+ if toolchain.linker_info.use_archiver_flags and toolchain.linker_info.archiver_flags != None:+ shell_quoted_args.add(toolchain.linker_info.archiver_flags)++ command.add(+ at_argfile(+ actions = ctx.actions,+ name = name + ".cxx_archive_argsfile",+ args = shell_quoted_args,+ allow_args = True,+ has_content_based_path = has_content_based_path,+ )+ )+ else:+ command.add(args)++ # By default, the archive header produced by `ar q` embeds the current unix+ # timestamp. With the GNU archiver we use `ar qD` (above in _archive_flags)+ # to make it produce a deterministic archive by zeroing the timestamp, but+ # other archivers do not support such a flag. Some implementations, notably+ # Xcode's, instead support zeroing the timestamp by way of an environment+ # variable.+ env = _ARCHIVE_ENV++ category = "archive"+ if thin:+ category = "archive_thin"+ ctx.actions.run(+ command,+ category = category,+ identifier = name,+ env = env,+ prefer_local = prefer_local,+ allow_cache_upload = allow_cache_upload,+ )+ return archive_output++def _archive_locally(ctx: AnalysisContext, linker_info: LinkerInfo) -> bool:+ archive_locally = linker_info.archive_objects_locally+ if hasattr(ctx.attrs, "_archive_objects_locally_override"):+ return value_or(ctx.attrs._archive_objects_locally_override, archive_locally)+ return archive_locally++def _archive_allow_cache_upload(ctx: AnalysisContext) -> bool:+ return getattr(ctx.attrs, "archive_allow_cache_upload", False)++# Creates a static library given a list of object files.+def make_archive(+ ctx: AnalysisContext, name: str, objects: list[Artifact], hidden: list[Artifact] = [], force_disable_content_based_path: bool = False+) -> Archive:+ if len(objects) == 0:+ fail("no objects to archive")++ linker_info = get_cxx_toolchain_info(ctx).linker_info+ thin = linker_info.archive_contents == "thin"+ object_args = cmd_args(objects)+ args = cmd_args(object_args, hidden = hidden)+ archive = _archive(+ ctx,+ name,+ args,+ thin = thin,+ prefer_local = _archive_locally(ctx, linker_info),+ allow_cache_upload = _archive_allow_cache_upload(ctx),+ force_disable_content_based_path = force_disable_content_based_path,+ )++ # TODO(T110378125): use argsfiles for GNU archiver for long lists of objects.+ # TODO(T110378123): for BSD archiver, split long args over multiple invocations.+ # TODO(T110378100): We need to scrub the static library (timestamps, permissions, etc) as those are+ # sources of non-determinism. See `ObjectFileScrubbers.createDateUidGidScrubber()` in Buck v1.++ return Archive(+ artifact = archive,+ archive_contents_type = ArchiveContentsType(linker_info.archive_contents),+ external_objects = objects,+ )
@@ -0,0 +1,50 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++ARGSFILES_SUBTARGET = "argsfiles"++# Information on argsfiles created for compilation.+CompileArgsfile = record(+ # The generated argsfile (does not contain dependent inputs).+ file = field(Artifact),+ # This argsfile as a command form that would use the argsfile (includes dependent inputs).+ cmd_form = field(cmd_args),+ # Command form for the NVCC dry run: the argsfile, the argsfiles it+ # references and the header maps the flags name, but not the header trees+ # or other artifacts behind the flags. Only built for CUDA sources.+ cmd_form_cuda_dryrun = field(cmd_args | None, None),+ # Args as written to the argsfile (with shell quoting applied).+ args = field(cmd_args),+ # Args aggregated for the argsfile excluding file prefix args (excludes shell quoting).+ args_without_file_prefix_args = field(cmd_args),+ # The generated GCC specs file carrying the file-prefix-map flags, when the+ # compiler takes them that way. None for compilers given the flags directly.+ file_prefix_specs = field(Artifact | None, None),+)++CompileArgsfiles = record(+ # Relative path argsfiles used for build actions, mapped by extension.+ relative = field(dict[str, CompileArgsfile], default = {}),+ # Argsfiles used for Xcode integration, mapped by extension.+ xcode = field(dict[str, CompileArgsfile], default = {}),+)++def get_argsfiles_output(ctx: AnalysisContext, argsfile_by_ext: dict[str, CompileArgsfile], summary_name: str) -> DefaultInfo:+ argsfiles = []+ dependent_outputs = []+ for _, argsfile in argsfile_by_ext.items():+ argsfiles.append(argsfile.file)++ # To materialize the dependent `Artifact`s of `CompileArgsfile#file`,+ # `CompileArgsfile#cmd_form` is returned in `DefaultInfo#other_outputs`,+ # because it tracks the dependents through the `cmd_args` API.+ dependent_outputs.append(argsfile.cmd_form)++ argsfiles_summary = ctx.actions.write(summary_name, argsfiles, has_content_based_path = False)++ return DefaultInfo(default_outputs = [argsfiles_summary], other_outputs = argsfiles + dependent_outputs)
@@ -0,0 +1,66 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++def cxx_by_language_ext(x: dict[typing.Any, typing.Any], ext: str) -> list[typing.Any]:+ # lang_preprocessor_flags is indexed by c/cxx+ # lang_compiler_flags is indexed by c_cpp_output/cxx_cpp_output+ # so write a function that can do either+ #+ # === Buck v1 Compatibility ===+ #+ # `lang_compiler_flags` keys are coerced to CxxSource,+ # so the allowable values are the lowercase versions of the enum values.+ #+ # The keys themselves should be the _output_ type of the language. For example,+ # for Obj-C, that would be OBJC_CPP_OUTPUT.+ #+ # The actual lookup for `lang_compiler_flags` happens in+ # CxxSourceRuleFactory::getRuleCompileFlags().+ #+ # `lang_preprocessor_flags` keys are also coerced to CxxSource.+ # The keys are the _input_ type of the language. For example, for Obj-C,+ # that would be OBJC.+ if ext == ".c":+ key_pp = "c"++ # TODO(gabrielrc): v1 docs have other keys+ # https://buck.build/rule/cxx_library.html#lang_compiler_flags+ # And you can see them in java code, but somehow it works with+ # this one, which is seem across the repo. Find out what's happening.+ key_compiler = "c_cpp_output"+ elif ext in (".cpp", ".cc", ".cl", ".cxx", ".c++", ".bc"):+ key_pp = "cxx"+ key_compiler = "cxx_cpp_output"+ elif ext == ".m":+ key_pp = "objc"+ key_compiler = "objc_cpp_output"+ elif ext == ".mm":+ key_pp = "objcxx"+ key_compiler = "objcxx_cpp_output"+ elif ext in (".s", ".sx", ".S"):+ key_pp = "assembler_with_cpp"+ key_compiler = "assembler"+ elif ext == ".cu":+ key_pp = "cuda"+ key_compiler = "cuda_cpp_output"+ elif ext == ".hip":+ key_pp = "hip"+ key_compiler = "hip_cpp_output"+ elif ext in (".asm", ".asmpp"):+ key_pp = "asm_with_cpp"+ key_compiler = "asm"+ elif ext in (".h", ".hpp", ".hh", ".hxx", ".h++"):+ fail("Not allowed to have header files in the `srcs` attribute - put them in `headers`")+ else:+ fail("Unexpected file extension: " + ext)+ res = []+ if key_pp in x:+ res += x[key_pp]+ if key_compiler in x:+ res += x[key_compiler]+ return res
@@ -0,0 +1,92 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//cxx:cxx_toolchain_types.bzl", "LinkerInfo")+load("@prelude//utils:argfile.bzl", "at_argfile")+load("@prelude//utils:utils.bzl", "value_or")+load(":cxx_context.bzl", "get_cxx_toolchain_info")++BitcodeBundle = record(+ artifact = field(Artifact),+)++BitcodeTSet = transitive_set()++BitcodeBundleInfo = provider(+ fields = {+ "bitcode": provider_field(typing.Any, default = None),+ "bitcode_bundle": provider_field(typing.Any, default = None),+ }+)++def _bundle_locally(ctx: AnalysisContext, linker_info: LinkerInfo) -> bool:+ archive_locally = linker_info.archive_objects_locally+ if hasattr(ctx.attrs, "_archive_objects_locally_override"):+ return value_or(ctx.attrs._archive_objects_locally_override, archive_locally)+ return archive_locally++def _bundle(ctx: AnalysisContext, name: str, args: cmd_args, prefer_local: bool) -> Artifact:+ llvm_link = get_cxx_toolchain_info(ctx).llvm_link+ if llvm_link == None:+ fail("Bitcode generation not supported when no LLVM linker, the `cxx_toolchain` has no `llvm_link`.")++ bundle_output = ctx.actions.declare_output(name, has_content_based_path = False)++ command = at_argfile(+ actions = ctx.actions,+ name = name + ".cxx_bitcode_argsfile",+ args = args,+ allow_args = True,+ )+ llvm_cmd = cmd_args(+ llvm_link,+ command,+ "-v",+ "-o",+ bundle_output.as_output(),+ )++ ctx.actions.run(llvm_cmd, category = "bitcode_bundle", identifier = name, prefer_local = prefer_local)+ return bundle_output++# Creates a static library given a list of object files.+def make_bitcode_bundle(ctx: AnalysisContext, name: str, objects: list[Artifact], ignore_native: bool = False, override: bool = False) -> [BitcodeBundle, None]:+ if len(objects) == 0:+ fail("no objects to archive")++ llvm_link = get_cxx_toolchain_info(ctx).llvm_link+ if llvm_link == None:+ return None++ linker_info = get_cxx_toolchain_info(ctx).linker_info++ args = cmd_args(quote = "shell")+ if ignore_native:+ args.add("--ignore-non-bitcode")++ if override and len(objects) > 1:+ args.add(objects[0])+ overrides = cmd_args(objects[1:], format = "--override={}")+ args.add(overrides)+ else:+ args.add(objects)++ bundle = _bundle(ctx, name, args, _bundle_locally(ctx, linker_info))++ return BitcodeBundle(artifact = bundle)++def llvm_link_bitcode_impl(ctx: AnalysisContext) -> list[Provider]:+ llvm_link = get_cxx_toolchain_info(ctx).llvm_link+ if llvm_link == None:+ fail("llvm-link is not provided by toolchain.")++ result = make_bitcode_bundle(ctx, ctx.attrs.name, ctx.attrs.srcs)+ if result != None:+ return [DefaultInfo(default_output = result.artifact), BitcodeBundleInfo(bitcode_bundle = result)]+ else:+ return [DefaultInfo()]
@@ -0,0 +1,63 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++ClangProfileListInfo = provider(+ fields = {+ "profile_list": provider_field(Artifact),+ }+)++def get_coverage_profile_list_artifact(dep: [Dependency, None]) -> [Artifact, None]:+ """Extract the profile list artifact from a clang_profile_list dependency."""+ if dep == None:+ return None+ info = dep.get(ClangProfileListInfo)+ if info == None:+ return None+ return info.profile_list++def _clang_profile_list_impl(ctx: AnalysisContext) -> list[Provider]:+ """+ Generates a clang profile list file for use with -fprofile-list.++ When `srcs` is non-empty (selective coverage), generates a file that+ instruments only the listed source files:+ [clang]+ source:<path>=allow+ ...+ default:skip++ When `srcs` is empty (whole coverage), generates a file that instruments+ everything:+ [clang]+ default:allow+ """+ lines = ["[clang]"]+ for src_path in ctx.attrs.srcs:+ # Use wildcard prefix to match both direct source paths (fbcode/path/to/file.cpp)+ # and symlink tree paths (buck-out/.../buck-headers/path/to/file.h)+ lines.append("source:*{}=allow".format(src_path))+ if ctx.attrs.srcs:+ lines.append("default:skip")+ else:+ lines.append("default:allow")+ lines.append("")++ profile_list = ctx.actions.write("profile_list.txt", "\n".join(lines), has_content_based_path = True)++ return [+ DefaultInfo(default_output = profile_list),+ ClangProfileListInfo(profile_list = profile_list),+ ]++clang_profile_list = rule(+ impl = _clang_profile_list_impl,+ attrs = {+ "srcs": attrs.list(attrs.string(), default = []),+ },+)
@@ -0,0 +1,133 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxInternalTools", "CxxPlatformInfo", "CxxToolchainInfo")+load("@prelude//utils:argfile.bzl", "at_argfile")+load(+ ":compile_types.bzl",+ "CxxSrcCompileCommand", # @unused Used as a type+)+load(":cxx_context.bzl", "get_cxx_toolchain_info")+load(":cxx_library_utility.bzl", "EMPTY_DEFAULT_INFO")++# Provider that exposes the compilation database information+CxxCompilationDbInfo = provider(+ fields = {+ "info": provider_field(typing.Any, default = None), # A map of the file (an `Artifact`) to its corresponding `CxxSrcCompileCommand`+ "platform": provider_field(typing.Any, default = None), # platform for this compilation database+ "toolchain": provider_field(typing.Any, default = None), # toolchain for this compilation database+ }+)++def make_compilation_db_info(+ src_compile_cmds: list[CxxSrcCompileCommand], toolchainInfo: CxxToolchainInfo, platformInfo: CxxPlatformInfo+) -> CxxCompilationDbInfo:+ info = {}+ for src_compile_cmd in src_compile_cmds:+ info.update({src_compile_cmd.src: src_compile_cmd})++ return CxxCompilationDbInfo(info = info, toolchain = toolchainInfo, platform = platformInfo)++def _comp_database_entry_path(identifier: str, src_path: str) -> str:+ return paths.join(identifier, "__comp_db__", src_path + ".comp_db.json")++def _create_comp_database_impl(+ actions: AnalysisActions,+ internal_tools: CxxInternalTools,+ identifier: str,+ src_compile_cmds: list[CxxSrcCompileCommand],+ db: OutputArtifact,+ entries: dict[str, OutputArtifact],+) -> list[Provider]:+ mk_comp_db = internal_tools.make_comp_db++ # Generate the per-source compilation DB entries.+ entries_as_input = []+ for src_compile_cmd in src_compile_cmds:+ cdb_path = _comp_database_entry_path(identifier, src_compile_cmd.src.short_path)+ entry = entries.pop(cdb_path, None)+ if entry:+ cmd = cmd_args(+ mk_comp_db,+ "gen",+ cmd_args(entry, format = "--output={}"),+ src_compile_cmd.src.basename,+ cmd_args(src_compile_cmd.src, parent = 1),+ "--",+ src_compile_cmd.cxx_compile_cmd.base_compile_cmd,+ src_compile_cmd.cxx_compile_cmd.argsfile.cmd_form,+ src_compile_cmd.args,+ )+ entry_identifier = paths.join(identifier, src_compile_cmd.src.short_path)+ actions.run(cmd, category = "cxx_compilation_database", identifier = entry_identifier)+ entries_as_input.append(entry.as_input())++ # Merge all entries into the actual compilation DB.+ cmd = cmd_args(mk_comp_db)+ cmd.add("merge")+ cmd.add(cmd_args(db, format = "--output={}"))++ cmd.add(+ at_argfile(+ actions = actions,+ name = identifier + ".cxx_comp_db_argsfile",+ args = entries_as_input,+ )+ )++ actions.run(cmd, category = "cxx_compilation_database_merge", identifier = identifier)++ return [EMPTY_DEFAULT_INFO]++_dynamic_compilation_database_rule = dynamic_actions(+ impl = _create_comp_database_impl,+ attrs = {+ "db": dynattrs.output(),+ "entries": dynattrs.dict(str, dynattrs.output()),+ "identifier": dynattrs.value(str),+ "internal_tools": dynattrs.value(CxxInternalTools),+ "src_compile_cmds": dynattrs.list(dynattrs.value(CxxSrcCompileCommand)),+ },+)++def create_compilation_database(ctx: AnalysisContext, src_compile_cmds: list[CxxSrcCompileCommand], identifier: str) -> DefaultInfo:+ actions = ctx.actions++ # Generate the per-source compilation DB entries.+ entries = {}+ other_outputs = []++ for src_compile_cmd in src_compile_cmds:+ cdb_path = _comp_database_entry_path(identifier, src_compile_cmd.src.short_path)+ if cdb_path not in entries:+ entry = actions.declare_output(cdb_path, has_content_based_path = False)++ # Add all inputs the command uses to runtime files.+ other_outputs.append(entry)+ other_outputs.append(src_compile_cmd.src)+ other_outputs.append(src_compile_cmd.cxx_compile_cmd.base_compile_cmd)+ other_outputs.append(src_compile_cmd.cxx_compile_cmd.argsfile.cmd_form)+ entries[cdb_path] = entry.as_output()++ # Merge all entries into the actual compilation DB.+ db = actions.declare_output(paths.join(identifier, "compile_commands.json"), has_content_based_path = False)++ # We don't have any dynamic inputs here and use dynamic action purely as an optimization+ # so we don't occupy memory in analysis graph until we actually need compilation database.+ actions.dynamic_output_new(+ _dynamic_compilation_database_rule(+ db = db.as_output(),+ entries = entries,+ identifier = identifier,+ internal_tools = get_cxx_toolchain_info(ctx).internal_tools,+ src_compile_cmds = src_compile_cmds,+ ),+ )++ return DefaultInfo(default_output = db, other_outputs = other_outputs)
@@ -0,0 +1,73 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Handles labels used to provide compilation database information for filegroup() and genrule() targets.++Our language services need to know how to compile files owned solely by filegroup() or genrule() targets like:+* Regular generated sources, that then end up being compiled by regular cxx_ or apple_ targets.+* Manually declared mixin files, that are always compiled by multiple other targets spread across the codebase.+* Files built by external build systems wrapped in genrules(), where compile_commands.json is produced by yet another genrule().++Prior approach for the former two cases was to run rdeps() queries to find a compilable target that would have a compile_commands.json entry for the file.+It suffered from reliability and performance issues, as the universe for rdeps() queries had to be quite broad and with no guarantee that there isn't even a single broken target within it.+And for external build system wrappers where there is no compilable target, we could define a rule that would effectively wrap two genrules and expose one of them as [compilation-database] subtarget,+but that wouldn't solve the problem with mixins which is still relevant with external build systems and would put us in the same suboptimal spot in terms of performance and reliability.++As the IDE needs to operate in O(changes) instead of O(repo), and open files even if some other corner of the repo is broken.+We need to make things both reliable and performant in an ever-growing codebase with a CI that explicitly cannot guarantee that the entire repo is green, and where rdeps() queries are thus flaky and slow.++And as the IDE needs to react to any local changes and act consistently with local checkout, we cannot simply use a remote cache for rdeps() queries that are slow and flaky.++So the solution is instead to localize the required information within the target, and directly point to the build system rules that provide compile_commands.json for the target.+"""++def compilation_database_rules(source_mapping: dict[str, list[str]] | list[str]) -> list[str]:+ """+ Takes a mapping from sources to the rules to be used to build compilation databases for those sources.++ Tooling like IDEs needs to obtain compile commands for source files that are exported by filegroup() to be built as part of another target, or are built with an external build system wrapped in a genrule().+ Labels provide a convenient way to link the non-compileable target with a rule that produces a compilation database for its sources:+ ```+ load("@prelude//cxx:compilation_database_labels.bzl", "compilation_database_rules")++ # The shorthand way for most cases:+ export_file(+ name = "gadget_to_be_compiled_as_part_of_another_target.cpp",+ labels = compilation_database_rules([+ "//path/to/some/dependent:target",+ "//path/to/another/dependent:target",+ ])+ )++ # A per-source mapping for cases when the generated files from one genrule() are compiled in different targets and never together:+ genrule(+ name = "multiple_gadgets_for_different_purposes",+ labels = compilation_database_rules({+ "server_gen.cpp": ["//path/to/dependent/module:server"],+ "client_gen.cpp": ["//path/to/dependent/module:client"],+ })+ )+ ```+ The tooling can use a BXL script to check the target kind and extract the compilation database rule from its labels. And then iterate over the resulting compilation database and resolve the symlinks in 'file' entries in order to find the matching entry for the original source.++ :param dict[str,str]|list[str] source_mapping: A mapping with source file name regex as key and target as value. The target has to be either a target with [compilation-database] subtarget, or a genrule that produces compile_commands.json (for wrapping external build systems).+ """+ if not isinstance(source_mapping, dict):+ source_mapping = {".*": source_mapping}+ return ["compilation_database_rules=" + json.encode(source_mapping)]++def get_compilation_database_rules(labels = list[str]) -> dict[str, list[str]] | None:+ """+ Retrieves and decodes compilation database targets from target labels, if any.+ """+ for label in labels:+ value = label.removeprefix("compilation_database_rules=")+ if value != label:+ return json.decode(value)+ return None
@@ -0,0 +1,2754 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load(+ "@prelude//cxx:compile_types.bzl",+ "AsmExtensions",+ "CudaDistributedCompileOutput",+ "CxxCompileCommand",+ "CxxCompileCommandOutput",+ "CxxCompileFlavor",+ "CxxCompileOutput",+ "CxxExtension",+ "CxxSrcCompileCommand",+ "CxxSrcPrecompileCommand",+ "DepFileType",+ "HeaderExtension",+ "HeadersDepFiles",+ "IndexStoreFactory",+ "UseHeaderUnitsMode",+)+load(+ "@prelude//cxx:cuda.bzl",+ "CudaCompileInfo",+ "CudaCompileStyle", # @unused Used as a type+ "CudaDistributedCompileSpec", # @unused Used as a type+ "create_cuda_distributed_compiles",+ "cuda_compile",+ "declare_cuda_dist_compile_output",+)+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")+load("@prelude//cxx:hip_debug_extract.bzl", "hip_debug_extract_available", "hip_debug_extract_compile_object")+load(+ "@prelude//ide_integrations/xcode:argsfiles.bzl",+ "XCODE_ARG_SUBSTITUTIONS",+)+load("@prelude//linking:lto.bzl", "LtoMode")+load("@prelude//utils:argfile.bzl", "argsfile_with_artifacts", _mk_argsfile = "mk_argsfile")+load("@prelude//utils:expect.bzl", "expect")+load(+ "@prelude//utils:utils.bzl",+ "as_output",+ "flatten",+ "map_val",+)+load(":argsfiles.bzl", "CompileArgsfile", "CompileArgsfiles")+load(":attr_selection.bzl", "cxx_by_language_ext")+load(+ ":compiler.bzl",+ "get_flags_for_colorful_output",+ "get_flags_for_reproducible_build",+ "get_headers_dep_files_flags_factory",+ "get_output_flags",+)+load(":cxx_context.bzl", "get_cxx_toolchain_info")+load(+ ":cxx_flags.bzl",+ "CxxFlagsInfo",+ "cxx_flags_projection_name",+ "cxx_flags_tset",+)+load(":cxx_library_utility.bzl", "EMPTY_DEFAULT_INFO")+load(":cxx_sources.bzl", "CxxSrcWithFlags")+load(":cxx_toolchain_types.bzl", "CxxObjectFormat", "DepTrackingMode", "compiler_info_with_argsfiles")+load(":cxx_types.bzl", "CxxRuleConstructorParams")+load(":debug.bzl", "SplitDebugMode")+load(+ ":headers.bzl",+ "CHeader",+ "CPrecompiledHeaderInfo",+ "CxxPrecompiledHeader", # @unused Used in type annotation+ "add_headers_dep_files",+)+load(+ ":preprocessor.bzl",+ "CPreprocessor", # @unused Used as a type+ "CPreprocessorInfo", # @unused Used as a type+ "HeaderUnit", # @unused Used as a type+ "cxx_merge_cpreprocessors",+ "get_flags_for_compiler_type",+)++# Output folder shared by every per-source object declaration; the shared CUDA+# plan must declare its outputs under the same folder as the objects it feeds.+_OBJECTS_FOLDER = "__objects__"++_CUDA_DRYRUN_SOURCE_PLACEHOLDER = "__buck2_cuda_dryrun_placeholder__.cu"++# Record containing compile info that will be passed to the dynamic action+CxxCompileInfo = record(+ src = field(Artifact),+ args = field(list[typing.Any]),+ short_path = field(str),+ filename_base = field(str),+ index_store_base = field(str | None), # filename_base for index store compilation+ identifier = field(str),+ folder_name = field(str),+)++CxxSharedCompileInfo = record(+ cxx_compile_cmd = field(CxxCompileCommand),+ index_store_factory = field(IndexStoreFactory | None),+ error_handler = field([typing.Callable, None]),+ expect_eligible_for_dedupe = field(bool),+)++# Input for a single CXX compilation - declared artifacts and compile info+CxxCompileInput = record(+ declared_artifacts = field(CxxCompileOutput),+ info = field(CxxCompileInfo),+)++CxxSharedCompileCommandArgs = record(+ before_src = field(cmd_args),+ after_src = field(cmd_args),+)++def _project_clang_traces_as_args(traces: list[Artifact]):+ return cmd_args(traces)++ClangTracesTSet = transitive_set(+ args_projections = {+ "clang_traces": _project_clang_traces_as_args,+ },+)++ClangTracesInfo = provider(+ fields = {+ "clang_traces": provider_field(typing.Any, default = None), # "ClangTracesTSet"+ }+)+PicClangTracesInfo = provider(+ fields = {+ "clang_traces": provider_field(typing.Any, default = None), # "ClangTracesTSet"+ }+)++def get_source_extension_for_header(header_extension: str, default: CxxExtension) -> CxxExtension:+ """+ Which source file extension to use to get compiler flags for the header.+ """+ if header_extension in (".hpp", ".hh", ".h++", ".hxx"):+ return CxxExtension(".cpp")+ elif header_extension == ".cuh":+ return CxxExtension(".cu")+ elif header_extension not in HeaderExtension.values():+ return CxxExtension(header_extension) # a file in `headers` has a source extension+ else:+ return default++def get_source_extension(src: CxxSrcWithFlags, default_for_headers: CxxExtension) -> CxxExtension:+ """+ Which source files extension to use for a source or a header file. We want+ headers to appear as though they are source files.+ """+ if src.is_header:+ return get_source_extension_for_header(src.file.extension, default_for_headers)+ else:+ return CxxExtension(src.file.extension)++def collect_extensions(srcs: list[CxxSrcWithFlags]) -> set[CxxExtension]:+ """+ Collect extensions of source files while doing light normalization.+ """++ duplicates = {+ ".c++": ".cpp",+ ".cc": ".cpp",+ ".cxx": ".cpp",+ }++ extensions = set([CxxExtension(duplicates.get(src.file.extension, src.file.extension)) for src in srcs])+ return extensions++def default_source_extension_for_plain_header(rule_type: str) -> CxxExtension:+ """+ Returns default source file extension to use to get get compiler flags for plain .h headers.+ """++ # Default to (Objective-)C++ instead of plain (Objective-)C as it is more likely to be compatible with both.+ return CxxExtension(".mm") if rule_type.startswith("apple_") else CxxExtension(".cpp")++def detect_source_extension_for_plain_headers(exts: set[CxxExtension], rule_type: str) -> CxxExtension:+ """+ For a given list source files determine which source file extension+ to use to get compiler flags for plain .h headers.+ """++ # Assembly doesn't need any special handling as included files tend to have .asm extension themselves.+ # And the presence of assembly in the target doesn't tell us anything about the language of .h files.+ for asm_ext in AsmExtensions:+ exts.discard(asm_ext)++ if len(exts) == 0:+ return default_source_extension_for_plain_header(rule_type)++ if len(exts) == 1:+ return exts.pop()+ if CxxExtension(".hip") in exts:+ return CxxExtension(".hip")+ if CxxExtension(".cu") in exts:+ return CxxExtension(".cu")+ if CxxExtension(".mm") in exts:+ return CxxExtension(".mm")+ if CxxExtension(".cpp") in exts and CxxExtension(".m") in exts:+ return CxxExtension(".mm")+ if CxxExtension(".cpp") in exts:+ return CxxExtension(".cpp")+ if CxxExtension(".m") in exts:+ return CxxExtension(".m")+ return CxxExtension(".c")++def collect_source_extensions(srcs: list[CxxSrcWithFlags], default_for_headers: CxxExtension) -> set[CxxExtension]:+ """+ Return unique source extensions from a list of source and header files where+ header extensions are mapped to corresponding source extensions.+ """+ source_extensions = set([get_source_extension(src, default_for_headers) for src in srcs])+ return source_extensions++def get_header_language_mode(source_extension: CxxExtension) -> str | None:+ """+ Returns the header mode to use for plain .h headers based on the+ source file extension used to obtain the compiler flags for them.+ """++ # Note: CUDA doesn't have its own header language mode, but the headers have distinct .cuh extension.+ modes = {+ CxxExtension(".cpp"): "c++-header",+ CxxExtension(".m"): "objective-c-header",+ CxxExtension(".mm"): "objective-c++-header",+ }+ return modes.get(source_extension)++def create_compile_cmds(+ actions: AnalysisActions,+ target_label: Label,+ toolchain: CxxToolchainInfo,+ impl_params: CxxRuleConstructorParams,+ own_preprocessors: list[CPreprocessor],+ inherited_preprocessor_infos: list[CPreprocessorInfo],+ add_coverage_instrumentation_compiler_flags: bool,+ compile_pch: CxxPrecompiledHeader | None = None,+ filename_prefix: str = "",+) -> CxxCompileCommandOutput:+ """+ Forms the CxxSrcCompileCommand to use for each source file based on it's extension+ and optional source file flags. Returns CxxCompileCommandOutput containing an array+ of the generated compile commands and argsfile output.+ """++ if compile_pch:+ srcs_extensions = set([CxxExtension(compile_pch.clanguage)])+ else:+ srcs_extensions = collect_extensions(impl_params.srcs)+ extension_for_plain_headers = detect_source_extension_for_plain_headers(srcs_extensions, impl_params.rule_type)++ srcs_with_flags = [] # type: [CxxSrcWithFlags]++ for src in impl_params.srcs:+ srcs_with_flags.append(src)++ # Some targets have .cpp files in their `headers` lists, see D46195628+ # todo: should this be prohibited or expanded to allow all source extensions?+ artifact_extensions = HeaderExtension.values() + [".cpp"]+ all_headers = flatten([x.headers for x in own_preprocessors])+ for header in all_headers:+ if header.artifact.extension in artifact_extensions:+ srcs_with_flags.append(CxxSrcWithFlags(file = header.artifact, is_header = True))++ all_raw_headers = flatten([x.raw_headers for x in own_preprocessors])+ for header in all_raw_headers:+ if header.extension in HeaderExtension.values():+ srcs_with_flags.append(CxxSrcWithFlags(file = header, is_header = True))++ if len(srcs_with_flags) == 0:+ return CxxCompileCommandOutput()++ # TODO(T110378129): Buck v1 validates *all* headers used by a compilation+ # at compile time, but that doing that here/eagerly might be expensive (but+ # we should figure out something).+ _validate_target_headers(target_label, own_preprocessors)++ # Combine all preprocessor info and prepare it for compilations.+ pre = cxx_merge_cpreprocessors(+ actions,+ filter(None, own_preprocessors + impl_params.extra_preprocessors),+ inherited_preprocessor_infos,+ )++ headers_tag = actions.artifact_tag()++ src_compile_cmds = []+ hdr_compile_cmds = []+ cxx_compile_cmd_by_ext = {} # type: dict[CxxExtension, CxxCompileCommand]+ argsfile_by_ext = {} # type: dict[str, CompileArgsfile]+ xcode_argsfile_by_ext = {} # type: dict[str, CompileArgsfile]+ if compile_pch:+ src_extensions = [CxxExtension(compile_pch.clanguage)]+ else:+ src_extensions = collect_source_extensions(srcs_with_flags, extension_for_plain_headers)++ # Deduplicate shared arguments to save memory. If we compile multiple files+ # of the same extension they will have some of the same flags. Save on+ # allocations by caching and reusing these objects.+ for ext in src_extensions:+ cmd = _generate_base_compile_command(+ actions,+ target_label,+ toolchain,+ impl_params,+ pre,+ headers_tag,+ ext,+ filename_prefix = filename_prefix,+ )+ cxx_compile_cmd_by_ext[ext] = cmd+ argsfile_by_ext[ext.value] = cmd.argsfile+ if cmd.xcode_argsfile != None:+ xcode_argsfile_by_ext[ext.value] = cmd.xcode_argsfile++ # Add -fprofile-list for selective coverage instrumentation.+ # The profile list file is generated by a clang_profile_list rule and tells+ # clang which source files to instrument, reducing overhead.+ coverage_profile_list_args = []+ if add_coverage_instrumentation_compiler_flags and impl_params.coverage_profile_list:+ coverage_profile_list_args = [cmd_args(impl_params.coverage_profile_list, format = "-fprofile-list={}")]++ for src in srcs_with_flags:+ src_args = []+ src_args.extend(src.flags)++ if compile_pch:+ ext = CxxExtension(compile_pch.clanguage)+ else:+ ext = get_source_extension(src, extension_for_plain_headers)++ cxx_compile_cmd = cxx_compile_cmd_by_ext[ext]++ if add_coverage_instrumentation_compiler_flags and cxx_compile_cmd.compiler_type != "gcc":+ src_args.extend(impl_params.coverage_instrumentation_compiler_flags)+ src_args.extend(coverage_profile_list_args)++ if src.is_header or compile_pch:+ if cxx_compile_cmd.compiler_type in ["clang", "clang_windows", "gcc"]:+ language_mode = get_header_language_mode(ext)+ src_args.extend(["-x", language_mode] if language_mode else [])+ elif cxx_compile_cmd.compiler_type in ["clang_cl", "windows", "windows_ml64"] and ext == CxxExtension(".cpp"):+ src_args.append("/TP")++ if cxx_compile_cmd.compiler_type != "nasm":+ src_args.append("-c")++ src_args.append(src.file)++ src_compile_command = CxxSrcCompileCommand(+ src = src.file,+ cxx_compile_cmd = cxx_compile_cmd,+ args = src_args,+ index = src.index,+ is_header = src.is_header,+ uses_content_based_paths = cxx_compile_cmd.allow_content_based_paths,+ index_store_factory = impl_params.index_store_factory,+ error_handler = impl_params.error_handler,+ expect_eligible_for_dedupe = impl_params.expect_eligible_for_dedupe,+ )++ if src.is_header:+ hdr_compile_cmds.append(src_compile_command)+ else:+ src_compile_cmds.append(src_compile_command)++ argsfile_by_ext.update(impl_params.additional.argsfiles.relative)+ xcode_argsfile_by_ext.update(impl_params.additional.argsfiles.xcode)++ return CxxCompileCommandOutput(+ src_compile_cmds = src_compile_cmds,+ base_compile_cmds = cxx_compile_cmd_by_ext,+ argsfiles = CompileArgsfiles(+ relative = argsfile_by_ext,+ xcode = xcode_argsfile_by_ext,+ ),+ comp_db_compile_cmds = src_compile_cmds + hdr_compile_cmds,+ )++COMMON_PREPROCESSOR_OUTPUT_ARGS = cmd_args("-E", "-dD")++def _prepare_cxx_compilation(+ actions: AnalysisActions,+ toolchain: CxxToolchainInfo,+ default_object_format: CxxObjectFormat,+ src_compile_cmd: CxxSrcCompileCommand,+ flavors: set[CxxCompileFlavor],+ provide_syntax_only: bool,+ use_header_units: UseHeaderUnitsMode,+ separate_debug_info: bool,+ cuda_compile_style: CudaCompileStyle | None,+ shared_cuda_dist_output: CudaDistributedCompileOutput | None,+ compile_pch: CxxPrecompiledHeader | None,+) -> CxxCompileInput:+ """+ DECLARATION PHASE: Declares all output artifacts for a single source file compilation.+ """+ short_path = src_compile_cmd.src.short_path+ if src_compile_cmd.index != None:+ # Add a unique postfix if we have duplicate source files with different flags+ short_path = short_path + "_" + str(src_compile_cmd.index)++ filename_base = short_path+ identifier = short_path++ if (+ src_compile_cmd.cxx_compile_cmd.category == "cxx_compile"+ and use_header_units == UseHeaderUnitsMode("pcm")+ and src_compile_cmd.cxx_compile_cmd.header_units_argsfile+ ):+ identifier += " (modular)"++ for flavor in flavors:+ filename_base = "{}.{}".format(filename_base, flavor.value)+ identifier = "{} ({})".format(identifier, flavor.value)++ content_based = src_compile_cmd.uses_content_based_paths+ folder_name = _OBJECTS_FOLDER+ compiler_type = src_compile_cmd.cxx_compile_cmd.compiler_type++ # Declare main object output+ object = actions.declare_output(+ folder_name,+ "{}.{}".format(filename_base, toolchain.linker_info.object_file_extension),+ has_content_based_path = content_based,+ )++ # Diagnostics+ diagnostics = None+ clang_tidy_diagnostics = None+ if compiler_type == "clang" and provide_syntax_only:+ diagnostics = actions.declare_output(+ "__diagnostics__",+ "{}.diag.txt".format(short_path),+ has_content_based_path = False,+ )+ if toolchain.binary_utilities_info.custom_tools.get("clang-tidy"):+ clang_tidy_diagnostics = actions.declare_output(+ "__diagnostics__",+ "{}.clang-tidy.txt".format(short_path),+ has_content_based_path = False,+ )++ # Declare index store upfront using factory.declare() if available+ index_store = None+ index_store_base = None+ if CxxCompileFlavor("pic") in flavors and src_compile_cmd.index_store_factory:+ factory = src_compile_cmd.index_store_factory+ declared_index_store = factory.declare(actions, src_compile_cmd)+ if declared_index_store:+ index_store = declared_index_store.output+ index_store_base = declared_index_store.filename_base++ # Clang LLVM statistics+ clang_llvm_statistics = None+ if toolchain.clang_llvm_statistics and compiler_type == "clang":+ clang_llvm_statistics = actions.declare_output(+ paths.join("__objects__", "{}.stats".format(filename_base)),+ has_content_based_path = content_based,+ )++ # GCNO file+ gcno_file = None+ if toolchain.gcno_files and src_compile_cmd.src.extension not in (".S", ".sx"):+ gcno_file = actions.declare_output(+ paths.join("__objects__", "{}.gcno".format(filename_base)),+ has_content_based_path = content_based,+ )++ # Clang remarks+ clang_remarks = None+ if toolchain.clang_remarks and compiler_type == "clang":+ clang_remarks = actions.declare_output(+ paths.join("__objects__", "{}.opt.yaml".format(filename_base)),+ has_content_based_path = content_based,+ )++ # Generate pre-processed sources+ preproc = actions.declare_output(+ "__preprocessed__",+ "{}.{}".format(filename_base, "i"),+ has_content_based_path = content_based,+ )++ # External debug info+ external_debug_info = None+ extension_supports_external_debug_info = src_compile_cmd.src.extension not in (".hip")+ use_external_debug_info = (+ separate_debug_info and toolchain.split_debug_mode == SplitDebugMode("split") and compiler_type == "clang" and extension_supports_external_debug_info+ )+ if use_external_debug_info:+ external_debug_info = actions.declare_output(+ folder_name,+ "{}.{}".format(filename_base, "dwo"),+ has_content_based_path = content_based,+ )++ # .S extension is native assembly code (machine level, processor specific)+ # and clang will happily compile them to .o files, but the object are always+ # native even if we ask for bitcode. If we don't mark the output format,+ # other tools would try and parse the .o file as LLVM-IR and fail.+ if src_compile_cmd.src.extension in [".S", ".s"]:+ object_format = CxxObjectFormat("native")+ else:+ object_format = default_object_format++ assembly = _declare_assembly(+ actions = actions,+ compiler_type = compiler_type,+ object_format = object_format,+ filename_base = filename_base,+ content_based = content_based,+ )++ # If we're building with split debugging, where the debug info is in the+ # original object, then add the object as external debug info+ # FIXME: ThinLTO generates debug info in a separate dwo dir, but we still+ # need to track object files if the object file is not compiled to bitcode.+ # We should track whether ThinLTO is used on a per-object basis rather than+ # globally on a toolchain level.+ object_has_external_debug_info = toolchain.split_debug_mode == SplitDebugMode("single")++ clang_trace = _declare_clang_trace_output(toolchain, compiler_type, actions, filename_base, content_based)++ # Only declare CUDA distributed compile outputs for CUDA source files+ cuda_dist_output = None+ if src_compile_cmd.src.extension == ".cu" and cuda_compile_style == CudaCompileStyle("dist"):+ cuda_dist_output = shared_cuda_dist_output or declare_cuda_dist_compile_output(+ actions,+ CudaCompileInfo(+ filename = filename_base,+ identifier = identifier,+ output_prefix = folder_name,+ uses_content_based_paths = content_based,+ ),+ )++ # Declare PCH object output for Windows compiler+ pch_object = None+ if compiler_type == "windows" and compile_pch:+ pch_object = actions.declare_output(+ folder_name,+ "{}.pch.o".format(filename_base),+ has_content_based_path = content_based,+ )++ # JSON error output+ json_error = None+ serialized_diags_to_json = toolchain.binary_utilities_info.custom_tools.get("serialized-diags-to-json", None)+ if serialized_diags_to_json and src_compile_cmd.error_handler and compiler_type == "clang" and src_compile_cmd.src.extension != ".cu":+ json_error = actions.declare_output(+ "__diagnostics__/{}.json".format(filename_base),+ has_content_based_path = content_based,+ )++ hip_device_debug = src_compile_cmd.src.extension == ".hip" and toolchain.hip_device_debug_extract++ declared_artifacts = CxxCompileOutput(+ object = object,+ object_format = object_format,+ object_has_external_debug_info = object_has_external_debug_info,+ external_debug_info = external_debug_info,+ clang_remarks = clang_remarks,+ clang_llvm_statistics = clang_llvm_statistics,+ clang_trace = clang_trace,+ gcno_file = gcno_file,+ index_store = index_store,+ assembly = assembly,+ diagnostics = diagnostics,+ clang_tidy_diagnostics = clang_tidy_diagnostics,+ preproc = preproc,+ dist_cuda = cuda_dist_output,+ pch_object = pch_object,+ json_error = json_error,+ hip_device_debug = hip_device_debug,+ )++ info = CxxCompileInfo(+ src = src_compile_cmd.src,+ args = src_compile_cmd.args,+ short_path = short_path,+ filename_base = filename_base,+ index_store_base = index_store_base,+ identifier = identifier,+ folder_name = folder_name,+ )++ return CxxCompileInput(+ declared_artifacts = declared_artifacts,+ info = info,+ )++def _compile_single_cxx(+ actions: AnalysisActions,+ label: Label,+ toolchain: CxxToolchainInfo,+ flavors: set[CxxCompileFlavor],+ compile_pch: CxxPrecompiledHeader | None,+ precompiled_header: Dependency | None,+ cuda_compile_style: CudaCompileStyle | None,+ # CxxCompileInfo fields+ info: CxxCompileInfo,+ shared_info: CxxSharedCompileInfo,+ # Output artifacts+ object: OutputArtifact,+ external_debug_info: OutputArtifact | None,+ clang_remarks: OutputArtifact | None,+ clang_llvm_statistics: OutputArtifact | None,+ clang_trace: OutputArtifact | None,+ gcno_file: OutputArtifact | None,+ assembly: OutputArtifact | None,+ diagnostics: OutputArtifact | None,+ clang_tidy_diagnostics: OutputArtifact | None,+ preproc: OutputArtifact,+ index_store: OutputArtifact | None,+ dist_cuda: CudaDistributedCompileOutput | None,+ prepare_cuda_dist: bool,+ cuda_shared_plan_identifier: str | None,+ shared_compile_args: CxxSharedCompileCommandArgs,+ shared_auxiliary_args: CxxSharedCompileCommandArgs,+ shared_dryrun_args: CxxSharedCompileCommandArgs | None,+ pch_object: OutputArtifact | None,+ json_error: OutputArtifact | None,+) -> CudaDistributedCompileSpec | None:+ """+ EXECUTION PHASE: Creates compilation actions for a single source file.++ This function runs INSIDE the dynamic action callback (`_cxx_dynamic_compile`),+ meaning it only executes when Buck2 determines the compilation is actually needed.++ ## Relationship to Declaration Phase+ The output artifacts passed here were declared earlier by `_prepare_cxx_compilation`+ during the analysis phase.+ """++ # Extract info fields+ src = info.src+ src_args = info.args+ filename_base = info.filename_base+ index_store_base = info.index_store_base+ identifier = info.identifier+ folder_name = info.folder_name+ short_path = info.short_path+ cxx_compile_cmd = shared_info.cxx_compile_cmd++ # Get compiler type+ compiler_type = cxx_compile_cmd.compiler_type+ content_based = cxx_compile_cmd.allow_content_based_paths++ cuda_dist_spec = None+ if src.extension == ".cu":+ output_args = None+ elif compile_pch:+ if compiler_type == "windows":+ output_args = [+ cmd_args(object, format = "/Fp{}"),+ cmd_args(pch_object, format = "/Fo{}"),+ cmd_args(compile_pch.path, format = "/Yc{}"),+ ]+ else:+ output_args = [+ get_output_flags(compiler_type, object),+ "-Xclang",+ "-emit-pch",+ "-Xclang",+ "-fno-pch-timestamp",+ "-fpch-instantiate-templates",+ ]+ else:+ output_args = get_output_flags(compiler_type, object)++ base_compile_cmd_override = None+ if src.extension == ".cu" and cuda_compile_style == CudaCompileStyle("dist"):+ compiler_for_dryrun = getattr(toolchain.cuda_compiler_info, "compiler_for_dryrun", None)+ if compiler_for_dryrun != None:+ base_compile_cmd_override = _get_compile_base(+ toolchain,+ toolchain.cuda_compiler_info,+ use_wrapper = False,+ compiler_override = compiler_for_dryrun,+ )++ cmd = _get_base_compile_cmd(+ src = src,+ src_args = src_args,+ cxx_compile_cmd = cxx_compile_cmd,+ output_args = output_args,+ base_compile_cmd_override = base_compile_cmd_override,+ shared_args = shared_compile_args,+ )+ cuda_prepare_cmd = None+ if prepare_cuda_dist:+ expect(shared_dryrun_args != None, "distributed CUDA prepare requires dry-run compile args")+ cuda_prepare_cmd = _get_base_compile_cmd(+ src = src,+ src_args = src_args,+ cxx_compile_cmd = cxx_compile_cmd,+ base_compile_cmd_override = base_compile_cmd_override,+ source_override = _CUDA_DRYRUN_SOURCE_PLACEHOLDER,+ shared_args = shared_dryrun_args,+ )++ if index_store:+ compile_index_store_cmd = _get_base_compile_cmd(+ src = src,+ src_args = src_args,+ cxx_compile_cmd = cxx_compile_cmd,+ shared_args = shared_auxiliary_args,+ )+ shared_info.index_store_factory.compile(+ actions,+ label,+ index_store,+ index_store_base,+ toolchain,+ compile_index_store_cmd,+ )++ if precompiled_header and precompiled_header[CPrecompiledHeaderInfo] and precompiled_header[CPrecompiledHeaderInfo].compiled:+ pch_info = precompiled_header[DefaultInfo].sub_targets["pch"]+ pch_subtargets = pch_info.get(DefaultInfo).sub_targets++ pch_flavor = "default"+ for flavor in flavors:+ pch_flavor = flavor.value if flavor.value else pch_flavor++ target = pch_subtargets[pch_flavor].get(CPrecompiledHeaderInfo)+ cmd.add(_get_use_pch_args(src, cxx_compile_cmd, target, precompiled_header[CPrecompiledHeaderInfo]))++ action_dep_files = {}++ headers_dep_files = cxx_compile_cmd.headers_dep_files++ # CUDA compilation attaches dep files itself (see cuda_mono_compile and+ # cuda_distributed_compile), because the flags have to land on the real+ # compile sub-command rather than on the nvcc driver command we dryrun here.+ if src.extension == ".cu":+ headers_dep_files = None++ if headers_dep_files:+ cmd = add_headers_dep_files(+ actions,+ cmd,+ headers_dep_files,+ src,+ filename_base,+ action_dep_files,+ )++ if clang_remarks:+ cmd.add(["-fsave-optimization-record", "-fdiagnostics-show-hotness", "-foptimization-record-passes=" + toolchain.clang_remarks])+ cmd.add(cmd_args(hidden = clang_remarks))++ if clang_llvm_statistics:+ # Use stderr_to_file to capture clang statistics output+ cmd = cmd_args(+ toolchain.internal_tools.stderr_to_file,+ cmd_args(clang_llvm_statistics, format = "--out={}"),+ cmd,+ ["-mllvm", "-stats"],+ )++ if clang_trace:+ cmd.add(["-ftime-trace"])+ cmd.add(cmd_args(hidden = clang_trace))++ if gcno_file:+ cmd.add(["--coverage"])+ cmd.add(cmd_args(hidden = gcno_file))++ if external_debug_info:+ cmd.add(cmd_args(external_debug_info, format = "--fbcc-create-external-debug-info={}"))++ outputs_for_error_handler = []+ if json_error:+ # We need to wrap the entire compile to provide serialized diagnostics+ # output and on error convert it to JSON.+ serialized_diags_to_json = toolchain.binary_utilities_info.custom_tools.get("serialized-diags-to-json", None)+ outputs_for_error_handler.append(json_error)+ cmd = cmd_args(+ toolchain.internal_tools.serialized_diagnostics_to_json_wrapper,+ serialized_diags_to_json,+ json_error,+ cmd,+ )++ if src.extension == ".cu":+ expect(cuda_compile_style != None, "CUDA compile style should be configured for targets with .cu sources")+ cuda_compile_info = CudaCompileInfo(+ filename = filename_base,+ identifier = identifier,+ output_prefix = folder_name,+ uses_content_based_paths = content_based,+ )++ cuda_dist_spec = cuda_compile(+ actions,+ cmd,+ object,+ src,+ cxx_compile_cmd,+ cuda_compile_info,+ action_dep_files,+ allow_dep_file_cache_upload = False,+ error_handler = shared_info.error_handler,+ cuda_compile_style = cuda_compile_style,+ cuda_dist_output = dist_cuda,+ cuda_prepare_cmd = cuda_prepare_cmd,+ shared_plan_identifier = cuda_shared_plan_identifier,+ )+ else:+ is_producing_compiled_pch = bool(compile_pch)+ is_consuming_compiled_pch = bool(precompiled_header and precompiled_header[CPrecompiledHeaderInfo].compiled)+ actions.run(+ cmd,+ category = cxx_compile_cmd.category,+ identifier = identifier,+ dep_files = action_dep_files,+ allow_cache_upload = cxx_compile_cmd.allow_cache_upload,+ allow_dep_file_cache_upload = False,+ error_handler = shared_info.error_handler,+ outputs_for_error_handler = outputs_for_error_handler,+ local_only = is_producing_compiled_pch or is_consuming_compiled_pch,+ expect_eligible_for_dedupe = shared_info.expect_eligible_for_dedupe,+ )++ # Generate asm for compiler which accept `-S` (TODO: support others)+ if assembly:+ assembly_cmd = _get_base_compile_cmd(+ src = src,+ src_args = src_args,+ cxx_compile_cmd = cxx_compile_cmd,+ output_args = ["-S"] + get_output_flags(compiler_type, assembly),+ shared_args = shared_auxiliary_args,+ )+ actions.run(+ assembly_cmd,+ category = cxx_compile_cmd.category,+ identifier = identifier + " (assembly)",+ allow_cache_upload = cxx_compile_cmd.allow_cache_upload,+ allow_dep_file_cache_upload = False,+ error_handler = shared_info.error_handler,+ )++ if diagnostics:+ syntax_only_cmd = _get_base_compile_cmd(+ src = src,+ src_args = src_args,+ cxx_compile_cmd = cxx_compile_cmd,+ output_args = ["-fsyntax-only"],+ shared_args = shared_auxiliary_args,+ )+ diagnostics_dep_files = {}+ if headers_dep_files:+ syntax_only_cmd = add_headers_dep_files(+ actions = actions,+ cmd = syntax_only_cmd,+ headers_dep_files = headers_dep_files,+ src = src,+ filename_base = "{}.check".format(filename_base),+ action_dep_files = diagnostics_dep_files,+ )+ actions.run(+ [+ toolchain.internal_tools.stderr_to_file,+ cmd_args(diagnostics, format = "--out={}"),+ syntax_only_cmd,+ ],+ category = "check",+ identifier = short_path,+ dep_files = diagnostics_dep_files,+ allow_cache_upload = cxx_compile_cmd.allow_cache_upload,+ allow_dep_file_cache_upload = False,+ error_handler = shared_info.error_handler,+ )++ if clang_tidy_diagnostics:+ clang_tidy_tool = toolchain.binary_utilities_info.custom_tools["clang-tidy"]+ actions.run(+ [+ toolchain.internal_tools.clang_tidy_wrapper,+ cmd_args(clang_tidy_diagnostics, format = "--output={}"),+ cmd_args(clang_tidy_tool, format = "--clang-tidy={}"),+ cmd_args(src, format = "--source={}"),+ "--",+ cxx_compile_cmd.base_compile_cmd,+ cxx_compile_cmd.argsfile.cmd_form,+ src_args,+ ],+ category = "clang_tidy",+ identifier = short_path,+ allow_cache_upload = cxx_compile_cmd.allow_cache_upload,+ allow_dep_file_cache_upload = False,+ error_handler = shared_info.error_handler,+ )++ # Generate pre-processed sources+ preproc_cmd = _get_base_compile_cmd(+ src = src,+ src_args = src_args,+ cxx_compile_cmd = cxx_compile_cmd,+ output_args = [COMMON_PREPROCESSOR_OUTPUT_ARGS, get_output_flags(compiler_type, preproc)],+ shared_args = shared_auxiliary_args,+ )+ actions.run(+ preproc_cmd,+ category = cxx_compile_cmd.category,+ identifier = identifier + " (preprocessor)",+ allow_cache_upload = cxx_compile_cmd.allow_cache_upload,+ allow_dep_file_cache_upload = False,+ error_handler = shared_info.error_handler,+ )++ return cuda_dist_spec++def _get_base_compile_cmd(+ src: Artifact,+ src_args: list[typing.Any],+ cxx_compile_cmd: CxxCompileCommand,+ shared_args: CxxSharedCompileCommandArgs,+ output_args: list | None = None,+ base_compile_cmd_override = None,+ source_override: str | None = None,+) -> cmd_args:+ """+ Construct a compile command for a single CXX source from its+ `cxx_compile_cmd`, the extension-shared `shared_args`, and other+ compilation options.+ """+ cmd = cmd_args(base_compile_cmd_override if base_compile_cmd_override != None else cxx_compile_cmd.base_compile_cmd)+ if output_args:+ cmd.add(output_args)++ cmd.add(shared_args.before_src)++ if source_override == None:+ cmd.add(src_args)+ else:+ expect(+ src_args and src_args[-1] == src,+ "source override requires the source artifact to be the final compile argument",+ )+ cmd.add(src_args[:-1])+ cmd.add(source_override)++ cmd.add(shared_args.after_src)++ return cmd++def _get_shared_compile_command_args(+ bitcode_args: cmd_args | list,+ cxx_compile_cmd: CxxCompileCommand,+ flavors: set[CxxCompileFlavor],+ flavor_flags: dict[str, list[str]],+ use_header_units: UseHeaderUnitsMode = UseHeaderUnitsMode("none"),+ cuda_dryrun: bool = False,+) -> CxxSharedCompileCommandArgs:+ before_src = cmd_args()++ if use_header_units == UseHeaderUnitsMode("pcm") and cxx_compile_cmd.header_units_argsfile:+ before_src.add(cxx_compile_cmd.header_units_argsfile.cmd_form)+ elif use_header_units == UseHeaderUnitsMode("stub") and cxx_compile_cmd.header_unit_stubs_argsfile:+ before_src.add(cmd_args(hidden = cxx_compile_cmd.header_unit_stubs_argsfile.file))++ if cuda_dryrun:+ dryrun_form = cxx_compile_cmd.argsfile.cmd_form_cuda_dryrun+ expect(dryrun_form != None, "compile argsfile has no CUDA dry-run form")+ before_src.add(dryrun_form)+ else:+ before_src.add(cxx_compile_cmd.argsfile.cmd_form)++ for flavor in flavors:+ flags = flavor_flags.get(flavor.value)+ if flags:+ before_src.add(flags)++ return CxxSharedCompileCommandArgs(+ before_src = before_src,+ after_src = cmd_args(bitcode_args),+ )++def toolchain_supports_flavor(toolchain: CxxToolchainInfo, flavor: CxxCompileFlavor) -> bool:+ return flavor.value in toolchain.supported_compile_flavors and toolchain.compiler_flavor_flags.get(flavor.value) != None++# Fallback when the toolchain configures no flavor flags at all, for clang and+# gcc. Ideally this would be a default value in the toolchain definition itself,+# but it is compiler-dependent so we can't have it there. Module-level so every+# per-source compile record shares one frozen value instead of allocating a+# fresh dict+list per TU.+_DEFAULT_PIC_FLAVOR_FLAGS = {CxxCompileFlavor("pic").value: ["-fPIC"]}++def build_flavor_flags(flavor_flags: dict[str, typing.Any], compiler_type: str) -> dict[str, typing.Any]:+ if not flavor_flags and compiler_type in ["clang", "gcc"]:+ return _DEFAULT_PIC_FLAVOR_FLAGS++ return flavor_flags++def _cxx_dynamic_compile(+ actions: AnalysisActions,+ label: Label,+ toolchain: CxxToolchainInfo,+ bitcode_args: list[str],+ flavors: list[CxxCompileFlavor],+ use_header_units: UseHeaderUnitsMode,+ precompiled_header: Dependency | None,+ compile_pch: CxxPrecompiledHeader | None,+ cuda_compile_style: CudaCompileStyle | None,+ infos: list[CxxCompileInfo],+ shared_infos: dict[str, CxxSharedCompileInfo],+ object: list[OutputArtifact],+ external_debug_info: dict[int, OutputArtifact],+ clang_remarks: dict[int, OutputArtifact],+ clang_llvm_statistics: dict[int, OutputArtifact],+ clang_trace: dict[int, OutputArtifact],+ gcno_file: dict[int, OutputArtifact],+ assembly: list[OutputArtifact | None],+ diagnostics: list[OutputArtifact | None],+ clang_tidy_diagnostics: dict[int, OutputArtifact],+ preproc: list[OutputArtifact],+ index_store: dict[int, OutputArtifact],+ dist_cuda: dict[int, (OutputArtifact, OutputArtifact, OutputArtifact)],+ shared_dist_cuda: (OutputArtifact, OutputArtifact, OutputArtifact) | None,+ pch_object: dict[int, OutputArtifact],+ json_error: dict[int, OutputArtifact],+) -> list[Provider]:+ """+ DYNAMIC ACTION CALLBACK: The bridge between declaration and execution phases.++ This function is the implementation for Buck2's `dynamic_output_new` API. It runs+ LAZILY—only when Buck2 determines that one or more of the declared outputs are+ actually needed by the build. This is the key to memory optimization: action+ graphs are not materialized until necessary.++ ## How This Fits+ ```+ compile_cxx() # ANALYSIS PHASE+ │+ ├─► for each source file:+ │ _prepare_cxx_compilation() # Declares outputs (Artifact)+ │ collect declared artifacts+ │+ └─► actions.dynamic_output_new() # Registers this callback+ │+ ▼+ _cxx_dynamic_compile() # EXECUTION PHASE (called lazily)+ │+ └─► for each source:+ _compile_single_cxx() # Creates actual actions+ ```++ ## Why Batched Dynamic Actions?+ All source files are compiled in a single `dynamic_output_new` call rather than+ one per source file.+ """+ flavors_set = set(flavors)+ shared_cuda_specs = []+ shared_cuda_dist_output = None+ shared_cuda_plan_src_idx = None+ if shared_dist_cuda != None:+ shared_cuda_dist_output = CudaDistributedCompileOutput(+ nvcc_dag = shared_dist_cuda[0].as_input(),+ nvcc_env = shared_dist_cuda[1].as_input(),+ hostcc_argsfile = shared_dist_cuda[2].as_input(),+ )+ cuda_shared_plan_identifier = _cuda_plan_identifier(flavors_set) if shared_cuda_dist_output != None else None+ shared_compile_args = {}+ shared_auxiliary_args = {}+ shared_dryrun_args = {}+ for extension, shared_info in shared_infos.items():+ flavor_flags = build_flavor_flags(toolchain.compiler_flavor_flags, shared_info.cxx_compile_cmd.compiler_type)+ shared_compile_args[extension] = _get_shared_compile_command_args(+ bitcode_args = bitcode_args,+ cxx_compile_cmd = shared_info.cxx_compile_cmd,+ flavors = flavors_set,+ flavor_flags = flavor_flags,+ use_header_units = use_header_units,+ )+ shared_auxiliary_args[extension] = _get_shared_compile_command_args(+ bitcode_args = bitcode_args,+ cxx_compile_cmd = shared_info.cxx_compile_cmd,+ flavors = flavors_set,+ flavor_flags = toolchain.compiler_flavor_flags,+ )+ if extension == ".cu" and cuda_compile_style == CudaCompileStyle("dist"):+ shared_dryrun_args[extension] = _get_shared_compile_command_args(+ bitcode_args = bitcode_args,+ cxx_compile_cmd = shared_info.cxx_compile_cmd,+ flavors = flavors_set,+ flavor_flags = flavor_flags,+ use_header_units = use_header_units,+ cuda_dryrun = True,+ )+ for i in range(len(infos)):+ extension = infos[i].src.extension+ is_cuda = extension == ".cu"++ # Exactly one prepare action must bind the shared plan outputs. Any+ # shared CUDA source is a valid representative, since sharing requires+ # identical plan-affecting args across sources; use the first one.+ if is_cuda and shared_cuda_dist_output != None and shared_cuda_plan_src_idx == None:+ shared_cuda_plan_src_idx = i+ source_dist_cuda = shared_cuda_dist_output if is_cuda else None+ source_dist_cuda_outputs = dist_cuda.get(i)+ if source_dist_cuda == None and source_dist_cuda_outputs != None:+ source_dist_cuda = CudaDistributedCompileOutput(+ nvcc_dag = source_dist_cuda_outputs[0].as_input(),+ nvcc_env = source_dist_cuda_outputs[1].as_input(),+ hostcc_argsfile = source_dist_cuda_outputs[2].as_input(),+ )+ prepare_cuda_dist = source_dist_cuda != None and (shared_cuda_dist_output == None or i == shared_cuda_plan_src_idx)+ cuda_dist_spec = _compile_single_cxx(+ actions = actions,+ label = label,+ toolchain = toolchain,+ flavors = flavors_set,+ compile_pch = compile_pch,+ precompiled_header = precompiled_header,+ cuda_compile_style = cuda_compile_style,+ info = infos[i],+ shared_info = shared_infos[extension],+ object = object[i],+ external_debug_info = external_debug_info.get(i),+ clang_remarks = clang_remarks.get(i),+ clang_llvm_statistics = clang_llvm_statistics.get(i),+ clang_trace = clang_trace.get(i),+ gcno_file = gcno_file.get(i),+ assembly = assembly[i],+ diagnostics = diagnostics[i],+ clang_tidy_diagnostics = clang_tidy_diagnostics.get(i),+ preproc = preproc[i],+ index_store = index_store.get(i),+ dist_cuda = source_dist_cuda,+ prepare_cuda_dist = prepare_cuda_dist,+ cuda_shared_plan_identifier = cuda_shared_plan_identifier,+ shared_compile_args = shared_compile_args[extension],+ shared_auxiliary_args = shared_auxiliary_args[extension],+ shared_dryrun_args = shared_dryrun_args.get(extension),+ pch_object = pch_object.get(i),+ json_error = json_error.get(i),+ )+ if cuda_dist_spec != None:+ if shared_cuda_dist_output != None:+ shared_cuda_specs.append(cuda_dist_spec)+ else:+ cxx_compile_cmd = shared_infos[extension].cxx_compile_cmd+ create_cuda_distributed_compiles(+ actions,+ toolchain,+ source_dist_cuda,+ [cuda_dist_spec],+ cxx_compile_cmd.allow_cache_upload,+ # The argsfile closure carries the file-prefix specs file+ # that replayed host compiles reference by path.+ cmd_args(cxx_compile_cmd.base_compile_cmd, hidden = cxx_compile_cmd.argsfile.cmd_form),+ cxx_compile_cmd.headers_dep_files,+ )++ if shared_cuda_specs:+ cxx_compile_cmd = shared_infos[".cu"].cxx_compile_cmd+ expect(+ shared_cuda_plan_src_idx != None,+ "shared CUDA plan outputs were declared but no .cu source is present to bind them",+ )+ create_cuda_distributed_compiles(+ actions,+ toolchain,+ shared_cuda_dist_output,+ shared_cuda_specs,+ cxx_compile_cmd.allow_cache_upload,+ cmd_args(cxx_compile_cmd.base_compile_cmd, hidden = cxx_compile_cmd.argsfile.cmd_form),+ cxx_compile_cmd.headers_dep_files,+ )++ return [EMPTY_DEFAULT_INFO]++# https://buck2.build/docs/api/build/AnalysisActions/#analysisactionsdynamic_output_new+# Dynamic actions factory for batch CXX compilation+_dynamic_compile_rule = dynamic_actions(+ impl = _cxx_dynamic_compile,+ attrs = {+ "assembly": dynattrs.list(dynattrs.option(dynattrs.output())),+ "bitcode_args": dynattrs.value(list[str]),+ "clang_llvm_statistics": dynattrs.dict(int, dynattrs.output()),+ "clang_remarks": dynattrs.dict(int, dynattrs.output()),+ "clang_tidy_diagnostics": dynattrs.dict(int, dynattrs.output()),+ "clang_trace": dynattrs.dict(int, dynattrs.output()),+ "compile_pch": dynattrs.option(dynattrs.value(CxxPrecompiledHeader)),+ "cuda_compile_style": dynattrs.option(dynattrs.value(CudaCompileStyle)),+ "diagnostics": dynattrs.list(dynattrs.option(dynattrs.output())),+ "dist_cuda": dynattrs.dict(int, dynattrs.tuple(dynattrs.output(), dynattrs.output(), dynattrs.output())),+ "external_debug_info": dynattrs.dict(int, dynattrs.output()),+ "flavors": dynattrs.value(list[CxxCompileFlavor]),+ "gcno_file": dynattrs.dict(int, dynattrs.output()),+ "index_store": dynattrs.dict(int, dynattrs.output()),+ "infos": dynattrs.value(list[CxxCompileInfo]),+ "json_error": dynattrs.dict(int, dynattrs.output()),+ "label": dynattrs.value(Label),+ "object": dynattrs.list(dynattrs.output()),+ "pch_object": dynattrs.dict(int, dynattrs.output()),+ "precompiled_header": dynattrs.option(dynattrs.value(Dependency)),+ "preproc": dynattrs.list(dynattrs.output()),+ "shared_dist_cuda": dynattrs.option(dynattrs.tuple(dynattrs.output(), dynattrs.output(), dynattrs.output())),+ "shared_infos": dynattrs.dict(str, dynattrs.value(CxxSharedCompileInfo)),+ "toolchain": dynattrs.value(CxxToolchainInfo),+ "use_header_units": dynattrs.value(UseHeaderUnitsMode),+ },+)++def _cuda_plan_flavor(flavors: set[CxxCompileFlavor]) -> str:+ return ".".join(sorted([flavor.value for flavor in flavors])) or "default"++def _cuda_plan_identifier(flavors: set[CxxCompileFlavor]) -> str:+ return "cuda_compile_plan ({})".format(_cuda_plan_flavor(flavors))++def maybe_get_shared_cuda_dist_output(+ actions: AnalysisActions,+ src_compile_cmds: list[CxxSrcCompileCommand],+ cuda_compile_style: CudaCompileStyle | None,+ flavors: set[CxxCompileFlavor],+) -> CudaDistributedCompileOutput | None:+ cuda_src_compile_cmds = [cmd for cmd in src_compile_cmds if cmd.src.extension == ".cu"]+ if cuda_compile_style != CudaCompileStyle("dist") or not cuda_src_compile_cmds:+ return None++ for cmd in cuda_src_compile_cmds:+ # Same-extension sources already share one `cxx_compile_cmd`, so per-source+ # args, duplicate-basename disambiguation (`index`), and path style are the+ # only sharing hazards.+ # create_compile_cmds appends source flags before "-c" and the source artifact.+ # Only commands with no source-specific flags can share an NVCC plan.+ if len(cmd.args) != 2 or cmd.args[0] != "-c" or cmd.args[1] != cmd.src or cmd.index != None:+ return None+ if cmd.uses_content_based_paths != cuda_src_compile_cmds[0].uses_content_based_paths:+ return None++ # Plan outputs are named per flavor set: callers invoke compile_cxx at most+ # once per flavor set within a target, and a collision fails analysis loudly.+ cuda_plan_flavor = _cuda_plan_flavor(flavors)+ return declare_cuda_dist_compile_output(+ actions,+ CudaCompileInfo(+ filename = "cuda_compile_plan.{}".format(cuda_plan_flavor),+ identifier = _cuda_plan_identifier(flavors),+ output_prefix = _OBJECTS_FOLDER,+ uses_content_based_paths = cuda_src_compile_cmds[0].uses_content_based_paths,+ ),+ )++def compile_cxx(+ actions: AnalysisActions,+ target_label: Label,+ toolchain: CxxToolchainInfo,+ src_compile_cmds: list[CxxSrcCompileCommand],+ flavors: set[CxxCompileFlavor],+ provide_syntax_only: bool,+ separate_debug_info: bool,+ use_header_units: UseHeaderUnitsMode = UseHeaderUnitsMode("none"),+ precompiled_header: Dependency | None = None,+ cuda_compile_style: CudaCompileStyle | None = None,+ compile_pch: CxxPrecompiledHeader | None = None,+) -> list[CxxCompileOutput]:+ """+ MAIN ENTRY POINT: Compiles a list of C/C++ source files.++ This function implements a two-phases that separates output+ declaration (analysis phase) from action creation (execution phase).+ """+ linker_info = toolchain.linker_info++ # Resolve the output format, which is a tristate of native (default being mach-o/elf/pe)+ # bitcode (being LLVM-IR, which is also produced if any link time optimization flags are+ # enabled) or the third hybrid state where the bitcode is embedded into a section of the+ # native code, allowing the file to be used as either (but at twice the size)+ default_object_format = toolchain.object_format or CxxObjectFormat("native")+ bitcode_args = []+ if linker_info.lto_mode == LtoMode("none"):+ if toolchain.object_format == CxxObjectFormat("bitcode"):+ bitcode_args.append("-emit-llvm")+ default_object_format = CxxObjectFormat("bitcode")+ elif toolchain.object_format == CxxObjectFormat("embedded-bitcode"):+ bitcode_args.append("-fembed-bitcode")+ default_object_format = CxxObjectFormat("embedded-bitcode")+ else:+ # LTO always produces bitcode object in any mode (thin, full, etc)+ default_object_format = CxxObjectFormat("bitcode")++ objects = []++ # Dynamic action inputs+ infos = []+ object_outputs = []+ external_debug_info_outputs = {}+ clang_remarks_outputs = {}+ clang_llvm_statistics_outputs = {}+ clang_trace_outputs = {}+ gcno_file_outputs = {}+ assembly_outputs = []+ diagnostics_outputs = []+ clang_tidy_diagnostics_outputs = {}+ preproc_outputs = []+ index_store_outputs = {}+ dist_cuda_outputs = {}+ pch_object_outputs = {}+ json_error_outputs = {}+ shared_infos = {}++ for src_compile_cmd in src_compile_cmds:+ extension = src_compile_cmd.src.extension+ shared_info = shared_infos.get(extension)+ if shared_info == None:+ shared_infos[extension] = CxxSharedCompileInfo(+ cxx_compile_cmd = src_compile_cmd.cxx_compile_cmd,+ index_store_factory = src_compile_cmd.index_store_factory,+ error_handler = src_compile_cmd.error_handler,+ expect_eligible_for_dedupe = src_compile_cmd.expect_eligible_for_dedupe,+ )+ else:+ expect(+ src_compile_cmd.cxx_compile_cmd == shared_info.cxx_compile_cmd+ and src_compile_cmd.index_store_factory == shared_info.index_store_factory+ and src_compile_cmd.error_handler == shared_info.error_handler+ and src_compile_cmd.expect_eligible_for_dedupe == shared_info.expect_eligible_for_dedupe,+ "sources with the same extension must share compile command inputs",+ )++ shared_cuda_dist_output = maybe_get_shared_cuda_dist_output(+ actions,+ src_compile_cmds,+ cuda_compile_style,+ flavors,+ )++ for source_index, src_compile_cmd in enumerate(src_compile_cmds):+ cxx_compile_input = _prepare_cxx_compilation(+ actions = actions,+ toolchain = toolchain,+ default_object_format = default_object_format,+ src_compile_cmd = src_compile_cmd,+ flavors = flavors,+ provide_syntax_only = provide_syntax_only,+ use_header_units = use_header_units,+ separate_debug_info = separate_debug_info,+ cuda_compile_style = cuda_compile_style,+ shared_cuda_dist_output = shared_cuda_dist_output,+ compile_pch = compile_pch,+ )++ # Collect info (metadata without artifacts)+ infos.append(cxx_compile_input.info)++ # Collect outputs - call .as_output() on each artifact+ declared = cxx_compile_input.declared_artifacts+ object_outputs.append(declared.object.as_output())+ if declared.external_debug_info:+ external_debug_info_outputs[source_index] = declared.external_debug_info.as_output()+ if declared.clang_remarks:+ clang_remarks_outputs[source_index] = declared.clang_remarks.as_output()+ if declared.clang_llvm_statistics:+ clang_llvm_statistics_outputs[source_index] = declared.clang_llvm_statistics.as_output()+ if declared.clang_trace:+ clang_trace_outputs[source_index] = declared.clang_trace.as_output()+ if declared.gcno_file:+ gcno_file_outputs[source_index] = declared.gcno_file.as_output()+ assembly_outputs.append(map_val(as_output, declared.assembly))+ diagnostics_outputs.append(map_val(as_output, declared.diagnostics))+ if declared.clang_tidy_diagnostics:+ clang_tidy_diagnostics_outputs[source_index] = declared.clang_tidy_diagnostics.as_output()+ preproc_outputs.append(declared.preproc.as_output())+ if declared.index_store:+ index_store_outputs[source_index] = declared.index_store.as_output()+ if shared_cuda_dist_output == None and declared.dist_cuda:+ dist_cuda_outputs[source_index] = (+ declared.dist_cuda.nvcc_dag.as_output(),+ declared.dist_cuda.nvcc_env.as_output(),+ declared.dist_cuda.hostcc_argsfile.as_output(),+ )+ if declared.pch_object:+ pch_object_outputs[source_index] = declared.pch_object.as_output()+ if declared.json_error:+ json_error_outputs[source_index] = declared.json_error.as_output()++ objects.append(declared)++ actions.dynamic_output_new(+ _dynamic_compile_rule(+ assembly = assembly_outputs,+ bitcode_args = bitcode_args,+ clang_llvm_statistics = clang_llvm_statistics_outputs,+ clang_remarks = clang_remarks_outputs,+ clang_tidy_diagnostics = clang_tidy_diagnostics_outputs,+ clang_trace = clang_trace_outputs,+ compile_pch = compile_pch,+ cuda_compile_style = cuda_compile_style,+ diagnostics = diagnostics_outputs,+ dist_cuda = dist_cuda_outputs,+ external_debug_info = external_debug_info_outputs,+ flavors = list(flavors),+ gcno_file = gcno_file_outputs,+ index_store = index_store_outputs,+ infos = infos,+ json_error = json_error_outputs,+ label = target_label,+ object = object_outputs,+ pch_object = pch_object_outputs,+ precompiled_header = precompiled_header,+ preproc = preproc_outputs,+ shared_dist_cuda = map_val(lambda d: (d.nvcc_dag.as_output(), d.nvcc_env.as_output(), d.hostcc_argsfile.as_output()), shared_cuda_dist_output),+ shared_infos = shared_infos,+ toolchain = toolchain,+ use_header_units = use_header_units,+ )+ )++ # Strip per-arch device DWARF from each .hip TU's `.o` into+ # sidecars. Replaces `.object` with the stripped artifact; downstream+ # linker concatenates the stripped bundles into the final+ # `.hip_fatbin`.+ if hip_debug_extract_available(toolchain):+ processed = []+ for i, out in enumerate(objects):+ if out.hip_device_debug:+ hip_outs = hip_debug_extract_compile_object(+ actions = actions,+ toolchain = toolchain,+ obj = out.object,+ identifier = infos[i].identifier,+ )+ processed.append(+ CxxCompileOutput(+ object = hip_outs.patched_output,+ object_format = out.object_format,+ object_has_external_debug_info = out.object_has_external_debug_info,+ external_debug_info = out.external_debug_info,+ clang_remarks = out.clang_remarks,+ clang_llvm_statistics = out.clang_llvm_statistics,+ clang_trace = out.clang_trace,+ gcno_file = out.gcno_file,+ index_store = out.index_store,+ assembly = out.assembly,+ diagnostics = out.diagnostics,+ clang_tidy_diagnostics = out.clang_tidy_diagnostics,+ preproc = out.preproc,+ dist_cuda = out.dist_cuda,+ pch_object = out.pch_object,+ json_error = out.json_error,+ hip_device_debug = out.hip_device_debug,+ hip_arch_debug_files = hip_outs.arch_debug_files,+ )+ )+ else:+ processed.append(out)+ return processed++ return objects++def _compiler_supports_header_units(compiler_info: typing.Any):+ return "clang" in compiler_info.compiler_type and compiler_info.supports_two_phase_compilation++def _get_module_name(target_label: Label, group_name: str) -> str:+ return paths.normalize(+ paths.join(+ "__header_units__",+ target_label.package,+ "{}{}.h".format(target_label.name, group_name),+ )+ )++def _get_import_filename(target_label: Label, group_name: str) -> str:+ return paths.normalize(+ paths.join(+ target_label.package,+ "__import__{}{}.h".format(target_label.name, group_name),+ )+ )++def _is_standalone_header(header: CHeader) -> bool:+ if header.artifact.extension not in HeaderExtension.values():+ return False+ if header.name.endswith("-inl.h") or header.name.endswith("-inl.hpp"):+ return False+ if header.name.endswith(".tcc"):+ return False+ if header.name.endswith("-pre.h") or header.name.endswith("-pre.hpp"):+ return False+ if header.name.endswith("-post.h") or header.name.endswith("-post.hpp"):+ return False+ return True++def _convert_raw_header(target_label: Label, raw_header: Artifact, include_dirs: list[CellPath]) -> CHeader:+ full_path = str(target_label.path) + "/" + raw_header.short_path+ best_dir = None+ for d in include_dirs:+ abs_dir = str(d)+ if paths.starts_with(full_path, abs_dir) and (best_dir == None or len(abs_dir) > len(best_dir)):+ best_dir = abs_dir+ if best_dir != None:+ ns = paths.dirname(paths.relativize(full_path, best_dir))+ else:+ ns = paths.dirname(raw_header.short_path)+ return CHeader(+ artifact = raw_header,+ name = raw_header.basename,+ namespace = ns,+ named = False,+ )++def _get_raw_header_include_dirs(preprocessors: list[CPreprocessor]) -> list[CellPath]:+ return flatten([x.include_dirs for x in preprocessors]) + flatten(+ [x.system_include_dirs.include_dirs for x in preprocessors if x.system_include_dirs != None]+ )++def _create_precompile_cmd(+ actions: AnalysisActions,+ target_label: Label,+ compiler_info: typing.Any,+ preprocessors: list[CPreprocessor],+ header_group: str | None,+ group_name: str,+ extra_preprocessors: list[CPreprocessor],+ cmd: CxxCompileCommand,+) -> CxxSrcPrecompileCommand:+ include_dirs = _get_raw_header_include_dirs(preprocessors)+ converted_headers = [_convert_raw_header(target_label, raw_header, include_dirs) for raw_header in flatten([x.raw_headers for x in preprocessors])]+ header_group_regex = regex(header_group, fancy = False) if header_group else None++ header_paths = [+ paths.normalize(paths.join(header.namespace, header.name))+ for header in flatten([x.headers for x in preprocessors]) + converted_headers+ if (_is_standalone_header(header) if header_group_regex == None else header_group_regex.match(header.name))+ ]++ input_header_contents = cmd_args(header_paths, format = '#include "{}"')++ module_name = _get_module_name(target_label, group_name)+ import_name = _get_import_filename(target_label, group_name)++ input_header = actions.write(+ module_name,+ cmd_args(input_header_contents, cmd_args(["\n"])),+ has_content_based_path = True,+ )++ import_stub = actions.write(+ import_name,+ """+#ifdef FACEBOOK_CPP_HEADER_UNIT+export+#endif+import \"{}\";+""".format(module_name),+ has_content_based_path = True,+ )++ symlinked_files = {}+ for path in header_paths:+ symlinked_files[path] = import_stub++ modulemap_content = """+module "{}" {{+ header "{}"+ export *+}}+""".format(module_name, module_name)+ modulemap_file = actions.write(+ "module.modulemap" + group_name,+ modulemap_content,+ has_content_based_path = True,+ )++ src_dir = actions.symlinked_dir(+ "header-unit" + group_name,+ symlinked_files+ | {+ module_name: input_header,+ import_name: import_stub,+ "module.modulemap": modulemap_file,+ },+ has_content_based_path = True,+ )++ args = []+ args.extend([+ # TODO(nml): Fix warning bugs.+ "-Wno-uninitialized",+ "-Wno-conversion",+ "-Wno-zero-as-null-pointer-constant",+ "-Wno-c++98-compat-extra-semi",+ ])++ extra_argsfile = None+ if extra_preprocessors:+ extra_argsfile = _mk_header_units_argsfile(+ actions = actions,+ compiler_info = compiler_info,+ preprocessor = cxx_merge_cpreprocessors(actions, extra_preprocessors, []),+ ext = CxxExtension(".cpp"),+ has_content_based_path = True,+ filename_prefix = "export{}_".format(group_name),+ )++ args.extend(["-xc++-user-header", "-fmodule-header"])+ args.extend(["-fmodule-name={}".format(module_name)])+ args.extend(["-Xclang", "-fmodule-file-home-is-cwd"])++ # check_args: same setup but -fsyntax-only instead of --precompile, and+ # without -DFACEBOOK_CPP_HEADER_UNIT=1 (the `export` keyword in import+ # stubs is only valid inside module purview set up by --precompile).+ check_args = list(args)++ args.extend(["-Xclang", cmd_args(input_header, format = "-fmodules-embed-file={}")])+ args.extend(["-DFACEBOOK_CPP_HEADER_UNIT=1", "--precompile", input_header])++ check_args.extend(["-fsyntax-only", input_header])++ return CxxSrcPrecompileCommand(+ src = src_dir,+ cxx_compile_cmd = cmd,+ args = args,+ check_args = check_args,+ extra_argsfile = extra_argsfile,+ )++def _precompile_single_cxx(+ actions: AnalysisActions,+ target_label: Label,+ toolchain: CxxToolchainInfo,+ impl_params: CxxRuleConstructorParams,+ group_name: str,+ src_compile_cmd: CxxSrcPrecompileCommand,+) -> HeaderUnit:+ identifier = src_compile_cmd.src.short_path+ cxx_cmd = src_compile_cmd.cxx_compile_cmd++ filename = "{}.pcm".format(identifier)+ module = actions.declare_output(+ "__pcm_files__",+ filename,+ has_content_based_path = True,+ )++ # Declare stub artifact+ stub_filename = "{}.pcm.stub".format(identifier)+ stub = actions.declare_output(+ "__pcm_files__",+ stub_filename,+ has_content_based_path = True,+ )++ # Build actual header units+ # TODO(nml): We don't meaningfully support dep files. See T225373444.+ cmd = cmd_args(cxx_cmd.base_compile_cmd)+ if cxx_cmd.header_units_argsfile:+ cmd.add(cxx_cmd.header_units_argsfile.cmd_form)+ if src_compile_cmd.extra_argsfile:+ cmd.add(src_compile_cmd.extra_argsfile.cmd_form)+ cmd.add(cxx_cmd.argsfile.cmd_form)+ cmd.add(src_compile_cmd.args)+ cmd.add("-o", module.as_output())++ clang_trace = None+ if toolchain.clang_trace and toolchain.cxx_compiler_info.compiler_type == "clang":+ clang_trace = actions.declare_output(+ paths.join("__pcm_files__", "{}.json".format(identifier)),+ has_content_based_path = True,+ )+ cmd.add(cmd_args("-ftime-trace", hidden = clang_trace.as_output()))++ actions.run(+ cmd,+ category = "cxx_modules_precompile",+ identifier = identifier,+ allow_cache_upload = cxx_cmd.allow_cache_upload,+ low_pass_filter = False,+ )++ # Diagnostics: run -fsyntax-only variant for [check] subtarget.+ # This is cheaper than --precompile because it skips module serialization.+ # We must remove -DFACEBOOK_CPP_HEADER_UNIT=1 because that macro gates+ # `export` keywords in import stubs, which are only valid inside module+ # purview (set up by --precompile but not -fsyntax-only).+ diagnostics = None+ if cxx_cmd.compiler_type == "clang":+ diagnostics = actions.declare_output(+ "__diagnostics__",+ "{}.header-unit.diag.txt".format(identifier),+ has_content_based_path = False,+ )+ check_cmd = cmd_args(cxx_cmd.base_compile_cmd)+ if cxx_cmd.header_units_argsfile:+ check_cmd.add(cxx_cmd.header_units_argsfile.cmd_form)+ if src_compile_cmd.extra_argsfile:+ check_cmd.add(src_compile_cmd.extra_argsfile.cmd_form)+ check_cmd.add(cxx_cmd.argsfile.cmd_form)++ # Add all precompile args except --precompile and -DFACEBOOK_CPP_HEADER_UNIT=1+ check_cmd.add(src_compile_cmd.check_args)+ actions.run(+ [+ toolchain.internal_tools.stderr_to_file,+ cmd_args(diagnostics.as_output(), format = "--out={}"),+ check_cmd,+ ],+ category = "check",+ identifier = identifier + " (header-unit)",+ allow_cache_upload = cxx_cmd.allow_cache_upload,+ low_pass_filter = False,+ )++ # Build the stub artifact using the stub_header_unit tool+ stub_cmd = cmd_args(toolchain.internal_tools.stub_header_unit)+ stub_cmd.add(cxx_cmd.base_compile_cmd)+ if cxx_cmd.header_unit_stubs_argsfile:+ stub_cmd.add(cmd_args(hidden = cxx_cmd.header_unit_stubs_argsfile.file))+ stub_cmd.add(cxx_cmd.argsfile.cmd_form)+ stub_cmd.add(src_compile_cmd.args)+ stub_cmd.add("-o", stub.as_output())++ actions.run(+ stub_cmd,+ category = "cxx_modules_precompile_stub",+ identifier = identifier,+ allow_cache_upload = cxx_cmd.allow_cache_upload,+ low_pass_filter = False,+ )++ return HeaderUnit(+ name = _get_module_name(target_label, group_name),+ module = module,+ stub = stub,+ include_dir = src_compile_cmd.src,+ import_include = _get_import_filename(target_label, group_name) if impl_params.export_header_unit == "preload" else None,+ clang_trace = clang_trace,+ diagnostics = diagnostics,+ )++def precompile_cxx(+ actions: AnalysisActions,+ target_label: Label,+ toolchain: CxxToolchainInfo,+ impl_params: CxxRuleConstructorParams,+ preprocessors: list[CPreprocessor],+ header_preprocessor_info: CPreprocessorInfo,+) -> list[CPreprocessor]:+ """+ Produces header units for the target and returns a list of preprocessors enabling+ them; depending on those preprocessors will allow the corresponding module to load.+ """+ compiler_info = toolchain.cxx_compiler_info+ if not _compiler_supports_header_units(compiler_info):+ return []++ def mk_base_cmd():+ base_compile_cmd = _get_compile_base(toolchain, compiler_info, use_wrapper = True)+ ext = CxxExtension(".cpp")+ headers_tag = actions.artifact_tag() # Currently ignored+ argsfile = _mk_argsfiles(+ actions,+ target_label,+ impl_params,+ compiler_info,+ header_preprocessor_info,+ ext,+ headers_tag,+ is_xcode_argsfile = False,+ is_precompile = True,+ uses_content_based_paths = True,+ filename_prefix = "pre_",+ )+ header_units_argsfile = _mk_header_units_argsfile(+ actions,+ compiler_info,+ header_preprocessor_info,+ ext,+ has_content_based_path = True,+ filename_prefix = "pre_",+ stub = False,+ )+ header_unit_stubs_argsfile = _mk_header_units_argsfile(+ actions,+ compiler_info,+ header_preprocessor_info,+ ext,+ has_content_based_path = True,+ filename_prefix = "pre_",+ stub = True,+ )+ return CxxCompileCommand(+ base_compile_cmd = base_compile_cmd,+ argsfile = argsfile,+ xcode_argsfile = argsfile, # Unused+ header_units_argsfile = header_units_argsfile,+ header_unit_stubs_argsfile = header_unit_stubs_argsfile,+ headers_dep_files = None,+ compiler_type = compiler_info.compiler_type,+ category = "cxx_modules_precompile",+ allow_cache_upload = impl_params.allow_cache_upload,+ allow_content_based_paths = True, # Unused: we always use content-based paths for precompile+ )++ cmd = mk_base_cmd()++ header_unit_preprocessors = []+ if len(impl_params.export_header_unit_filter) <= 1:+ group = None+ if impl_params.export_header_unit_filter:+ group = impl_params.export_header_unit_filter[0]+ precompile_cmd = _create_precompile_cmd(+ actions = actions,+ target_label = target_label,+ compiler_info = toolchain.cxx_compiler_info,+ preprocessors = preprocessors,+ header_group = group,+ group_name = "",+ extra_preprocessors = [],+ cmd = cmd,+ )+ header_unit = _precompile_single_cxx(actions, target_label, toolchain, impl_params, "", precompile_cmd)+ header_unit_preprocessors.append(CPreprocessor(header_units = [header_unit]))+ else:+ # Chain preprocessors in order.+ i = 0+ for header_group in impl_params.export_header_unit_filter:+ name = ".{}".format(i)+ precompile_cmd = _create_precompile_cmd(+ actions = actions,+ target_label = target_label,+ compiler_info = toolchain.cxx_compiler_info,+ preprocessors = preprocessors,+ header_group = header_group,+ group_name = name,+ extra_preprocessors = header_unit_preprocessors,+ cmd = cmd,+ )+ header_unit = _precompile_single_cxx(actions, target_label, toolchain, impl_params, name, precompile_cmd)+ header_unit_preprocessors.append(CPreprocessor(header_units = [header_unit]))+ i += 1++ return header_unit_preprocessors++def cxx_objects_sub_targets(outs: list[CxxCompileOutput]) -> dict[str, list[Provider]]:+ objects_sub_targets = {}+ for obj in outs:+ sub_targets = {}+ if obj.clang_trace:+ sub_targets["clang-trace"] = [DefaultInfo(obj.clang_trace)]+ if obj.clang_remarks:+ sub_targets["clang-remarks"] = [DefaultInfo(obj.clang_remarks)]+ if obj.clang_llvm_statistics:+ sub_targets["clang-llvm-statistics"] = [DefaultInfo(obj.clang_llvm_statistics)]+ if obj.assembly:+ sub_targets["assembly"] = [DefaultInfo(obj.assembly)]+ if obj.preproc:+ sub_targets["preprocessed"] = [DefaultInfo(obj.preproc)]+ if obj.dist_cuda:+ sub_targets["nvcc-dag"] = [DefaultInfo(obj.dist_cuda.nvcc_dag)]+ sub_targets["nvcc-env"] = [DefaultInfo(obj.dist_cuda.nvcc_env)]+ objects_sub_targets[obj.object.short_path] = [+ DefaultInfo(+ obj.object,+ sub_targets = sub_targets,+ )+ ]+ return objects_sub_targets++def _validate_target_headers(label: Label, preprocessor: list[CPreprocessor]):+ path_to_artifact = {}+ all_headers = flatten([x.headers for x in preprocessor])+ for header in all_headers:+ header_path = paths.join(header.namespace, header.name)+ artifact = path_to_artifact.get(header_path)+ if artifact != None:+ if artifact != header.artifact:+ fail("Conflicting headers {} and {} map to {} in target {}".format(artifact, header.artifact, header_path, label))+ else:+ path_to_artifact[header_path] = header.artifact++def _get_compiler_info(toolchain: CxxToolchainInfo, ext: CxxExtension) -> typing.Any:+ compiler_info = None+ if ext.value in (".cpp", ".cc", ".cl", ".cxx", ".c++", ".h", ".hpp", ".hh", ".h++", ".hxx", ".bc"):+ compiler_info = toolchain.cxx_compiler_info+ elif ext.value == ".c":+ compiler_info = toolchain.c_compiler_info+ elif ext.value == ".m":+ compiler_info = toolchain.objc_compiler_info+ elif ext.value == ".mm":+ compiler_info = toolchain.objcxx_compiler_info+ elif ext.value in (".s", ".sx", ".S"):+ compiler_info = toolchain.as_compiler_info+ elif ext.value == ".cu":+ compiler_info = toolchain.cuda_compiler_info+ elif ext.value == ".hip":+ compiler_info = toolchain.hip_compiler_info+ elif ext.value in (".asm", ".asmpp"):+ compiler_info = toolchain.asm_compiler_info+ else:+ # This should be unreachable as long as we handle all enum values+ fail("Unknown C++ extension: " + ext.value)++ if not compiler_info:+ fail("Could not find compiler for extension `{ext}`".format(ext = ext.value))++ return compiler_info++def _get_category(ext: CxxExtension) -> str:+ if ext.value in (".cpp", ".cc", ".cl", ".cxx", ".c++", ".h", ".hpp", ".hh", ".h++", ".hxx"):+ return "cxx_compile"+ if ext.value == ".c":+ return "c_compile"+ if ext.value == ".m":+ return "objc_compile"+ if ext.value == ".mm":+ return "objcxx_compile"+ elif ext.value in (".s", ".sx", ".S", ".asm", ".asmpp"):+ return "asm_compile"+ elif ext.value == ".cu":+ return "cuda_compile"+ elif ext.value == ".hip":+ return "hip_compile"+ elif ext.value == ".bc":+ return "bitcode_compile"+ else:+ # This should be unreachable as long as we handle all enum values+ fail("Unknown extension: " + ext.value)++def _get_compile_base(toolchain: CxxToolchainInfo, compiler_info: typing.Any, use_wrapper, compiler_override = None) -> cmd_args:+ """+ Given a compiler info returned by _get_compiler_info, form the base compile args.++ `compiler_override` substitutes the compiler executable while keeping the+ toolchain-level wrapping (e.g. cwd remapping) that all compiles of this+ compiler type must run under.+ """+ if compiler_override != None:+ compiler = compiler_override+ else:+ compiler = compiler_info.compiler_with_wrapper if compiler_info.compiler_with_wrapper and use_wrapper else compiler_info.compiler++ if toolchain.remap_cwd and compiler_info.compiler_type in ["clang", "clang_windows", "clang_cl", "gcc"]:+ return cmd_args(toolchain.internal_tools.remap_cwd, compiler)+ else:+ return cmd_args(compiler)++def _dep_file_type(ext: CxxExtension) -> [DepFileType, None]:+ # Raw assembly doesn't make sense to capture dep files for.+ # .S is preprocessed assembly, but some builds use it with+ # assemblers that don't support -MF, so leave depfiles off.+ if ext.value in (".s", ".S", ".asm"):+ return None+ elif ext.value == ".hip":+ # TODO (T118797886): HipCompilerInfo doesn't have dep files processor.+ # Should it?+ return None+ elif ext.value == ".bc":+ # Bitcode doesn't have depfiles+ return None++ # Return the file type as well+ if ext.value in (".cpp", ".cc", ".cl", ".mm", ".cxx", ".c++", ".h", ".hpp", ".hh", ".h++", ".hxx"):+ return DepFileType("cpp")+ elif ext.value in (".c", ".m"):+ return DepFileType("c")+ elif ext.value == ".cu":+ return DepFileType("cuda")+ elif ext.value in (".asmpp", ".sx"):+ return DepFileType("asm")+ else:+ # This should be unreachable as long as we handle all enum values+ fail("Unknown C++ extension: " + ext.value)++def _add_compiler_info_flags(compiler_info: typing.Any) -> list:+ cmd = []+ cmd.append(compiler_info.preprocessor_flags or [])+ cmd.append(compiler_info.compiler_flags or [])++ return cmd++def mk_toolchain_precompile_argsfile(actions: AnalysisActions, name: str, argsfile: cmd_args, filter_argsfile: RunInfo) -> cmd_args:+ """+ Copy a toolchain argsfile with flags that are invalid for C++20 module+ precompilation filtered out. One filter action per toolchain, run only if+ a precompile demands it. `argsfile` is an `argsfile_with_artifacts()`+ value; the filtered copy carries everything the original carried.+ """+ filtered = actions.declare_output(name + "_toolchain_args_precompile", has_content_based_path = True)+ actions.run(+ [filter_argsfile, _PRECOMPILE_OPTION_IGNORE_REGEX_STR, argsfile, filtered.as_output()],+ category = "filter_modules_precompile_argsfile",+ identifier = name,+ )+ return argsfile_with_artifacts(filtered, argsfile)++def compiler_info_with_toolchain_argsfiles(+ actions: AnalysisActions, name: str, ctor: typing.Callable, compiler_info: typing.Any, precompile_filter: RunInfo | None = None+) -> typing.Any:+ """+ Given a compiler_info that can have a new version made with ctor, this+ will generate new `argsfile`/`argsfile_xcode` containing the compiler_info's+ preprocessor and compiler flags. Compile commands use these per-toolchain+ files, so targets using the toolchain don't each write their own+ `{ext}.toolchain_cxx_args` copy of the same flags. With `precompile_filter`,+ also generate `argsfile_precompile`.+ """+ if compiler_info == None:+ return None+ is_nasm = compiler_info.compiler_type == "nasm"+ flags = _add_compiler_info_flags(compiler_info)+ content_based = bool(compiler_info.supports_content_based_paths)+ argsfile = _mk_argsfile(+ actions = actions,+ name = name + "_toolchain_args",+ args = create_cmd_args(is_nasm, False, flags),+ has_content_based_path = content_based,+ )+ argsfile_xcode = _mk_argsfile(+ actions = actions,+ name = name + "_toolchain_args_xcode",+ args = create_cmd_args(is_nasm, True, flags),+ has_content_based_path = content_based,+ )+ argsfile_precompile = None+ if precompile_filter != None:+ argsfile_precompile = mk_toolchain_precompile_argsfile(actions, name, argsfile, precompile_filter)+ return compiler_info_with_argsfiles(+ compiler_info,+ ctor,+ argsfile,+ argsfile_xcode,+ argsfile_precompile,+ )++def _add_compiler_type_flags(target_label: Label, compiler_type: str, ext: CxxExtension) -> list:+ cmd = []+ cmd.append(get_flags_for_reproducible_build(target_label, compiler_type))++ if ext.value not in (".asm", ".asmpp"):+ # Clang's asm compiler doesn't support colorful output, so we skip this there.+ cmd.append(get_flags_for_colorful_output(compiler_type))++ return cmd++def _compiler_type_flags_anon_impl(ctx: AnalysisContext):+ is_nasm = ctx.attrs.compiler_type == "nasm"+ args = _add_compiler_type_flags(ctx.label, ctx.attrs.compiler_type, CxxExtension(ctx.attrs.src_extension))+ content = create_cmd_args(is_nasm, ctx.attrs.is_xcode_argsfile, *args)+ argsfile_artifact, _ = ctx.actions.write("compiler_type_args", content, allow_args = True, has_content_based_path = True)++ return [DefaultInfo(default_outputs = [argsfile_artifact])]++_compiler_type_flags_anon_rule = anon_rule(+ impl = _compiler_type_flags_anon_impl,+ attrs = {+ "compiler_type": attrs.string(doc = "The compiler type. Examples: clang, gcc, nasm"),+ "is_xcode_argsfile": attrs.bool(doc = "Apply xcode specific formatting to the argsfile."),+ "src_extension": attrs.string(doc = "The extension of the source file being compiled. See `CxxExtension` enum."),+ },+ artifact_promise_mappings = {+ "argsfile": lambda x: x[DefaultInfo].default_outputs[0],+ },+ doc = "Creates compiler flags argsfile for a given compiler type. " + "The argsfile is shared between targets, thus reducing resource usage.",+)++def create_cmd_args(is_nasm: bool, is_xcode_argsfile: bool, *args) -> cmd_args:+ if is_xcode_argsfile:+ return cmd_args(replace_regex = XCODE_ARG_SUBSTITUTIONS, *args)+ elif is_nasm:+ return cmd_args(*args)+ else:+ return cmd_args(quote = "shell", *args)++_PRECOMPILE_OPTION_IGNORE_REGEX_STR = (+ "^(?:"+ + "|".join([+ # Debug flags, which only affect debug symbols in the backend.+ "-f(?:no-)?debug-types-section",+ "-g(?:no-)?pubnames",+ "-g(?:no-)?record-gcc-switches",+ "-g(?:no-)?simple-template-names",+ "-g(?:no-)?split-dwarf(?:=.*)?",+ "-g[0-3]",+ "-gdwarf.*",+ # Profiling flags, used for PGO in the backend.+ "-fdebug-info-for-profiling",+ "-fprofile-sample-use=.*",+ ])+ + ")$"+)++_PRECOMPILE_OPTION_IGNORE_REGEX = regex(_PRECOMPILE_OPTION_IGNORE_REGEX_STR)++def _filter_precompile_args(args: list[typing.Any]) -> list[typing.Any]:+ def should_ignore(s):+ return _PRECOMPILE_OPTION_IGNORE_REGEX.match(repr(s)[1:-1])++ return filter(+ None,+ [_filter_precompile_args(arg) if type(arg) == type([]) else arg if not should_ignore(arg) else None for arg in args],+ )++def _cxx_flags_args(flags, ext: str, is_precompile: bool):+ if not is_precompile:+ return flags.project_as_args(+ cxx_flags_projection_name(ext),+ ordering = "postorder",+ )++ values = flags.traverse(ordering = "postorder")+ args = [+ [+ value.preprocessor_flags,+ cxx_by_language_ext(value.lang_preprocessor_flags, ext),+ cxx_by_language_ext(value.lang_compiler_flags, ext),+ value.compiler_flags,+ ]+ for value in values+ ]+ return _filter_precompile_args(args)++def _cxx_flags_argsfile_anon_impl(ctx: AnalysisContext):+ flags = cxx_flags_tset(ctx.actions, ctx.attrs.flags)+ if flags == None:+ fail("cxx flags argsfile requires at least one `cxx_flags` target")+ args = _cxx_flags_args(flags, ctx.attrs.src_extension, ctx.attrs.is_precompile)+ content = create_cmd_args(ctx.attrs.is_nasm, ctx.attrs.is_xcode_argsfile, args)+ argsfile, _ = ctx.actions.write("cxx_flags_args", content, allow_args = True, has_content_based_path = True)+ return [DefaultInfo(default_outputs = [argsfile])]++_cxx_flags_argsfile_anon_rule = anon_rule(+ impl = _cxx_flags_argsfile_anon_impl,+ attrs = {+ "flags": attrs.list(attrs.dep(providers = [CxxFlagsInfo])),+ "is_nasm": attrs.bool(),+ "is_precompile": attrs.bool(),+ "is_xcode_argsfile": attrs.bool(),+ "src_extension": attrs.string(),+ },+ artifact_promise_mappings = {+ "argsfile": lambda x: x[DefaultInfo].default_outputs[0],+ },+ doc = "Creates a shared argsfile from one or more nested `cxx_flags` targets.",+)++def _filter_precompile_argsfile_anon_impl(ctx: AnalysisContext):+ argsfile = ctx.actions.declare_output("filtered_args", has_content_based_path = True)+ ctx.actions.run(+ [+ ctx.attrs._cxx_toolchain[CxxToolchainInfo].internal_tools.filter_argsfile,+ _PRECOMPILE_OPTION_IGNORE_REGEX_STR,+ ctx.attrs.src,+ argsfile.as_output(),+ ],+ category = "filter_modules_precompile_argsfile",+ allow_cache_upload = ctx.attrs.allow_cache_upload,+ )+ return [DefaultInfo(default_outputs = [argsfile])]++_filter_precompile_argsfile_anon_rule = anon_rule(+ impl = _filter_precompile_argsfile_anon_impl,+ attrs = {+ "allow_cache_upload": attrs.bool(),+ "src": attrs.source(),+ "_cxx_toolchain": attrs.dep(),+ },+ artifact_promise_mappings = {+ "argsfile": lambda x: x[DefaultInfo].default_outputs[0],+ },+)++def _mk_argsfiles(+ actions: AnalysisActions,+ target_label: Label,+ impl_params: CxxRuleConstructorParams,+ compiler_info: typing.Any,+ preprocessor: CPreprocessorInfo,+ ext: CxxExtension,+ headers_tag: ArtifactTag,+ is_xcode_argsfile: bool,+ is_precompile: bool = False,+ filename_prefix: str = "",+ uses_content_based_paths: bool = False,+) -> CompileArgsfile:+ """+ Generate and return an {ext}.argsfile artifact and command args that utilize the argsfile.+ """+ is_nasm = compiler_info.compiler_type == "nasm"++ # prefix example: .cpp.xcode_+ filename_prefix = "{src_file_extension}.{xcode_prefix}{filename_prefix}".format(+ src_file_extension = ext.value,+ xcode_prefix = "xcode_" if is_xcode_argsfile else "",+ filename_prefix = filename_prefix,+ )++ argsfiles = []+ args_list = []++ def mk_argsfile(filename: str, args, absolute: bool = False, use_dep_files_placeholder_for_content_based_paths: bool = False) -> Artifact:+ content = create_cmd_args(is_nasm, is_xcode_argsfile, args)+ argsfile, _ = actions.write(+ filename,+ content,+ allow_args = True,+ absolute = absolute,+ has_content_based_path = uses_content_based_paths,+ use_dep_files_placeholder_for_content_based_paths = use_dep_files_placeholder_for_content_based_paths,+ )+ return argsfile++ def write_for_dep_file_filtering(filename: str, content, absolute: bool = False) -> (Artifact, Artifact | None):+ # Dep-file filtering needs two versions of the file:+ # - The first is a tagged file with the optionally content-based paths, which+ # will be passed to the compiler as usual, but will NOT be marked used, so+ # whether the paths in it change or not, the action will NOT rerun.+ # - The second is an untagged file with the same content except content-based+ # paths are replaced by placeholders. This file is not read by the compiler,+ # but is passed as a hidden input of the compiler action, so that if+ # something OTHER than paths in the file changes, this redacted version will+ # change and trigger a rerun.+ output, _ = actions.write(+ filename,+ content,+ allow_args = True,+ absolute = absolute,+ has_content_based_path = uses_content_based_paths,+ )+ # Precompile actions do not filter inputs with dep files, so the real+ # argsfile already tracks flag changes.+ if is_precompile:+ return (output, None)++ redacted_output, _ = actions.write(+ filename + "_redacted",+ content,+ allow_args = True,+ absolute = absolute,+ has_content_based_path = uses_content_based_paths,+ use_dep_files_placeholder_for_content_based_paths = True,+ )+ return (output, redacted_output)++ def mk_argsfile_for_dep_file_filtering(filename: str, args, absolute: bool = False) -> (Artifact, Artifact | None):+ return write_for_dep_file_filtering(+ filename,+ create_cmd_args(is_nasm, is_xcode_argsfile, args),+ absolute = absolute,+ )++ def make_toolchain_argsfile():+ compiler_info_flags = _add_compiler_info_flags(compiler_info)++ if is_precompile:+ if impl_params._cxx_toolchain == None:+ # TODO(nml): Compared to get_cxx_toolchain_info(), we don't support+ # AppleToolchain for C++20 modules. Update this if that changes.+ fail("C++20 modules are not supported for AppleToolchain")++ if compiler_info.argsfile_precompile and not is_xcode_argsfile:+ compiler_info_argsfile = compiler_info.argsfile_precompile+ else:+ # The anon filter takes an `attrs.source()` argsfile, so write+ # a per-target copy of the flags for it.+ unfiltered_argsfile = mk_argsfile(filename_prefix + "toolchain_cxx_args", compiler_info_flags)+ filtered_info_argsfile = actions.anon_target(+ _filter_precompile_argsfile_anon_rule,+ {+ "allow_cache_upload": impl_params.allow_cache_upload,+ "src": unfiltered_argsfile,+ "_cxx_toolchain": impl_params._cxx_toolchain,+ },+ ).artifact("argsfile")++ # The promise artifact doesn't carry the artifacts the flags+ # reference forward automatically for us; re-pair them.+ compiler_info_argsfile = argsfile_with_artifacts(+ actions.assert_has_content_based_path(filtered_info_argsfile),+ compiler_info_flags,+ )+ elif compiler_info.argsfile and not is_xcode_argsfile:+ compiler_info_argsfile = compiler_info.argsfile+ elif compiler_info.argsfile_xcode and is_xcode_argsfile:+ compiler_info_argsfile = compiler_info.argsfile_xcode+ else:+ # filename example: .cpp.toolchain_cxx_args+ compiler_info_filename = filename_prefix + "toolchain_cxx_args"+ compiler_info_argsfile = mk_argsfile(compiler_info_filename, compiler_info_flags)++ argsfiles.append(compiler_info_argsfile)+ args_list.append(compiler_info_flags)++ make_toolchain_argsfile()++ def make_compiler_type_argsfile():+ compiler_type_flags = _add_compiler_type_flags(target_label, compiler_info.compiler_type, ext)++ if impl_params.anon_targets_allowed:+ compiler_type_flags_anon_target = actions.anon_target(+ _compiler_type_flags_anon_rule,+ {+ "compiler_type": compiler_info.compiler_type,+ "is_xcode_argsfile": is_xcode_argsfile,+ "src_extension": ext.value,+ },+ )+ compiler_type_argsfile_artifact = actions.assert_has_content_based_path(compiler_type_flags_anon_target.artifact("argsfile"))+ else:+ compiler_type_argsfile_artifact = mk_argsfile(+ filename_prefix + "compiler_type_args",+ compiler_type_flags,+ )+ argsfiles.append(compiler_type_argsfile_artifact)+ args_list.append(compiler_type_flags)++ make_compiler_type_argsfile()++ def make_cxx_flags_argsfile():+ flag_deps = impl_params.cxx_flags+ if not flag_deps:+ return++ flags = cxx_flags_tset(actions, flag_deps)+ projection = flags.project_as_args(+ cxx_flags_projection_name(ext.value),+ ordering = "postorder",+ )+ if impl_params.anon_targets_allowed:+ argsfile = actions.anon_target(+ _cxx_flags_argsfile_anon_rule,+ {+ "flags": flag_deps,+ "is_nasm": is_nasm,+ "is_precompile": is_precompile,+ "is_xcode_argsfile": is_xcode_argsfile,+ "src_extension": ext.value,+ },+ ).artifact("argsfile")+ argsfile = actions.assert_has_content_based_path(argsfile)+ else:+ argsfile = mk_argsfile(+ filename_prefix + "cxx_flags_args",+ _cxx_flags_args(flags, ext.value, is_precompile),+ )++ argsfiles.append(argsfile_with_artifacts(argsfile, projection))+ args_list.append(projection)++ make_cxx_flags_argsfile()++ def make_deps_argsfile():+ deps_args = []+ if is_precompile:+ # TODO(nml): We don't support dep files for now in precompile.+ deps_args.append(preprocessor.set.project_as_args("precompile_args"))+ else:+ deps_args.append(headers_tag.tag_artifacts(preprocessor.set.project_as_args("args")))++ # Different preprocessors will contain whether to use modules,+ # and the modulemap to use, so we need to get the final outcome.+ if preprocessor.set.reduce("uses_modules"):+ deps_args.append(headers_tag.tag_artifacts(preprocessor.set.project_as_args("modular_args")))++ # filename example: .cpp.deps_cxx_args, .cpp.deps_cxx_args_redacted+ deps_argsfile_for_compiler, deps_argsfile_for_buck_action_rerun = mk_argsfile_for_dep_file_filtering(filename_prefix + "deps_cxx_args", deps_args)+ argsfiles.append(+ cmd_args(+ headers_tag.tag_artifacts(deps_argsfile_for_compiler),+ hidden = [deps_argsfile_for_buck_action_rerun] if deps_argsfile_for_buck_action_rerun != None else [],+ )+ )+ args_list.extend(deps_args)++ make_deps_argsfile()++ def make_target_argsfile():+ target_args = [+ # preprocessor+ impl_params.preprocessor_flags,+ cxx_by_language_ext(impl_params.lang_preprocessor_flags, ext.value),+ get_flags_for_compiler_type(compiler_info.compiler_type),+ # compiler+ cxx_by_language_ext(impl_params.lang_compiler_flags, ext.value),+ # ctx.attrs.compiler_flags need to come last to preserve buck1 ordering, this prevents compiler+ # flags ordering-dependent build errors+ impl_params.compiler_flags,+ headers_tag.tag_artifacts(preprocessor.set.project_as_args("include_dirs")),+ ]+ if is_precompile:+ target_args = _filter_precompile_args(target_args)+ target_args = cmd_args(target_args)++ # Workaround as that's not precompiled, but working just as prefix header.+ # Another thing is that it's clang specific, should be generalized.+ if impl_params.precompiled_header != None and not impl_params.precompiled_header[CPrecompiledHeaderInfo].compiled:+ target_args.add(["-include", headers_tag.tag_artifacts(impl_params.precompiled_header[CPrecompiledHeaderInfo].header)])+ if impl_params.prefix_header != None:+ target_args.add(["-include", headers_tag.tag_artifacts(impl_params.prefix_header)])++ # filename example: .cpp.target_cxx_args+ target_argsfile_filename = filename_prefix + "target_cxx_args"+ argsfiles.append(mk_argsfile(target_argsfile_filename, target_args))+ args_list.append(target_args)++ make_target_argsfile()++ # Create a copy of the args so that we can continue to modify it later.+ args_without_file_prefix_args = cmd_args(args_list)++ # Holder, because the closure below cannot bind an enclosing name.+ file_prefix_specs = []++ def make_file_prefix_argsfile():+ if is_precompile:+ # The precompile_args field overrides these.+ return++ if compiler_info.compiler_type in ("nasm", "windows_ml64"):+ # NASM/MASM don't understand -ffile-prefix-map. .s/.sx/.S go through the gcc/clang+ # driver (as_compiler_info) and do accept these flags.+ return++ if not preprocessor.set.reduce("has_file_prefix_args"):+ return++ # Put file_prefix_args in argsfile, make sure they do not appear when evaluating $(cxxppflags)+ # to avoid "argument too long" errors+ file_prefix_args = headers_tag.tag_artifacts(preprocessor.set.project_as_args("file_prefix_args"))++ if ext.value == ".cu":+ # NVCC passes argsfile flags to device sub-tools (cicc, ptxas) which don't+ # understand -ffile-prefix-map.+ file_prefix_args = cmd_args(file_prefix_args, replace_regex = ("-ffile-prefix-map=", "-fdebug-prefix-map="))+ elif compiler_info.compiler_type == "clang":+ # -fcoverage-prefix-map is only supported by clang. Include coverage prefix args+ # only for clang to avoid breaking non-clang compilers that receive flags from+ # dependencies via the preprocessor set.+ coverage_prefix_args = headers_tag.tag_artifacts(preprocessor.set.project_as_args("coverage_prefix_args"))+ file_prefix_args = cmd_args(file_prefix_args, coverage_prefix_args)++ file_prefix_args_filename = filename_prefix + "file_prefix_cxx_args"++ # GCC copies all flags into COLLECT_GCC_OPTIONS env var before exec'ing cc1. This single+ # string can exceed Linux's 128KB MAX_ARG_STRLEN limit when there are hundreds of prefix-map+ # flags.+ #+ # Delivering via -specs injects flags directly into cc1 without touching+ # COLLECT_GCC_OPTIONS.+ #+ # Assembly may report compiler_type=="gcc" via as_compiler_info even on Clang toolchains;+ # -specs= is GCC-driver-only so skip it for assembly.+ if compiler_info.compiler_type == "gcc" and _get_category(ext) != "asm_compile":+ specs_content = cmd_args(+ "*cc1:\n+ ",+ file_prefix_args,+ delimiter = " ",+ )+ specs_file, specs_file_for_buck_action_rerun = write_for_dep_file_filtering(+ file_prefix_args_filename + ".specs",+ specs_content,+ )+ prefix_ref = cmd_args(+ headers_tag.tag_artifacts(specs_file),+ format = "-specs={}",+ hidden = specs_file_for_buck_action_rerun,+ )+ file_prefix_specs.append(specs_file)+ else:+ prefix_ref = file_prefix_args++ file_prefix_argsfile_for_compiler, file_prefix_argsfile_for_buck_action_rerun = mk_argsfile_for_dep_file_filtering(+ file_prefix_args_filename,+ prefix_ref,+ )+ argsfiles.append(+ cmd_args(+ headers_tag.tag_artifacts(file_prefix_argsfile_for_compiler),+ hidden = file_prefix_argsfile_for_buck_action_rerun,+ )+ )+ args_list.append(prefix_ref)++ make_file_prefix_argsfile()++ if is_xcode_argsfile:+ file_args = cmd_args(argsfiles, format = "@{}")+ elif is_nasm:+ file_args = cmd_args(argsfiles, format = "-@{}")+ else:+ file_args = cmd_args(argsfiles, format = "@{}", quote = "shell")++ # filename example: .cpp.cxx_compile_argsfile+ file_name = filename_prefix + "cxx_compile_argsfile"++ # For Xcode to parse argsfiles of argsfiles, the paths in the former must be absolute.+ argsfile, argsfile_for_buck_action_rerun = write_for_dep_file_filtering(+ file_name,+ file_args,+ absolute = is_xcode_argsfile,+ )++ args = create_cmd_args(is_nasm, is_xcode_argsfile, args_list)+ input_args = [args, file_args]+ if argsfile_for_buck_action_rerun != None:+ input_args.append(argsfile_for_buck_action_rerun)++ argsfile_format = "-@{}" if is_nasm else "@{}"+ cmd_form = cmd_args(+ headers_tag.tag_artifacts(argsfile),+ format = argsfile_format,+ hidden = input_args,+ )++ # The NVCC dry run expands the flags and reads header maps, nothing else behind them.+ cmd_form_cuda_dryrun = None+ if ext.value == ".cu":+ cmd_form_cuda_dryrun = cmd_args(+ argsfile,+ format = argsfile_format,+ hidden = [file_args, preprocessor.set.project_as_args("header_maps")],+ )+ return CompileArgsfile(+ file = argsfile,+ cmd_form = cmd_form,+ cmd_form_cuda_dryrun = cmd_form_cuda_dryrun,+ args = args,+ args_without_file_prefix_args = args_without_file_prefix_args,+ file_prefix_specs = file_prefix_specs[0] if file_prefix_specs else None,+ )++def _mk_header_units_argsfile(+ actions: AnalysisActions,+ compiler_info: typing.Any,+ preprocessor: CPreprocessorInfo,+ ext: CxxExtension,+ filename_prefix: str = "",+ has_content_based_path: bool = False,+ stub: bool = False,+) -> CompileArgsfile | None:+ """+ Generate and return an argsfile artifact containing all header unit options, and+ command args that utilize the argsfile.+ """+ if not preprocessor.set:+ return None+ if _get_category(ext) != "cxx_compile":+ return None+ if not _compiler_supports_header_units(compiler_info):+ return None+ if not preprocessor.set.reduce("has_header_units_args"):+ return None++ file_name = "{}.{}header_unit{}_args".format(ext.value, filename_prefix, "_stubs" if stub else "s")+ args = cmd_args()+ args.add([+ # TODO(nml): We only support Clang 17+, which don't need/want the extra -f+ # arguments when compiling C++20. Clang 15 is too buggy to work properly, but if+ # you wanted to try, you would need the below options at the very least, to get+ # started:+ # "-fmodules",+ # "-fno-implicit-modules",+ # "-fno-implicit-module-maps",+ "-Wno-experimental-header-units",+ "-Wno-ambiguous-macro",+ ])++ # TODO(nml): Tag args with headers_tag.tag_artifacts() once -MD -MF reports correct+ # usage of PCMs. See T225373444 and _mk_header_units_argsfile() below.+ projection_name = "header_unit_stubs_args" if stub else "header_units_args"+ args.add(preprocessor.set.project_as_args(projection_name))+ file_args = cmd_args(args, quote = "shell")+ argsfile, _ = actions.write(+ file_name,+ file_args,+ allow_args = True,+ has_content_based_path = has_content_based_path,+ )+ cmd_form = cmd_args(argsfile, format = "@{}", hidden = file_args)++ return CompileArgsfile(+ file = argsfile,+ cmd_form = cmd_form,+ args = file_args,+ args_without_file_prefix_args = args,+ )++def _get_dep_tracking_mode(toolchain: Provider, file_type: DepFileType) -> DepTrackingMode:+ if file_type == DepFileType("cpp") or file_type == DepFileType("c"):+ return toolchain.cpp_dep_tracking_mode+ elif file_type == DepFileType("cuda"):+ return toolchain.cuda_dep_tracking_mode+ else:+ return DepTrackingMode("makefile")++def get_compiler_type(ctx: AnalysisContext, ext: CxxExtension) -> typing.Any:+ toolchain = get_cxx_toolchain_info(ctx)+ compiler_info = _get_compiler_info(toolchain, ext)+ return compiler_info.compiler_type++def _generate_base_compile_command(+ actions: AnalysisActions,+ target_label: Label,+ toolchain: CxxToolchainInfo,+ impl_params: CxxRuleConstructorParams,+ pre: CPreprocessorInfo,+ headers_tag: ArtifactTag,+ ext: CxxExtension,+ filename_prefix: str = "",+) -> CxxCompileCommand:+ """+ Generate a common part of a compile command that is shared by all sources+ with a given extension.+ """+ compiler_info = _get_compiler_info(toolchain, ext)++ base_compile_cmd = _get_compile_base(toolchain, compiler_info, impl_params.use_fbcc_rust_wrapper)+ category = _get_category(ext)++ headers_dep_files = None+ dep_file_file_type_hint = _dep_file_type(ext)+ if dep_file_file_type_hint != None and toolchain.use_dep_files:+ tracking_mode = _get_dep_tracking_mode(toolchain, dep_file_file_type_hint)+ mk_dep_files_flags = get_headers_dep_files_flags_factory(tracking_mode)+ if mk_dep_files_flags:+ headers_dep_files = HeadersDepFiles(+ processor = cmd_args(toolchain.internal_tools.dep_file_processor),+ mk_flags = mk_dep_files_flags,+ tag = headers_tag,+ dep_tracking_mode = tracking_mode,+ )++ def gen_argsfiles(is_xcode_argsfile):+ return _mk_argsfiles(+ actions,+ target_label,+ impl_params,+ compiler_info,+ pre,+ ext,+ headers_tag,+ is_precompile = False,+ filename_prefix = filename_prefix,+ uses_content_based_paths = not is_xcode_argsfile,+ is_xcode_argsfile = is_xcode_argsfile,+ )++ argsfile = gen_argsfiles(is_xcode_argsfile = False)++ # The Xcode argsfile is consumed only by the `xcode-argsfiles` sub-target and+ # `XcodeDataInfo`, both of which are Xcode/IDE features gated on `xcode_data`.+ # Skip generating it (per source extension, per target) otherwise, saving+ # memory on non-IDE builds.+ if impl_params.generate_sub_targets.xcode_data:+ xcode_argsfile = gen_argsfiles(is_xcode_argsfile = True)+ else:+ xcode_argsfile = None++ header_units_argsfile = _mk_header_units_argsfile(+ actions,+ compiler_info,+ pre,+ ext,+ filename_prefix,+ has_content_based_path = True,+ stub = False,+ )++ header_unit_stubs_argsfile = _mk_header_units_argsfile(+ actions,+ compiler_info,+ pre,+ ext,+ filename_prefix,+ has_content_based_path = True,+ stub = True,+ )++ allow_content_based_paths = bool(compiler_info.supports_content_based_paths and impl_params.use_content_based_paths)+ return CxxCompileCommand(+ base_compile_cmd = base_compile_cmd,+ argsfile = argsfile,+ xcode_argsfile = xcode_argsfile,+ header_units_argsfile = header_units_argsfile,+ header_unit_stubs_argsfile = header_unit_stubs_argsfile,+ headers_dep_files = headers_dep_files,+ compiler_type = compiler_info.compiler_type,+ category = category,+ allow_cache_upload = impl_params.allow_cache_upload,+ allow_content_based_paths = allow_content_based_paths,+ )++def _get_use_pch_args(+ src: Artifact,+ cxx_compile_cmd: CxxCompileCommand,+ compile_with_pch: CPrecompiledHeaderInfo,+ precompiled_header: CPrecompiledHeaderInfo,+) -> cmd_args:+ if precompiled_header.clanguage != src.extension:+ return cmd_args()++ pch_args = cmd_args()+ if cxx_compile_cmd.compiler_type in ["windows"]:+ pch_args.add(cmd_args(compile_with_pch.basename, format = "/Yu{}"))+ pch_args.add(cmd_args(compile_with_pch.basename, format = "/FI{}"))+ pch_args.add(cmd_args(compile_with_pch.header, format = "/Fp{}"))+ elif cxx_compile_cmd.compiler_type in ["clang"]:+ pch_args.add("-Xclang", "-include-pch", "-Xclang", compile_with_pch.header)+ else:+ fail(+ "Warning: Unsupported compiler type for precompiled header usage: {}".format(+ cxx_compile_cmd.compiler_type,+ )+ )++ return pch_args++def _declare_clang_trace_output(+ toolchain: CxxToolchainInfo, compiler_type: str, actions: AnalysisActions, filename_base: str, content_based: bool+) -> Artifact | None:+ """+ Declares an output artifact for clang trace JSON file.+ """+ if toolchain.clang_trace and compiler_type == "clang":+ return actions.declare_output(+ paths.join("__objects__", "{}.json".format(filename_base)),+ has_content_based_path = content_based,+ )+ return None++def _declare_assembly(actions: AnalysisActions, compiler_type: str, object_format: CxxObjectFormat, filename_base: str, content_based: bool) -> Artifact | None:+ """+ Declares an output artifact for assembly or LLVM IR output file.+ Returns None for compilers that don't support the -S flag.+ """+ if compiler_type not in ["clang", "gcc"]:+ return None++ # Generate assembler or llvm bitcode output file+ assembly_extension = "s"+ if compiler_type == "clang" and object_format == CxxObjectFormat("bitcode"):+ assembly_extension = "ll"++ return actions.declare_output(+ "__assembly__",+ "{}.{}".format(filename_base, assembly_extension),+ has_content_based_path = content_based,+ )
@@ -0,0 +1,202 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")+load(":argsfiles.bzl", "CompileArgsfile", "CompileArgsfiles")+load(":cxx_toolchain_types.bzl", "CxxObjectFormat", "DepTrackingMode")++# Supported assembly extensions+AsmExtensions = enum(+ ".s",+ ".sx",+ ".S",+ ".asm",+ ".asmpp",+)++# Supported Cxx file extensions+CxxExtension = enum(".cpp", ".cc", ".cl", ".cxx", ".c++", ".c", ".m", ".mm", ".cu", ".hip", ".h", ".hpp", ".hh", ".h++", ".hxx", ".bc", *AsmExtensions.values())++# Header files included in compilation databases+HeaderExtension = enum(+ ".h",+ ".hpp",+ ".hh",+ ".h++",+ ".hxx",+ ".cuh",+)++# Mode for using header units in compilation+UseHeaderUnitsMode = enum(+ # Don't use header units+ "none",+ # Use full precompiled modules (.pcm files)+ "pcm",+ # Use module stubs (.pcm.stub files): those are not directly used in the compilation+ # command line; instead, they are inert stand-ins that behave like real PCM files,+ # cache-wise (i.e. expected to be cached when real PCM files would be cached, and+ # rebuilt when PCM files would be). You can enable these to trace and model the+ # behaviour of module-enabled builds before actually migrating to them. This steps+ # helps estimate the overhead of precompiling modules in terms of additional+ # uncached Buck actions.+ "stub",+)++# File types for dep files+DepFileType = enum(+ "cpp",+ "c",+ "cuda",+ "asm",+)++HeadersDepFiles = record(+ # An executable to wrap the actual command with for post-processing of dep+ # files into the format that Buck2 recognizes (i.e. one artifact per line).+ processor = field(cmd_args),+ # The tag that was added to headers.+ tag = field(ArtifactTag),+ # A function that produces new cmd_args to append to the compile command to+ # get it to emit the dep file. This will receive the output dep file as an+ # input.+ mk_flags = field(typing.Callable),+ # Dependency tracking mode to know how to generate dep file+ dep_tracking_mode = field(DepTrackingMode),+)++# Output from CUDA distributed compilation+CudaDistributedCompileOutput = record(+ # Dependency graph of the NVCC sub-commands.+ nvcc_dag = field(Artifact),+ # Environment variables for the NVCC sub-commands.+ nvcc_env = field(Artifact),+ # Argsfile for the host compiler.+ hostcc_argsfile = field(Artifact),+)++# Information about how to compile a source file of particular extension.+CxxCompileCommand = record(+ # The compiler and any args which are independent of the rule.+ base_compile_cmd = field(cmd_args),+ # The argsfile of arguments from the rule and it's dependencies.+ argsfile = field(CompileArgsfile),+ # The argsfile to use for Xcode integration. Requires xcode_data subtarget.+ xcode_argsfile = field(CompileArgsfile | None),+ # The argsfile containing header units args.+ header_units_argsfile = field(CompileArgsfile | None),+ # The argsfile containing header unit stubs args.+ header_unit_stubs_argsfile = field(CompileArgsfile | None),+ headers_dep_files = field([HeadersDepFiles, None]),+ compiler_type = field(str),+ # The action category+ category = field(str),+ allow_cache_upload = field(bool),+ allow_content_based_paths = field(bool),+)++# Declared index store output and metadata+DeclaredIndexStore = record(+ output = field(Artifact),+ filename_base = field(str),+)++# Factory for creating and compiling index stores+# - declare: Called during analysis to declare the output artifact+# - compile: Called during execution (inside dynamic action) to run the compilation+IndexStoreFactory = record(+ declare = field(typing.Callable[[AnalysisActions, typing.Any], DeclaredIndexStore | None]),+ compile = field(typing.Callable[[AnalysisActions, Label, OutputArtifact, str, CxxToolchainInfo, cmd_args], None]),+)++# Information about how to compile a source file.+CxxSrcCompileCommand = record(+ # Source file to compile.+ src = field(Artifact),+ # If we have multiple source entries with same files but different flags,+ # specify an index so we can differentiate them. Otherwise, use None.+ index = field([int, None], None),+ # The CxxCompileCommand to use to compile this file.+ cxx_compile_cmd = field(CxxCompileCommand),+ # Arguments specific to the source file.+ args = field(list[typing.Any]),+ # Is this a header file?+ is_header = field(bool, False),+ # Whether to use content-based paths for the outputs of the compilation command.+ uses_content_based_paths = field(bool),+ # The index store factory to use to generate index store for this source file.+ index_store_factory = field(IndexStoreFactory | None, None),+ error_handler = field([typing.Callable, None], None),+ # Whether to set expect_eligible_for_dedupe on compile actions.+ expect_eligible_for_dedupe = field(bool, False),+)++CxxSrcPrecompileCommand = record(+ # Source file to compile.+ src = field(Artifact),+ # The CxxCompileCommand to use to compile this file.+ cxx_compile_cmd = field(CxxCompileCommand),+ # Arguments specific to the source file.+ args = field(list[typing.Any]),+ # Arguments for -fsyntax-only check (args without --precompile and+ # -DFACEBOOK_CPP_HEADER_UNIT=1, with -fsyntax-only instead).+ check_args = field(list[typing.Any], []),+ # Extra argsfile to include after any other header units argsfile but before the+ # main argsfiles.+ extra_argsfile = field([CompileArgsfile, None], None),+)++# Output of creating compile commands for Cxx source files.+CxxCompileCommandOutput = record(+ # List of compile commands for each source file.+ src_compile_cmds = field(list[CxxSrcCompileCommand], default = []),+ # Base compile commands for each source file extension.+ base_compile_cmds = field(dict[CxxExtension, CxxCompileCommand], default = {}),+ # Argsfiles generated for compiling these source files.+ argsfiles = field(CompileArgsfiles, default = CompileArgsfiles()),+ # List of compile commands for use in compilation database generation.+ comp_db_compile_cmds = field(list[CxxSrcCompileCommand], default = []),+)++CxxCompileOutput = record(+ # The compiled `.o` file.+ object = field(Artifact),+ object_format = field(CxxObjectFormat, CxxObjectFormat("native")),+ object_has_external_debug_info = field(bool, False),+ # Externally referenced debug info, which doesn't get linked with the+ # object (e.g. the above `.o` when using `-gsplit-dwarf=single` or the+ # the `.dwo` when using `-gsplit-dwarf=split`).+ external_debug_info = field(Artifact | None, None),+ clang_remarks = field(Artifact | None, None),+ clang_llvm_statistics = field(Artifact | None, None),+ clang_trace = field(Artifact | None, None),+ gcno_file = field(Artifact | None, None),+ index_store = field(Artifact | None, None),+ assembly = field(Artifact | None, None),+ diagnostics = field(Artifact | None, None),+ clang_tidy_diagnostics = field(Artifact | None, None),+ preproc = field(Artifact | None, None),+ dist_cuda = field(CudaDistributedCompileOutput | None, None),+ pch_object = field(Artifact | None, None),+ json_error = field(Artifact | None, None),+ # True for HIP TUs under the device-debug-extract modifier.+ hip_device_debug = field(bool, False),+ # Per-arch sidecar .debug files from hip_debug_extract_compile_object.+ hip_arch_debug_files = field(dict[str, Artifact], {}),+)++CxxCompileFlavor = enum(+ # Produces position independent compile outputs+ "pic",+ # Produces position independent compile outputs+ # using optimization flags from toolchain+ "optimized",+ # Produces position independent compile outputs+ # using debug flags from toolchain+ "debug",+)
@@ -0,0 +1,87 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load(+ "@prelude//utils:utils.bzl",+ "as_output",+)+load(":cxx_toolchain_types.bzl", "DepTrackingMode")++# TODO(T110378132): Added here for compat with v1, but this might make more+# sense on the toolchain definition.+def get_flags_for_reproducible_build(target_label: Label, compiler_type: str) -> list[[str, cmd_args]]:+ """+ Return flags needed to make compilations reproducible (e.g. avoiding+ embedding the working directory into debug info.+ """++ flags = []++ if compiler_type in ["clang_cl", "windows"]:+ flags.extend(["/Brepro", "/d2threads1"])++ if compiler_type in ["clang", "clang_windows", "clang_cl"]:+ flags.extend(["-Xclang", "-fdebug-compilation-dir", "-Xclang", cmd_args(target_label.project_root)])++ if compiler_type == "clang_windows":+ flags.append("-mno-incremental-linker-compatible")++ return flags++def get_flags_for_colorful_output(compiler_type: str) -> list[str]:+ """+ Return flags for enabling colorful diagnostic output.+ """+ flags = []+ if compiler_type in ["clang", "clang_windows", "clang_cl"]:+ # https://clang.llvm.org/docs/UsersManual.html+ flags.append("-fcolor-diagnostics")+ elif compiler_type == "gcc":+ # https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Message-Formatting-Options.html+ flags.append("-fdiagnostics-color=always")++ return flags++# These functions return two values: wrapper_args and compiler_args+# wrapper_args -> the arguments used by the dep_file_processor to determine how to process the dep files+# compiler_args -> args passed to the compiler when generating dependencies++def cc_dep_files(actions: AnalysisActions, filename_base: str, _input_file: Artifact) -> (cmd_args, cmd_args):+ intermediary_dep_file = actions.declare_output(+ paths.join("__dep_files_intermediaries__", filename_base),+ has_content_based_path = True,+ ).as_output()++ return (cmd_args(intermediary_dep_file), cmd_args(["-MD", "-MF", intermediary_dep_file]))++def tree_style_cc_dep_files(_actions: AnalysisActions, _filename_base: str, input_file: Artifact) -> (cmd_args, cmd_args):+ # If we use color diagnostics, then error messages come through in color, which messes up parsing of the+ # -H output in `show_headers_to_dep_file.py`. So make sure to pass -fno-color-diagnostics.+ return (cmd_args(input_file), cmd_args(["-H", "-fno-color-diagnostics"]))++def windows_cc_dep_files(_actions: AnalysisActions, _filename_base: str, input_file: Artifact) -> (cmd_args, cmd_args):+ return (cmd_args(input_file), cmd_args(["/showIncludes"]))++def get_headers_dep_files_flags_factory(dep_tracking_mode: DepTrackingMode) -> [typing.Callable, None]:+ if dep_tracking_mode.value == "makefile":+ return cc_dep_files++ if dep_tracking_mode.value == "show_includes":+ return windows_cc_dep_files++ if dep_tracking_mode.value == "show_headers":+ return tree_style_cc_dep_files++ return None++def get_output_flags(compiler_type: str, output: Artifact | OutputArtifact) -> list[typing.Any]:+ if compiler_type in ["windows", "clang_cl", "windows_ml64"]:+ return [cmd_args(as_output(output), format = "/Fo{}")]+ else:+ return ["-o", as_output(output)]
@@ -0,0 +1,603 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//cxx:compile_types.bzl", "CudaDistributedCompileOutput", "CxxCompileCommand", "HeadersDepFiles")+load("@prelude//cxx:compiler.bzl", "get_output_flags")+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")+load("@prelude//cxx:headers.bzl", "add_headers_dep_files")+load(+ "@prelude//utils:utils.bzl",+ "as_output",+)++CudaCompileInfo = record(+ # Output base filename without extension+ filename = field(str),+ # Buck action identifier+ identifier = field(str),+ # Output sub-directory where all CUDA compilation artifacts will go to+ output_prefix = field(str),+ uses_content_based_paths = field(bool),+)++CudaCompileStyle = enum(+ # Use NVCC as the compiler driver and compile a CUDA file in a single Buck+ # action.+ "mono",+ # NVCC provides the compilation plan, but use one Buck action per compilation+ # sub-command.+ "dist",+)++CudaDistributedCompileSpec = record(+ cuda_compile_info = field(CudaCompileInfo),+ original_cmd = field(cmd_args),+ argsfile_args = field(cmd_args),+ file_prefix_specs = field(Artifact | None),+ output_declared_artifact = field(OutputArtifact),+ src = field(Artifact),+)++PreparedCudaCommand = record(+ cmd_node = field(dict[str, typing.Any]),+ exe = field(str),+ parts = field(list[typing.Any]),+)++def declare_cuda_dist_compile_output(actions: AnalysisActions, cuda_compile_info: CudaCompileInfo) -> CudaDistributedCompileOutput:+ """+ Declare output artifacts for CUDA distributed compilation upfront.+ This should be called during analysis before the dynamic action.+ """+ content_based = cuda_compile_info.uses_content_based_paths++ # Create the following files for each CUDA file:+ # - Envvars to run the NVCC sub-commands with.+ # - A dependency graph of the NVCC sub-commands.+ # - Argsfile for the host compiler.+ env = actions.declare_output(+ cuda_compile_info.output_prefix,+ "{}.env".format(cuda_compile_info.filename),+ has_content_based_path = content_based,+ )+ subcmds = actions.declare_output(+ cuda_compile_info.output_prefix,+ "{}.json".format(cuda_compile_info.filename),+ has_content_based_path = content_based,+ )+ hostcc_argsfile = actions.declare_output(+ cuda_compile_info.output_prefix,+ "{}.hostcc_argsfile".format(cuda_compile_info.filename),+ has_content_based_path = content_based,+ )+ return CudaDistributedCompileOutput(+ nvcc_dag = subcmds,+ nvcc_env = env,+ hostcc_argsfile = hostcc_argsfile,+ )++def cuda_mono_compile(+ actions: AnalysisActions,+ cmd: cmd_args,+ object: OutputArtifact,+ src: Artifact,+ cxx_compile_cmd: CxxCompileCommand,+ cuda_compile_info: CudaCompileInfo,+ action_dep_files: dict[str, ArtifactTag],+ allow_dep_file_cache_upload: bool,+ error_handler: [typing.Callable, None],+) -> None:+ """+ Compile a CUDA file monolithically using NVCC as the compiler driver.+ All compilation happens in a single Buck action.+ """++ # Bind the object output for monolithic NVCC compilation.+ cmd.add(get_output_flags(cxx_compile_cmd.compiler_type, object))+ headers_dep_files = cxx_compile_cmd.headers_dep_files+ if headers_dep_files:+ cmd = add_headers_dep_files(+ actions,+ cmd,+ headers_dep_files,+ src,+ cuda_compile_info.filename,+ action_dep_files,+ )+ actions.run(+ cmd,+ category = cxx_compile_cmd.category,+ identifier = cuda_compile_info.identifier,+ dep_files = action_dep_files,+ allow_cache_upload = cxx_compile_cmd.allow_cache_upload,+ allow_dep_file_cache_upload = allow_dep_file_cache_upload,+ error_handler = error_handler,+ )++def cuda_distributed_compile(+ actions: AnalysisActions,+ cmd: cmd_args,+ object: OutputArtifact,+ cuda_dist_output: CudaDistributedCompileOutput,+ src: Artifact,+ cxx_compile_cmd: CxxCompileCommand,+ cuda_compile_info: CudaCompileInfo,+ cuda_prepare_cmd: cmd_args | None,+ shared_plan_identifier: str | None,+) -> CudaDistributedCompileSpec:+ """+ Set up distributed compilation for a CUDA file: optionally register the+ nvcc -dryrun prepare action that produces the target's shared compilation+ plan, and return the spec from which create_cuda_distributed_compiles+ later creates one Buck action per NVCC sub-command.++ Compilation modes that require a whole-program device link step are NOT+ supported here: relocatable device code (-rdc=true / --device-c), device+ LTO (-dlto), and PTX-only codegen all make nvcc -dryrun emit an nvlink+ sub-command that dist NVCC cannot distribute. Such targets must set+ cuda_compile_style = "mono". If one of these modes reaches this path, the+ dryrun parser (tools/build/cuda/nvcc_dryrun.py) fails the+ cuda_compile_prepare action with an actionable error that names the source+ .cu and points to the mono escape hatch.+ """+ hostcc_argsfile = cuda_dist_output.hostcc_argsfile++ # The object is produced by the replayed plan sub-actions, not by this+ # command, so embed its path as a string rather than binding the output.+ cmd_with_output = cmd_args(cmd, ["-o", object.short_path])+ original_cmd = cmd_args(+ cmd_with_output,+ hidden = [+ cxx_compile_cmd.base_compile_cmd,+ cxx_compile_cmd.argsfile.cmd_form,+ ],+ )++ # The dry run never opens this file. It matches the flag, echoed as one+ # `-specs=<path>` token, so the plan can carry a placeholder in place of a+ # path that moves with the header closure.+ file_prefix_specs = cxx_compile_cmd.argsfile.file_prefix_specs++ if cuda_prepare_cmd != None:+ prepare_cmd = cmd_args(+ cuda_prepare_cmd,+ ["-o", object.short_path],+ [+ "-_NVCC_DRYRUN_",+ "-_NVCC_HOSTCC_ARGSFILE_",+ as_output(hostcc_argsfile),+ "-_NVCC_DRYRUN_ENV_OUT_",+ as_output(cuda_dist_output.nvcc_env),+ "-_NVCC_DRYRUN_DAG_OUT_",+ as_output(cuda_dist_output.nvcc_dag),+ ],+ )+ if file_prefix_specs != None:+ prepare_cmd.add(+ "-_NVCC_FILE_PREFIX_SPECS_",+ cmd_args(file_prefix_specs, format = "-specs={}"),+ )++ # Run nvcc with -dryrun to create the inputs needed for dist nvcc.+ actions.run(prepare_cmd, category = "cuda_compile_prepare", identifier = shared_plan_identifier or cuda_compile_info.identifier)++ return CudaDistributedCompileSpec(+ cuda_compile_info = cuda_compile_info,+ original_cmd = original_cmd,+ argsfile_args = cxx_compile_cmd.argsfile.args,+ file_prefix_specs = file_prefix_specs,+ output_declared_artifact = object,+ src = src,+ )++# Keep the old cuda_compile function for backward compatibility+def cuda_compile(+ actions: AnalysisActions,+ cmd: cmd_args,+ object: OutputArtifact,+ src: Artifact,+ cxx_compile_cmd: CxxCompileCommand,+ cuda_compile_info: CudaCompileInfo,+ action_dep_files: dict[str, ArtifactTag],+ allow_dep_file_cache_upload: bool,+ error_handler: [typing.Callable, None],+ cuda_compile_style: CudaCompileStyle | None,+ cuda_dist_output: CudaDistributedCompileOutput | None = None,+ cuda_prepare_cmd: cmd_args | None = None,+ shared_plan_identifier: str | None = None,+) -> CudaDistributedCompileSpec | None:+ """+ Compile a CUDA file using either monolithic or distributed compilation.+ This is a convenience function that dispatches to the appropriate implementation.+ """+ if cuda_compile_style == CudaCompileStyle("mono"):+ cuda_mono_compile(+ actions,+ cmd,+ object,+ src,+ cxx_compile_cmd,+ cuda_compile_info,+ action_dep_files,+ allow_dep_file_cache_upload,+ error_handler,+ )+ return None+ elif cuda_compile_style == CudaCompileStyle("dist"):+ if cuda_dist_output == None:+ fail("cuda_dist_output is required for distributed CUDA compilation")+ return cuda_distributed_compile(+ actions,+ cmd,+ object,+ cuda_dist_output,+ src,+ cxx_compile_cmd,+ cuda_compile_info,+ cuda_prepare_cmd,+ shared_plan_identifier,+ )+ else:+ fail("Unsupported CUDA compile style: {}".format(cuda_compile_style))++def create_cuda_distributed_compiles(+ actions: AnalysisActions,+ toolchain: CxxToolchainInfo,+ cuda_dist_output: CudaDistributedCompileOutput,+ specs: list[CudaDistributedCompileSpec],+ allow_cache_upload: bool,+ cuda_cxx_compile_inputs: cmd_args,+ headers_dep_files: HeadersDepFiles | None,+) -> None:+ if not specs:+ return++ # The argsfile is shared by the target's sources, so one fingerprint covers+ # them all. It carries the same flags with content-based paths rendered as a+ # placeholder: it moves when a flag really changes, not when a path does.+ hostcc_argsfile_fingerprint = None+ if headers_dep_files != None:+ hostcc_argsfile_fingerprint, _ = actions.write(+ "__redacted__/{}.hostcc_argsfile_fingerprint".format(specs[0].cuda_compile_info.filename),+ cmd_args(specs[0].original_cmd, specs[0].argsfile_args, quote = "shell"),+ allow_args = True,+ has_content_based_path = specs[0].cuda_compile_info.uses_content_based_paths,+ use_dep_files_placeholder_for_content_based_paths = True,+ )++ actions.dynamic_output_new(+ _nvcc_dynamic_compile_rule(+ toolchain = toolchain,+ cuda_compile_infos = [spec.cuda_compile_info for spec in specs],+ srcs = [spec.src for spec in specs],+ allow_cache_upload = allow_cache_upload,+ cuda_cxx_compile_inputs = cuda_cxx_compile_inputs,+ headers_dep_files = headers_dep_files,+ original_cmds = [spec.original_cmd for spec in specs],+ hostcc_argsfile = cuda_dist_output.hostcc_argsfile,+ hostcc_argsfile_fingerprint = hostcc_argsfile_fingerprint,+ file_prefix_specs = specs[0].file_prefix_specs,+ plan_artifact = cuda_dist_output.nvcc_dag,+ env_artifact = cuda_dist_output.nvcc_env,+ output_declared_artifacts = [spec.output_declared_artifact for spec in specs],+ )+ )++def _create_file_to_artifact_map(+ actions: AnalysisActions,+ plan_json: list[dict[str, typing.Any]],+ src: Artifact,+ cuda_compile_info: CudaCompileInfo,+ output_declared_artifact: OutputArtifact,+ uses_content_based_paths: bool,+) -> dict[str, Artifact | OutputArtifact]:+ # Create artifacts for all intermediate input and output files.+ file2artifact = {}+ for cmd_node in plan_json:+ node_inputs = cmd_node["inputs"]+ node_outputs = cmd_node["outputs"]+ for input in node_inputs:+ if input not in file2artifact:+ if input.endswith(".cu"):+ file2artifact[input] = src+ else:+ input_artifact = actions.declare_output(+ "__cuda_intermediates__",+ "{}/{}".format(cuda_compile_info.filename, input),+ has_content_based_path = uses_content_based_paths,+ )+ file2artifact[input] = input_artifact+ for output in node_outputs:+ if output not in file2artifact:+ if output.endswith(".o"):+ file2artifact[output] = output_declared_artifact+ else:+ output_artifact = actions.declare_output(+ "__cuda_intermediates__",+ "{}/{}".format(cuda_compile_info.filename, output),+ has_content_based_path = uses_content_based_paths,+ )+ file2artifact[output] = output_artifact+ return file2artifact++def _create_nvcc_subcmd_env(env_artifact: ArtifactValue) -> dict[str, str]:+ # Create the nvcc envvars for the sub-commands.+ subcmd_env = {}+ for line in env_artifact.read_string().splitlines():+ key, value = line.split("=", 1)+ subcmd_env[key] = value+ return subcmd_env++def _include_symlinked_stubs_dir(+ actions: AnalysisActions,+ cuda_compile_info: CudaCompileInfo,+ file2artifact: dict[str, typing.Any],+ subcmd: cmd_args,+) -> None:+ """+ .cudafe1.stub.c and .fatbin.c files are hardcoded into the cudafe1.cpp file+ and its includes like below:++ #include "add.cu.o.compute_90a.cudafe1.stub.c"++ Before content-based hashing, this worked fine because all outputs were under+ the same directory. However, with content-based hashing this no longer works+ because the output files are put under the output_artifacts sub-directory.++ Fix this by creating a directory containing symlinks to the actual stubs, and+ adding it to the cuda_cxx_compile include search path.+ """+ stubs_dir = actions.declare_output(+ "__stubs__",+ cuda_compile_info.filename,+ dir = True,+ has_content_based_path = True,+ )+ stubs = {}+ for file, artifact in file2artifact.items():+ if file.endswith(".cudafe1.stub.c") or file.endswith(".fatbin.c"):+ # Remove the parent paths because the includes are the filenames only.+ # Each stubs directory is scoped to one CUDA source file.+ stubs[artifact.basename] = artifact+ symlinked_dir = actions.symlinked_dir(+ stubs_dir,+ stubs,+ has_content_based_path = True,+ )+ subcmd.add(cmd_args(symlinked_dir, format = "-I{}"))++def _prepare_cuda_command(cmd_node: dict[str, typing.Any], hostcc_wp_form: cmd_args, specs_form: cmd_args | None) -> PreparedCudaCommand:+ parts = []+ common = cmd_args()+ for token in cmd_node["cmd"][1:]:+ placeholder = None+ if "{input}" in token:+ placeholder = "input"+ elif "{output}" in token:+ placeholder = "output"+ elif "{source_path}" in token:+ placeholder = "source_path"++ if placeholder != None:+ parts.append(("common", common))+ left, right = token.split("{" + placeholder + "}", 1)++ # Replay substitutes exactly one placeholder per token; a second+ # one would be passed through literally.+ for kind in ("input", "output", "source_path"):+ if "{" + kind + "}" in left + right:+ fail("plan token carries multiple placeholders: {}".format(token))+ parts.append((placeholder, (left, right)))+ common = cmd_args()+ elif token.startswith("-Wp,@"):+ common.add(hostcc_wp_form)+ elif token == "{file_prefix_specs}":+ if specs_form == None:+ fail("CUDA plan references file-prefix specs without a specs artifact")+ common.add(specs_form)+ else:+ common.add(token)+ parts.append(("common", common))+ return PreparedCudaCommand(cmd_node = cmd_node, exe = cmd_node["cmd"][0], parts = parts)++def _cuda_replay_input_kind(category: str) -> str:+ # Device phase categories appear both arch-suffixed (`cuda_opt_sm90a`) and+ # bare: the plan parser emits the bare form whenever an intermediate file+ # name carries no compute_{arch} component, e.g. for arch suffixes its+ # normalization does not recognize.+ if category == "cuda_host_preproc" or category == "cuda_device_preproc" or category.startswith("cuda_device_preproc_"):+ return "preprocess"+ if category == "cuda_cxx_compile":+ return "host_compile"+ if category in ("cudafepp", "cuda_fatbin", "cuda_opt", "cuda_cubin_lower") or category.startswith("cuda_opt_") or category.startswith("cuda_cubin_lower_"):+ return "cuda_tool"+ fail("Unsupported distributed CUDA phase category `{}`; update its input policy".format(category))++def _nvcc_dynamic_compile(+ actions: AnalysisActions,+ toolchain: CxxToolchainInfo,+ cuda_compile_infos: list[CudaCompileInfo],+ srcs: list[Artifact],+ allow_cache_upload: bool,+ cuda_cxx_compile_inputs: cmd_args,+ headers_dep_files: HeadersDepFiles | None,+ original_cmds: list[cmd_args],+ hostcc_argsfile: Artifact,+ hostcc_argsfile_fingerprint: Artifact | None,+ file_prefix_specs: Artifact | None,+ plan_artifact: ArtifactValue,+ env_artifact: ArtifactValue,+ output_declared_artifacts: list[OutputArtifact],+) -> list[Provider]:+ num_sources = len(cuda_compile_infos)+ if len(srcs) != num_sources or len(original_cmds) != num_sources or len(output_declared_artifacts) != num_sources:+ fail(+ "per-source dist CUDA lists must be the same length, got {}/{}/{}/{}".format(+ len(cuda_compile_infos),+ len(srcs),+ len(original_cmds),+ len(output_declared_artifacts),+ )+ )++ plan = plan_artifact.read_json()+ subcmd_env = _create_nvcc_subcmd_env(env_artifact)++ # The plan is shared across the target's sources, so these references are+ # built once from the representative source. Tagging lets dep-file filtering+ # drop their paths from each sub-action key; the untagged fingerprint is what+ # still reruns the sub-actions when a flag changes.+ if headers_dep_files != None and hostcc_argsfile_fingerprint != None:+ hostcc_wp_form = cmd_args(+ headers_dep_files.tag.tag_artifacts(hostcc_argsfile),+ format = "-Wp,@{}",+ hidden = [hostcc_argsfile_fingerprint],+ )+ else:+ hostcc_wp_form = cmd_args(hostcc_argsfile, format = "-Wp,@{}")++ specs_form = None+ if file_prefix_specs != None:+ if headers_dep_files != None:+ specs_form = cmd_args(+ headers_dep_files.tag.tag_artifacts(file_prefix_specs),+ format = "-specs={}",+ )+ else:+ specs_form = cmd_args(file_prefix_specs, format = "-specs={}")++ prepared_commands = [_prepare_cuda_command(cmd_node, hostcc_wp_form, specs_form) for cmd_node in plan]+ cuda_toolchain = getattr(toolchain.cuda_compiler_info, "compiler_for_dryrun", None) or toolchain.cuda_compiler_info.compiler+ cuda_tool_inputs = cmd_args(hidden = [cuda_toolchain])++ for cuda_compile_info, src, original_cmd, output_declared_artifact in zip(+ cuda_compile_infos,+ srcs,+ original_cmds,+ output_declared_artifacts,+ ):+ content_based = cuda_compile_info.uses_content_based_paths+ file2artifact = _create_file_to_artifact_map(+ actions,+ plan,+ src,+ cuda_compile_info,+ output_declared_artifact,+ content_based,+ )++ category_counts = {}+ for prepared in prepared_commands:+ cmd_node = prepared.cmd_node+ subcmd = cmd_args()+ exe = prepared.exe+ input_kind = _cuda_replay_input_kind(cmd_node["category"])+ if input_kind == "preprocess":+ subcmd.add(cmd_args(hidden = original_cmd))+ elif input_kind == "host_compile":+ subcmd.add(cmd_args(hidden = cuda_cxx_compile_inputs))+ else:+ subcmd.add(cuda_tool_inputs)++ if "ptxas" in exe:+ # Ptxas occasionally produces an empty output. The root cause+ # is unknown as we're unable to reproduce it locally. Check the+ # output is not empty+ subcmd.add(toolchain.internal_tools.check_nonempty_output)+ subcmd.add(exe)++ # The stubs directory must lead the include path so its generated+ # stub files shadow any same-named file in later include dirs.+ if content_based and cmd_node["category"] == "cuda_cxx_compile":+ _include_symlinked_stubs_dir(actions, cuda_compile_info, file2artifact, subcmd)++ input_index = 0+ output_index = 0+ for kind, value in prepared.parts:+ if kind == "common":+ subcmd.add(value)+ elif kind == "input":+ input = cmd_node["inputs"][input_index]+ input_index += 1+ subcmd.add(cmd_args([value[0], file2artifact[input], value[1]], delimiter = ""))+ elif kind == "output":+ output = cmd_node["outputs"][output_index]+ output_index += 1+ artifact = file2artifact[output]+ bindable = artifact.as_output() if isinstance(artifact, Artifact) else artifact+ subcmd.add(cmd_args([value[0], bindable, value[1]], delimiter = ""))+ elif kind == "source_path":+ # The contents of the `source_path` files are not actually+ # used as inputs to the sub-action, they are used primarily+ # to name the actual source path for inclusion in things like+ # DWARF information. However, artifacts with content-based-paths+ # can't know their paths until their content is known, so they+ # cannot be included as ignore_artifacts=True+ # TODO(jtbraun): when has_content_based_path is available,+ # use that as the condition here+ if src.is_source:+ subcmd.add(cmd_args([value[0], src, value[1]], delimiter = "", ignore_artifacts = True))+ else:+ subcmd.add(cmd_args([value[0], src, value[1]], delimiter = ""))+ else:+ fail("unhandled placeholder kind: {}".format(kind))++ # Some nodes have hidden dependencies (deps that don't appear in+ # the cmd). Add them to the hidden field of cmd_args.+ if cmd_node["hidden"]:+ subcmd.add(cmd_args(hidden = [file2artifact[f] for f in cmd_node["hidden"]]))++ # Host-compiler sub-actions pin a declared header closure; dep files+ # let the compiler report what it actually read so buck can prune the+ # rest from the action key.+ action_dep_files = {}+ if input_kind != "cuda_tool" and headers_dep_files != None:+ # Categories can repeat within a plan, so disambiguate with a+ # per-category ordinal.+ ordinal = category_counts.get(cmd_node["category"], 0)+ category_counts[cmd_node["category"]] = ordinal + 1+ subcmd = add_headers_dep_files(+ actions,+ subcmd,+ headers_dep_files,+ src,+ "{}/{}/{}".format(cuda_compile_info.filename, cmd_node["category"], ordinal),+ action_dep_files,+ )++ actions.run(+ subcmd,+ category = cmd_node["category"],+ env = subcmd_env,+ identifier = cuda_compile_info.identifier,+ dep_files = action_dep_files,+ allow_cache_upload = allow_cache_upload,+ allow_dep_file_cache_upload = False,+ prefer_remote = True if "preproc" in cmd_node["category"] else False,+ )++ return [DefaultInfo()]++_nvcc_dynamic_compile_rule = dynamic_actions(+ impl = _nvcc_dynamic_compile,+ attrs = {+ "allow_cache_upload": dynattrs.value(bool),+ "cuda_compile_infos": dynattrs.list(dynattrs.value(CudaCompileInfo)),+ "cuda_cxx_compile_inputs": dynattrs.value(cmd_args),+ "env_artifact": dynattrs.artifact_value(),+ "file_prefix_specs": dynattrs.option(dynattrs.value(Artifact)),+ "headers_dep_files": dynattrs.option(dynattrs.value(HeadersDepFiles)),+ "hostcc_argsfile": dynattrs.value(Artifact),+ "hostcc_argsfile_fingerprint": dynattrs.option(dynattrs.value(Artifact)),+ "original_cmds": dynattrs.list(dynattrs.value(cmd_args)),+ "output_declared_artifacts": dynattrs.list(dynattrs.output()),+ "plan_artifact": dynattrs.artifact_value(),+ "srcs": dynattrs.list(dynattrs.value(Artifact)),+ "toolchain": dynattrs.value(CxxToolchainInfo),+ },+)
@@ -0,0 +1,1168 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:paths.bzl", "paths")+load(+ "@prelude//:resources.bzl",+ "gather_resources",+ "make_resource_info",+)+load(+ "@prelude//android:android_providers.bzl",+ "merge_android_packageable_info",+)+load("@prelude//apple:resource_groups.bzl", "create_resource_graph")+load(+ "@prelude//cxx:compile_types.bzl",+ "UseHeaderUnitsMode",+)+load(+ "@prelude//cxx:cuda.bzl",+ "CudaCompileStyle",+)+load("@prelude//cxx:cxx_flags.bzl", "cxx_attr_flags")+load("@prelude//cxx:cxx_sources.bzl", "get_srcs_with_flags")+load(+ "@prelude//cxx:cxx_toolchain_types.bzl",+ "RuntimeDependencyHandling",+ "ShlibInterfacesMode",+)+load("@prelude//cxx:cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload", "cxx_attrs_use_fbcc_rust_wrapper")+load(+ "@prelude//cxx:link_groups_types.bzl",+ "LinkGroupInfo", # @unused Used as a type+)+# @oss-disable[end= ]: load("@prelude//cxx/meta_only:linker_outputs.bzl", "get_extra_linker_output_flags", "get_extra_linker_outputs")+load("@prelude//graphql:graphql.bzl", "graphql_providers")+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference")+load(+ "@prelude//linking:link_groups.bzl",+ "merge_link_group_lib_info",+)+load(+ "@prelude//linking:link_info.bzl",+ "Archive",+ "ArchiveLinkable",+ "CxxSanitizerRuntimeInfo",+ "LibOutputStyle",+ "LinkArgs",+ "LinkCommandDebugOutputInfo",+ "LinkInfo",+ "LinkInfos",+ "LinkStrategy",+ "LinkedObject",+ "SharedLibLinkable",+ "create_merged_link_info",+ "create_merged_link_info_for_propagation",+ "get_lib_output_style",+ "get_link_args_for_strategy",+ "get_output_styles_for_linkage",+ "subtarget_for_output_style",+ "to_link_strategy",+)+load(+ "@prelude//linking:linkable_graph.bzl",+ "DLOPENABLE_LIBRARY_INFO_MARKER",+ "LinkableGraph",+ "create_linkable_graph",+ "create_linkable_graph_node",+ "create_linkable_node",+)+load(+ "@prelude//linking:linkables.bzl",+ "linkables",+)+load(+ "@prelude//linking:shared_libraries.bzl",+ "SharedLibraries",+ "SharedLibraryInfo",+ "create_shlib_from_ctx",+ "extract_soname_from_shlib",+ "merge_shared_libraries",+ "to_soname",+)+load("@prelude//linking:strip.bzl", "strip_debug_info")+load("@prelude//linking:types.bzl", "Linkage")+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")+load("@prelude//python:manifest.bzl", "create_manifest_for_entries")+load("@prelude//target_stats:target_stats.bzl", "CycleMode", "target_stats_providers_and_subtargets")+load("@prelude//target_stats:target_stats_config.bzl", "TARGET_STATS_ENABLED")+load("@prelude//test:inject_test_run_info.bzl", "inject_test_run_info")+load(+ "@prelude//tests:re_utils.bzl",+ "get_re_executors_from_props",+)+load(+ "@prelude//third-party:build.bzl",+ "create_third_party_build_info",+)+load(+ "@prelude//third-party:providers.bzl",+ "ThirdPartyBuildInfo",+)+load("@prelude//unix:providers.bzl", "UnixEnv", "create_unix_env_info")+load("@prelude//utils:expect.bzl", "expect")+load(+ "@prelude//utils:utils.bzl",+ "filter_and_map_idx",+ "value_or",+)+load(":cxx_context.bzl", "get_cxx_toolchain_info")+load(":cxx_executable.bzl", "cxx_executable")+load(+ ":cxx_library.bzl",+ "CxxLibraryOutput", # @unused Used as a type+ "cxx_library_parameterized",+)+load(+ ":cxx_library_utility.bzl",+ "cxx_attr_dep_metadata",+ "cxx_attr_deps",+ "cxx_attr_exported_deps",+ "cxx_attr_link_style",+ "cxx_attr_linker_flags_all",+ "cxx_attr_preferred_linkage",+ "cxx_attr_use_content_based_paths",+ "cxx_inherited_link_info",+ "cxx_platform_supported",+ "cxx_use_shlib_intfs_mode",+)+load(+ ":cxx_types.bzl",+ "CxxRuleConstructorParams",+ "CxxRuleProviderParams",+ "CxxRuleSubTargetParams",+ "LinkPreference",+ "xcode_data_enabled",+)+load(":gcno.bzl", "GcnoFilesInfo")+load(+ ":groups_types.bzl",+ "Group",+ "MATCH_ALL_LABEL",+ "NO_MATCH_LABEL",+)+load(+ ":headers.bzl",+ "CPrecompiledHeaderInfo",+ "cxx_attr_headers_list",+ "cxx_get_regular_cxx_headers_layout",+)+load(+ ":link.bzl",+ "cxx_link_shared_library",+)+load(+ ":link_groups.bzl",+ "LinkGroupLibSpec",+ "get_link_group_info",+)+load(+ ":link_types.bzl",+ "link_options",+)+load(+ ":linker.bzl",+ "DUMPBIN_SUB_TARGET",+ "IMPORT_LIBRARY_SUB_TARGET",+ "PDB_SUB_TARGET",+ "get_dumpbin_providers",+ "get_link_whole_args",+ "get_pdb_providers",+ "get_shared_library_name",+ "get_shared_library_name_for_param",+ "sandbox_exported_linker_flags",+)+load(+ ":omnibus.bzl",+ "create_linkable_root",+)+load(+ ":preprocessor.bzl",+ "CPreprocessor",+ "CPreprocessorArgs",+ "cxx_exported_preprocessor_info",+ "cxx_inherited_preprocessor_infos",+ "cxx_merge_cpreprocessors",+ "format_system_include_arg",+)+load(+ ":shared_library_interface.bzl",+ "shared_library_interface",+)++#####################################################################+# Operations++def _get_use_header_units_mode(use_header_units: bool | str) -> UseHeaderUnitsMode:+ """Convert the use_header_units attribute to UseHeaderUnitsMode enum."""+ if use_header_units == True:+ return UseHeaderUnitsMode("pcm")+ elif use_header_units == "stub":+ return UseHeaderUnitsMode("stub")+ else:+ return UseHeaderUnitsMode("none")++def _get_shared_link_style_sub_targets_and_providers(+ output_style: LibOutputStyle, ctx: AnalysisContext, output: [CxxLibraryOutput, None]+) -> (dict[str, list[Provider]], list[Provider]):+ if output_style != LibOutputStyle("shared_lib") or output == None:+ return ({}, [])+ sub_targets = {}+ providers = []+ if output.dwp != None:+ sub_targets["dwp"] = [DefaultInfo(default_output = output.dwp)]+ if output.hip_arch_debug_files:+ all_files = [f for files in output.hip_arch_debug_files.values() for f in files]+ sub_targets["hip_debug"] = [+ DefaultInfo(+ default_outputs = all_files,+ sub_targets = {arch: [DefaultInfo(default_outputs = files)] for arch, files in output.hip_arch_debug_files.items()},+ ),+ ]+ if output.pdb != None:+ sub_targets[PDB_SUB_TARGET] = get_pdb_providers(pdb = output.pdb, binary = output.default)+ cxx_toolchain = get_cxx_toolchain_info(ctx)+ if cxx_toolchain.dumpbin_toolchain_path != None:+ sub_targets[DUMPBIN_SUB_TARGET] = get_dumpbin_providers(ctx, output.default, cxx_toolchain.dumpbin_toolchain_path)+ if output.linker_map != None:+ sub_targets["linker-map"] = [DefaultInfo(default_output = output.linker_map.map, other_outputs = [output.linker_map.binary])]+ if output.implib != None:+ sub_targets[IMPORT_LIBRARY_SUB_TARGET] = [DefaultInfo(default_output = output.implib)]+ return (sub_targets, providers)++def cxx_library_impl(ctx: AnalysisContext) -> list[Provider]:+ return cxx_library_generate(ctx, "cxx_library")++def cxx_library_generate(ctx: AnalysisContext, rule_type: str) -> list[Provider]:+ if ctx.attrs.can_be_asset and ctx.attrs.used_by_wrap_script:+ fail("Cannot use `can_be_asset` and `used_by_wrap_script` in the same rule")++ if ctx.attrs._is_building_android_binary:+ sub_target_params, provider_params = _get_params_for_android_binary_cxx_library()+ else:+ sub_target_params = CxxRuleSubTargetParams(xcode_data = xcode_data_enabled())+ provider_params = CxxRuleProviderParams(+ third_party_build = True,+ )++ params = CxxRuleConstructorParams(+ rule_type = rule_type,+ headers_layout = cxx_get_regular_cxx_headers_layout(ctx),+ srcs = get_srcs_with_flags(ctx),+ output_style_sub_targets_and_providers_factory = _get_shared_link_style_sub_targets_and_providers,+ generate_sub_targets = sub_target_params,+ generate_providers = provider_params,+ compiler_flags = ctx.attrs.compiler_flags,+ cxx_flags = cxx_attr_flags(ctx),+ lang_compiler_flags = ctx.attrs.lang_compiler_flags,+ preprocessor_flags = ctx.attrs.preprocessor_flags,+ lang_preprocessor_flags = ctx.attrs.lang_preprocessor_flags,+ use_header_units = _get_use_header_units_mode(ctx.attrs.use_header_units),+ export_header_unit = ctx.attrs.export_header_unit,+ export_header_unit_filter = ctx.attrs.export_header_unit_filter,+ error_handler = get_cxx_toolchain_info(ctx).cxx_error_handler,+ extra_dwp_flags = ctx.attrs.extra_dwp_flags,+ use_fbcc_rust_wrapper = cxx_attrs_use_fbcc_rust_wrapper(ctx.attrs),+ allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs, get_cxx_toolchain_info(ctx).cxx_compiler_info.allow_cache_upload),+ precompiled_header = ctx.attrs.precompiled_header,+ prefix_header = ctx.attrs.prefix_header,+ _cxx_toolchain = ctx.attrs._cxx_toolchain,+ use_content_based_paths = cxx_attr_use_content_based_paths(ctx),+ coverage_instrumentation_compiler_flags = ctx.attrs.coverage_instrumentation_compiler_flags,+ coverage_profile_list = ctx.attrs.coverage_profile_list[DefaultInfo].default_outputs[0] if ctx.attrs.coverage_profile_list else None,+ separate_debug_info = ctx.attrs.separate_debug_info,+ cuda_compile_style = CudaCompileStyle(ctx.attrs.cuda_compile_style),+ # @oss-disable[end= ]: extra_linker_outputs_factory = get_extra_linker_outputs,+ # @oss-disable[end= ]: extra_linker_outputs_flags_factory = get_extra_linker_output_flags,+ supports_stripping = ctx.attrs.supports_stripping,+ expect_eligible_for_dedupe = getattr(ctx.attrs, "expect_eligible_for_dedupe", False),+ )+ output = cxx_library_parameterized(ctx, params)+ return output.providers + graphql_providers(ctx)++def _only_shared_mappings(group: Group) -> bool:+ """+ Return whether this group only has explicit "shared" linkage mappings,+ which indicates a group that re-uses pre-linked libs.+ """+ for mapping in group.mappings:+ if mapping.preferred_linkage != Linkage("shared"):+ return False+ return True++def create_shared_lib_link_group_specs(ctx: AnalysisContext, link_group_definitions: list[Group]) -> list[LinkGroupLibSpec]:+ specs = []+ linker_info = get_cxx_toolchain_info(ctx).linker_info+ for group in link_group_definitions:+ if group.name in (MATCH_ALL_LABEL, NO_MATCH_LABEL):+ continue++ # TODO(agallagher): We should probably add proper handling for "provided"+ # system handling to avoid needing this special case.+ if _only_shared_mappings(group):+ continue+ specs.append(+ LinkGroupLibSpec(+ name = get_shared_library_name(linker_info, group.name, apply_default_prefix = True),+ is_shared_lib = True,+ group = group,+ ),+ )+ return specs++def get_auto_link_group_specs(ctx: AnalysisContext, link_group_info: [LinkGroupInfo, None]) -> [list[LinkGroupLibSpec], None]:+ if link_group_info == None or not ctx.attrs.auto_link_groups:+ return None+ return create_shared_lib_link_group_specs(ctx, link_group_info.groups.values())++def cxx_binary_impl(ctx: AnalysisContext) -> list[Provider]:+ link_strategy = to_link_strategy(cxx_attr_link_style(ctx))+ link_group_info = get_link_group_info(+ ctx,+ filter_and_map_idx(LinkableGraph, cxx_attr_deps(ctx)),+ link_strategy,+ )+ params = CxxRuleConstructorParams(+ rule_type = "cxx_binary",+ generate_sub_targets = CxxRuleSubTargetParams(xcode_data = xcode_data_enabled()),+ executable_name = ctx.attrs.executable_name,+ headers_layout = cxx_get_regular_cxx_headers_layout(ctx),+ srcs = get_srcs_with_flags(ctx),+ link_group_info = link_group_info,+ auto_link_group_specs = get_auto_link_group_specs(ctx, link_group_info),+ prefer_stripped_objects = ctx.attrs.prefer_stripped_objects,+ exe_allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs),+ extra_link_roots = linkables(ctx.attrs.link_group_deps),+ compiler_flags = ctx.attrs.compiler_flags,+ cxx_flags = cxx_attr_flags(ctx),+ lang_compiler_flags = ctx.attrs.lang_compiler_flags,+ preprocessor_flags = ctx.attrs.preprocessor_flags,+ lang_preprocessor_flags = ctx.attrs.lang_preprocessor_flags,+ use_header_units = _get_use_header_units_mode(ctx.attrs.use_header_units),+ runtime_dependency_handling = RuntimeDependencyHandling(ctx.attrs.runtime_dependency_handling)+ if ctx.attrs.runtime_dependency_handling+ else get_cxx_toolchain_info(ctx).runtime_dependency_handling,+ error_handler = get_cxx_toolchain_info(ctx).cxx_error_handler,+ extra_dwp_flags = ctx.attrs.extra_dwp_flags,+ use_fbcc_rust_wrapper = cxx_attrs_use_fbcc_rust_wrapper(ctx.attrs),+ allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs, get_cxx_toolchain_info(ctx).cxx_compiler_info.allow_cache_upload),+ precompiled_header = ctx.attrs.precompiled_header,+ prefix_header = ctx.attrs.prefix_header,+ _cxx_toolchain = ctx.attrs._cxx_toolchain,+ use_content_based_paths = cxx_attr_use_content_based_paths(ctx),+ coverage_instrumentation_compiler_flags = ctx.attrs.coverage_instrumentation_compiler_flags,+ coverage_profile_list = ctx.attrs.coverage_profile_list[DefaultInfo].default_outputs[0] if ctx.attrs.coverage_profile_list else None,+ separate_debug_info = ctx.attrs.separate_debug_info,+ cuda_compile_style = CudaCompileStyle(ctx.attrs.cuda_compile_style),+ link_preference = LinkPreference(ctx.attrs.link_preference),+ # @oss-disable[end= ]: extra_linker_outputs_factory = get_extra_linker_outputs,+ # @oss-disable[end= ]: extra_linker_outputs_flags_factory = get_extra_linker_output_flags,+ )+ output = cxx_executable(ctx, params)++ extra_providers = []+ if output.link_command_debug_output:+ extra_providers.append(LinkCommandDebugOutputInfo(debug_outputs = [output.link_command_debug_output]))+ if output.sanitizer_runtime_files:+ extra_providers.append(CxxSanitizerRuntimeInfo(runtime_files = output.sanitizer_runtime_files))+ if output.validation_specs:+ extra_providers.append(ValidationInfo(validations = output.validation_specs))+ if output.xplugins_debug_artifacts_info:+ extra_providers.append(output.xplugins_debug_artifacts_info)++ if get_cxx_toolchain_info(ctx).gcno_files and output.gcno_files:+ extra_providers.append(GcnoFilesInfo(gcno_files = output.gcno_files))++ # Unix env provider.+ extra_providers.append(+ create_unix_env_info(+ actions = ctx.actions,+ env = UnixEnv(+ label = ctx.label,+ binaries = [+ create_manifest_for_entries(+ ctx = ctx,+ name = "unix_env",+ entries = [+ (ctx.label.name, output.binary, ""),+ ],+ ),+ ],+ ),+ # TODO(agallagher): We only want to traverse deps when dynamically+ # linking.+ # deps = ctx.attrs.deps,+ ),+ )++ # When an executable is the output of a build, also materialize all the+ # unpacked external debuginfo that goes with it. This makes `buck2 build+ # :main` equivalent to `buck2 build :main :main[debuginfo]`.+ #+ # This is wasted work if we are building an executable together with its dwp+ # subtarget (`buck2 build :main :main[dwp]`) in which case a large number of+ # unpacked debuginfo files can end up being materialized redundantly. LLDB+ # will ignore them and obtain debuginfo via the single packed debuginfo file+ # instead.+ #+ # But materializing unpacked debuginfo is usually the right tradeoff+ # because it means the output of `buck2 build :main` is always immediately+ # usable in a debugger. Toolchains whose debugging workflow materializes+ # debuginfo on demand instead (via the `[debuginfo]` or `[dwp]`+ # sub-targets) can opt out with `materialize_external_debug_info = False`.+ #+ # External debuginfo is *not* materialized when an executable is depended on+ # by another rule, such as by $(exe ...) or exec_dep.+ other_outputs = output.runtime_files + (output.external_debug_info_artifacts if get_cxx_toolchain_info(ctx).materialize_external_debug_info else [])++ return (+ filter(+ None,+ [+ DefaultInfo(+ default_output = output.binary,+ other_outputs = other_outputs,+ sub_targets = output.sub_targets,+ ),+ RunInfo(args = cmd_args(output.binary, hidden = output.runtime_files)),+ output.compilation_db,+ output.xcode_data,+ output.dist_info,+ ],+ )+ + extra_providers+ )++def _prebuilt_item(_ctx: AnalysisContext, item: [typing.Any, None]) -> [typing.Any, None]:+ """+ Return the item if it's set.+ """+ return item++def _prebuilt_linkage(ctx: AnalysisContext) -> Linkage:+ """+ Construct the preferred linkage to use for the given prebuilt library.+ """+ if ctx.attrs.header_only:+ return Linkage("any")+ if ctx.attrs.force_static:+ return Linkage("static")+ preferred_linkage = cxx_attr_preferred_linkage(ctx)+ if preferred_linkage != Linkage("any"):+ return preferred_linkage+ if ctx.attrs.provided:+ return Linkage("shared")+ return Linkage("any")++def _create_prebuilt_library_outputs(+ ctx: AnalysisContext,+ static_lib,+ static_pic_lib,+ shared_lib,+ static_lib_stripped,+ static_pic_lib_stripped,+ soname,+ linker_type,+ linker_flags,+ inherited_exported_link,+ header_dirs,+ propagated_preprocessor,+ propagate_shared_libs: bool,+):+ """+ Create outputs for all output styles of a prebuilt library.++ Returns a struct with:+ - outputs: dict of output_style -> artifact+ - libraries: dict of output_style -> LinkInfos+ - solibs: list of shared libraries+ - sub_targets: dict of sub-target names -> providers+ - generated_shared_lib: whether the shared lib was created via a link rule++ Args:+ propagate_shared_libs: Whether to propagate shared libraries via SharedLibraryInfo.+ Should be True only if the library's preferred linkage allows shared linking.+ """+ linker_info = get_cxx_toolchain_info(ctx).linker_info++ # Gather link infos, outputs, and shared libs for all output styles.+ outputs = {}+ libraries = {}+ solibs = []+ sub_targets = {}+ generated_shared_lib = False # whether the shared lib is created via a link rule++ # Generate outputs for ALL output styles (not just those for a specific preferred_linkage)+ for output_style in [LibOutputStyle("archive"), LibOutputStyle("pic_archive"), LibOutputStyle("shared_lib")]:+ out = None+ linkable = None+ linkable_stripped = None++ # If we have sources to compile, generate the necessary libraries and+ # add them to the exported link info.+ if not ctx.attrs.header_only:++ def archive_linkable(lib):+ return ArchiveLinkable(+ archive = Archive(artifact = lib),+ linker_type = linker_type,+ link_whole = ctx.attrs.link_whole,+ supports_lto = ctx.attrs.supports_lto,+ )++ if output_style == LibOutputStyle("archive"):+ if static_lib:+ out = static_lib+ linkable = archive_linkable(static_lib)+ linkable_stripped = archive_linkable(static_lib_stripped) if static_lib_stripped else None+ elif output_style == LibOutputStyle("pic_archive"):+ lib = static_pic_lib or static_lib+ if lib:+ out = lib+ linkable = archive_linkable(lib)+ linkable_stripped = (+ archive_linkable(static_pic_lib_stripped or static_lib_stripped) if (static_pic_lib_stripped or static_lib_stripped) else None+ )+ else: # shared+ # If no shared library was provided, link one from the static libraries.+ if shared_lib != None:+ shared_lib = LinkedObject(output = shared_lib, unstripped_output = shared_lib)+ else:+ lib = static_pic_lib or static_lib+ if lib:+ shlink_args = []++ # TODO(T110378143): Support post link flags properly.+ shlink_args.extend(linker_flags.exported_flags)+ shlink_args.extend(linker_flags.flags)+ shlink_args.extend(get_link_whole_args(linker_type, [lib]))++ # TODO(T110378118): As per v1, we always link against "shared"+ # dependencies when building a shaerd library.+ shared_link_args = get_link_args_for_strategy(+ ctx.actions,+ ctx.label,+ linker_info,+ inherited_exported_link,+ LinkStrategy("shared"),+ prefer_stripped = False,+ transformation_spec_context = None,+ )+ link_result = cxx_link_shared_library(+ ctx = ctx,+ output = soname.ensure_str(),+ name = soname.ensure_str(),+ opts = link_options(+ links = [+ LinkArgs(flags = shlink_args),+ shared_link_args,+ ],+ link_execution_preference = LinkExecutionPreference("any"),+ ),+ )+ shared_lib = link_result.linked_object+ generated_shared_lib = True++ if shared_lib:+ out = shared_lib.output++ shared_lib_for_linking = shared_lib.output++ # Generate a shared library interface if the rule supports it.+ # TODO: We should not permit both modes, but to keep builds green we have to for now.+ if ctx.attrs.supports_shared_library_interface and (+ cxx_use_shlib_intfs_mode(ctx, ShlibInterfacesMode("defined_only"))+ or cxx_use_shlib_intfs_mode(ctx, ShlibInterfacesMode("stub_from_library"))+ ):+ shared_lib_for_linking = shared_library_interface(+ ctx = ctx,+ shared_lib = shared_lib.output,+ )+ if ctx.attrs._target_os_type[OsLookup].os == Os("windows"):+ shared_lib_for_linking = ctx.attrs.import_lib++ linkable = None+ if shared_lib_for_linking != None:+ linkable = SharedLibLinkable(+ lib = shared_lib_for_linking,+ # Some prebuilt shared libs don't set a SONAME (e.g.+ # IntelComposerXE), so we can't link them via just the shared+ # lib (otherwise, we may embed build-time paths in `DT_NEEDED`+ # tags).+ link_without_soname = ctx.attrs.link_without_soname,+ )++ # Provided means something external to the build will provide+ # the libraries, so we don't need to propagate anything.+ if not ctx.attrs.provided and propagate_shared_libs:+ solibs.append(+ create_shlib_from_ctx(+ ctx = ctx,+ lib = shared_lib,+ soname = soname,+ ),+ )++ # Provide a sub-target that always provides the shared lib+ # using the soname.+ if soname and soname.is_str and shared_lib.output.basename != paths.basename(soname.ensure_str()):+ soname_lib = ctx.actions.copy_file(soname.ensure_str(), shared_lib.output, has_content_based_path = False)+ else:+ soname_lib = shared_lib.output+ sub_targets["soname-lib"] = [DefaultInfo(default_output = soname_lib)]++ if shared_lib.pdb:+ sub_targets[PDB_SUB_TARGET] = get_pdb_providers(pdb = shared_lib.pdb, binary = shared_lib.output)+ dumpbin_toolchain_path = get_cxx_toolchain_info(ctx).dumpbin_toolchain_path+ if dumpbin_toolchain_path != None:+ sub_targets[DUMPBIN_SUB_TARGET] = get_dumpbin_providers(ctx, shared_lib.output, dumpbin_toolchain_path)+ if shared_lib.dwp != None:+ sub_targets["dwp"] = [DefaultInfo(default_output = shared_lib.dwp)]+ if shared_lib.hip_arch_debug_files:+ all_files = [f for files in shared_lib.hip_arch_debug_files.values() for f in files]+ sub_targets["hip_debug"] = [+ DefaultInfo(+ default_outputs = all_files,+ sub_targets = {arch: [DefaultInfo(default_outputs = files)] for arch, files in shared_lib.hip_arch_debug_files.items()},+ ),+ ]++ # TODO(cjhopman): is it okay that we sometimes don't have a linkable?+ outputs[output_style] = out+ dep_metadata = cxx_attr_dep_metadata(ctx)+ exported_flags, exported_post_flags = sandbox_exported_linker_flags(+ linker_info,+ linker_flags.exported_flags,+ linker_flags.exported_post_flags,+ )+ libraries[output_style] = LinkInfos(+ default = LinkInfo(+ name = ctx.attrs.name,+ pre_flags = exported_flags,+ post_flags = exported_post_flags,+ linkables = [linkable] if linkable else [],+ metadata = dep_metadata,+ ),+ stripped = None+ if linkable_stripped == None+ else LinkInfo(+ name = ctx.attrs.name,+ pre_flags = exported_flags,+ post_flags = exported_post_flags,+ linkables = [linkable_stripped],+ metadata = dep_metadata,+ ),+ )++ sub_targets[subtarget_for_output_style(output_style)] = [+ DefaultInfo(+ default_output = outputs[output_style],+ )+ ]++ # Third-party provider.+ shared_libs_for_third_party = SharedLibraries(libraries = solibs)+ if ctx.attrs.third_party_build != None:+ third_party_build_info = create_third_party_build_info(+ ctx = ctx,+ shared_libs = shared_libs_for_third_party.libraries if generated_shared_lib else [],+ children = [ctx.attrs.third_party_build[ThirdPartyBuildInfo]],+ deps = ctx.attrs.deps + cxx_attr_exported_deps(ctx),+ )+ else:+ third_party_build_info = create_third_party_build_info(+ ctx = ctx,+ paths = [] if header_dirs == None else [(d.short_path, d) for d in header_dirs],+ cxx_headers = [propagated_preprocessor],+ shared_libs = shared_libs_for_third_party.libraries,+ cxx_header_dirs = ["include"] + ([] if header_dirs == None else [d.short_path for d in header_dirs]),+ deps = ctx.attrs.deps + cxx_attr_exported_deps(ctx),+ )++ return struct(+ outputs = outputs,+ libraries = libraries,+ solibs = solibs,+ sub_targets = sub_targets,+ generated_shared_lib = generated_shared_lib,+ third_party_build_info = third_party_build_info,+ )++def _create_prebuilt_library_providers(+ ctx: AnalysisContext,+ input_providers: list[Provider],+ preferred_linkage: Linkage,+ library_outputs,+ static_lib,+ static_pic_lib,+ soname,+ linker_type,+ linker_flags,+ inherited_exported_link,+ inherited_link,+ first_order_deps,+ exported_first_order_deps,+):+ """+ Create and return providers for a prebuilt library with a specific preferred linkage.++ Takes the providers list constructed so far and library_outputs from _create_prebuilt_library_outputs,+ and appends link-related providers.+ Returns a tuple of (providers, sub_targets, default_output).+ """++ providers = list(input_providers)++ # Extract data from library_outputs for the output styles relevant to this preferred_linkage+ outputs = library_outputs.outputs+ libraries = {}+ for output_style in get_output_styles_for_linkage(preferred_linkage):+ libraries[output_style] = library_outputs.libraries[output_style]++ solibs = library_outputs.solibs+ sub_targets = dict(library_outputs.sub_targets)++ cxx_toolchain = get_cxx_toolchain_info(ctx)+ pic_behavior = cxx_toolchain.pic_behavior++ # Propagate link info provider.+ providers.append(+ create_merged_link_info(+ ctx,+ pic_behavior,+ # Add link info for each link style,+ libraries,+ preferred_linkage = preferred_linkage,+ # Export link info from non-exported deps (when necessary).+ deps = inherited_link,+ # Export link info from out (exported) deps.+ exported_deps = inherited_exported_link,+ )+ )++ # Propagate shared libraries up the tree.+ shared_libs = SharedLibraries(libraries = solibs)+ providers.append(+ merge_shared_libraries(+ ctx.actions,+ shared_libs,+ filter_and_map_idx(SharedLibraryInfo, exported_first_order_deps),+ )+ )++ providers.append(+ create_unix_env_info(+ actions = ctx.actions,+ env = UnixEnv(+ label = ctx.label,+ native_libs = [shared_libs],+ ),+ deps = ctx.attrs.deps + ctx.attrs.exported_deps,+ ),+ )++ # Third-party provider (already created in library_outputs)+ third_party_build_info = library_outputs.third_party_build_info+ providers.append(third_party_build_info)+ sub_targets["third-party-build"] = [+ DefaultInfo(+ default_output = third_party_build_info.build.root.artifact,+ sub_targets = dict(+ manifest = [DefaultInfo(default_output = third_party_build_info.build.manifest)],+ ),+ ),+ ]++ # Create the default output for the library rule given it's link style and preferred linkage+ link_strategy = to_link_strategy(cxx_toolchain.linker_info.link_style)+ actual_output_style = get_lib_output_style(link_strategy, preferred_linkage, pic_behavior)+ default_output = outputs[actual_output_style]++ # Omnibus root provider.+ if LibOutputStyle("pic_archive") in libraries and (static_pic_lib or static_lib) and not ctx.attrs.header_only and soname.is_str:+ # TODO(cjhopman): This doesn't support thin archives+ linkable_root = create_linkable_root(+ label = ctx.label,+ name = soname.ensure_str(),+ link_infos = LinkInfos(+ default = LinkInfo(+ name = soname.ensure_str(),+ pre_flags = (linker_flags.exported_flags + linker_flags.flags),+ linkables = [+ ArchiveLinkable(+ archive = Archive(+ artifact = static_pic_lib or static_lib,+ ),+ linker_type = linker_type,+ link_whole = True,+ )+ ],+ post_flags = linker_flags.exported_post_flags,+ metadata = cxx_attr_dep_metadata(ctx),+ )+ ),+ deps = exported_first_order_deps,+ )+ providers.append(linkable_root)++ # Mark libraries that support `dlopen`.+ if ctx.attrs.supports_python_dlopen:+ providers.append(DLOPENABLE_LIBRARY_INFO_MARKER)++ linkable_graph = create_linkable_graph(+ ctx,+ node = create_linkable_graph_node(+ ctx,+ linkable_node = create_linkable_node(+ ctx = ctx,+ default_soname = soname.as_str(),+ preferred_linkage = preferred_linkage,+ default_link_strategy = to_link_strategy(cxx_toolchain.linker_info.link_style),+ exported_deps = exported_first_order_deps,+ # If we don't have link input for this link style, we pass in `None` so+ # that omnibus knows to avoid it.+ link_infos = libraries,+ shared_libs = shared_libs,+ linker_flags = linker_flags,+ can_be_asset = getattr(ctx.attrs, "can_be_asset", False) or False,+ stub = getattr(ctx.attrs, "stub", False),+ ),+ excluded = {ctx.label: None} if not value_or(ctx.attrs.supports_merged_linking, True) else {},+ ),+ deps = exported_first_order_deps,+ )++ providers.append(linkable_graph)++ providers.append(+ merge_link_group_lib_info(+ deps = first_order_deps + exported_first_order_deps,+ ),+ )++ # TODO(T107163344) this shouldn't be in prebuilt_cxx_library itself, use overlays to remove it.+ providers.append(merge_android_packageable_info(ctx.label, ctx.actions, first_order_deps + exported_first_order_deps))++ apple_resource_graph = create_resource_graph(+ ctx = ctx,+ labels = ctx.attrs.labels,+ deps = first_order_deps,+ exported_deps = exported_first_order_deps,+ )+ providers += [apple_resource_graph]++ return (providers, sub_targets, default_output)++def prebuilt_cxx_library_impl(ctx: AnalysisContext) -> list[Provider]:+ # Versioned params should be intercepted and converted away via the stub.+ expect(not ctx.attrs.versioned_exported_lang_preprocessor_flags)+ expect(not ctx.attrs.versioned_exported_preprocessor_flags)+ expect(not ctx.attrs.versioned_header_dirs)+ expect(not ctx.attrs.versioned_shared_lib)+ expect(not ctx.attrs.versioned_static_lib)+ expect(not ctx.attrs.versioned_static_pic_lib)++ if not cxx_platform_supported(ctx):+ return [DefaultInfo(default_output = None)]++ providers = []++ toolchain_info = get_cxx_toolchain_info(ctx)+ linker_info = toolchain_info.linker_info+ linker_type = linker_info.type++ # Parse library parameters.+ static_lib = _prebuilt_item(+ ctx,+ ctx.attrs.static_lib,+ )+ static_pic_lib = _prebuilt_item(+ ctx,+ ctx.attrs.static_pic_lib,+ )+ shared_lib = _prebuilt_item(+ ctx,+ ctx.attrs.shared_lib,+ )+ header_dirs = _prebuilt_item(+ ctx,+ ctx.attrs.header_dirs,+ )+ preferred_linkage = _prebuilt_linkage(ctx)++ # Prepare the stripped static lib.+ static_lib_stripped = None+ if not ctx.attrs.prestripped and static_lib != None:+ static_lib_stripped = strip_debug_info(+ ctx.actions, static_lib.short_path, static_lib, toolchain_info, has_content_based_path = cxx_attr_use_content_based_paths(ctx)+ )++ # Prepare the stripped static PIC lib. If the static PIC lib is the same+ # artifact as the static lib, then just re-use the stripped static lib.+ static_pic_lib_stripped = None+ if not ctx.attrs.prestripped:+ if static_lib == static_pic_lib:+ static_pic_lib_stripped = static_lib_stripped+ elif static_pic_lib != None:+ static_pic_lib_stripped = strip_debug_info(+ ctx.actions, static_pic_lib.short_path, static_pic_lib, toolchain_info, has_content_based_path = cxx_attr_use_content_based_paths(ctx)+ )++ if ctx.attrs.soname != None:+ soname = get_shared_library_name_for_param(linker_info, ctx.attrs.soname)+ elif shared_lib != None and ctx.attrs.extract_soname:+ soname = extract_soname_from_shlib(+ actions = ctx.actions,+ name = "__soname__.txt",+ shared_lib = shared_lib,+ )+ else:+ soname = get_shared_library_name(linker_info, ctx.label.name, apply_default_prefix = True)+ soname = to_soname(soname)++ # Use ctx.attrs.deps instead of cxx_attr_deps, since prebuilt rules don't have platform_deps.+ first_order_deps = ctx.attrs.deps+ exported_first_order_deps = cxx_attr_exported_deps(ctx)++ # Exported preprocessor info.+ inherited_pp_infos = cxx_inherited_preprocessor_infos(exported_first_order_deps)+ generic_exported_pre = cxx_exported_preprocessor_info(ctx, cxx_get_regular_cxx_headers_layout(ctx), [])+ args = []+ compiler_type = get_cxx_toolchain_info(ctx).cxx_compiler_info.compiler_type+ if header_dirs != None:+ for x in header_dirs:+ args.append(format_system_include_arg(cmd_args(x), compiler_type))+ exported_items = [generic_exported_pre]+ if args:+ exported_items.append(CPreprocessor(args = CPreprocessorArgs(args = args, precompile_args = args)))+ propagated_preprocessor = cxx_merge_cpreprocessors(+ ctx.actions,+ exported_items,+ inherited_pp_infos,+ )+ providers.append(propagated_preprocessor)++ inherited_link = cxx_inherited_link_info(first_order_deps)+ inherited_exported_link = cxx_inherited_link_info(exported_first_order_deps)++ linker_flags = cxx_attr_linker_flags_all(ctx)++ # Generate outputs for all output styles once+ # Only propagate shared libs if the preferred linkage allows shared linking+ propagate_shared_libs = LibOutputStyle("shared_lib") in get_output_styles_for_linkage(preferred_linkage)+ library_outputs = _create_prebuilt_library_outputs(+ ctx,+ static_lib,+ static_pic_lib,+ shared_lib,+ static_lib_stripped,+ static_pic_lib_stripped,+ soname,+ linker_type,+ linker_flags,+ inherited_exported_link,+ header_dirs,+ propagated_preprocessor,+ propagate_shared_libs,+ )++ # Create link-related providers.+ linkage_providers = {}+ for linkage in Linkage:+ linkage_providers[linkage] = _create_prebuilt_library_providers(+ ctx,+ providers,+ linkage,+ library_outputs,+ static_lib,+ static_pic_lib,+ soname,+ linker_type,+ linker_flags,+ inherited_exported_link,+ inherited_link,+ first_order_deps,+ exported_first_order_deps,+ )++ providers, sub_targets, output = linkage_providers[preferred_linkage]+ for linkage in (Linkage("static"), Linkage("shared")):+ lproviders, lsub_targets, loutput = linkage_providers[linkage]+ lproviders_with_default = list(lproviders)+ lproviders_with_default.append(+ DefaultInfo(+ default_output = loutput,+ sub_targets = lsub_targets,+ )+ )+ sub_targets["prefer-{}".format(linkage.value)] = lproviders_with_default+ providers.append(+ DefaultInfo(+ default_output = output,+ sub_targets = sub_targets,+ )+ )++ providers.append(+ make_resource_info(+ gather_resources(+ label = ctx.label,+ deps = first_order_deps + exported_first_order_deps,+ ),+ ),+ )++ return providers++def cxx_precompiled_header_impl(ctx: AnalysisContext) -> list[Provider]:+ if ctx.attrs.compile_pch_file:+ ctx.attrs.srcs.append(ctx.attrs.src)+ return cxx_library_generate(ctx, "cxx_precompiled_header")++ inherited_pp_infos = cxx_inherited_preprocessor_infos(ctx.attrs.deps)+ inherited_link = cxx_inherited_link_info(ctx.attrs.deps)+ return [+ DefaultInfo(default_output = ctx.attrs.src),+ cxx_merge_cpreprocessors(ctx.actions, [], inherited_pp_infos),+ create_merged_link_info_for_propagation(ctx, inherited_link),+ CPrecompiledHeaderInfo(header = ctx.attrs.src, compiled = False),+ ]++def cxx_test_impl(ctx: AnalysisContext) -> list[Provider]:+ link_strategy = to_link_strategy(cxx_attr_link_style(ctx))+ link_group_info = get_link_group_info(+ ctx,+ filter_and_map_idx(LinkableGraph, cxx_attr_deps(ctx)),+ link_strategy,+ )++ # TODO(T110378115): have the runinfo contain the correct test running args+ headers_layout = cxx_get_regular_cxx_headers_layout(ctx)+ srcs = get_srcs_with_flags(ctx)+ params = CxxRuleConstructorParams(+ rule_type = "cxx_test",+ generate_sub_targets = CxxRuleSubTargetParams(xcode_data = xcode_data_enabled()),+ headers_layout = headers_layout,+ srcs = srcs,+ link_group_info = link_group_info,+ auto_link_group_specs = get_auto_link_group_specs(ctx, link_group_info),+ prefer_stripped_objects = ctx.attrs.prefer_stripped_objects,+ extra_link_roots = linkables(ctx.attrs.link_group_deps),+ compiler_flags = ctx.attrs.compiler_flags,+ cxx_flags = cxx_attr_flags(ctx),+ lang_compiler_flags = ctx.attrs.lang_compiler_flags,+ preprocessor_flags = ctx.attrs.preprocessor_flags,+ lang_preprocessor_flags = ctx.attrs.lang_preprocessor_flags,+ use_header_units = _get_use_header_units_mode(ctx.attrs.use_header_units),+ runtime_dependency_handling = RuntimeDependencyHandling(ctx.attrs.runtime_dependency_handling)+ if ctx.attrs.runtime_dependency_handling+ else get_cxx_toolchain_info(ctx).runtime_dependency_handling,+ error_handler = get_cxx_toolchain_info(ctx).cxx_error_handler,+ extra_dwp_flags = ctx.attrs.extra_dwp_flags,+ use_fbcc_rust_wrapper = cxx_attrs_use_fbcc_rust_wrapper(ctx.attrs),+ allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs, get_cxx_toolchain_info(ctx).cxx_compiler_info.allow_cache_upload),+ precompiled_header = ctx.attrs.precompiled_header,+ prefix_header = ctx.attrs.prefix_header,+ _cxx_toolchain = ctx.attrs._cxx_toolchain,+ use_content_based_paths = cxx_attr_use_content_based_paths(ctx),+ coverage_instrumentation_compiler_flags = ctx.attrs.coverage_instrumentation_compiler_flags,+ coverage_profile_list = ctx.attrs.coverage_profile_list[DefaultInfo].default_outputs[0] if ctx.attrs.coverage_profile_list else None,+ separate_debug_info = ctx.attrs.separate_debug_info,+ cuda_compile_style = CudaCompileStyle(ctx.attrs.cuda_compile_style),+ link_preference = LinkPreference(ctx.attrs.link_preference),+ )+ output = cxx_executable(ctx, params, is_cxx_test = True)++ target_stats_providers = []+ if TARGET_STATS_ENABLED:+ target_stats_tools = get_cxx_toolchain_info(ctx).target_stats_tools+ if target_stats_tools != None:+ target_stats_srcs = {src.file.short_path: src.file for src in srcs}+ target_stats_srcs.update({+ # Named headers use the dict key; list headers retain their+ # package-relative path. This matches the collector and avoids+ # collisions between headers with the same basename.+ (header.name if header.named else header.artifact.short_path): header.artifact+ for header in cxx_attr_headers_list(ctx, ctx.attrs.headers, headers_layout)+ })+ target_stats_providers, target_stats_subtargets = target_stats_providers_and_subtargets(+ ctx,+ tools = target_stats_tools,+ srcs = target_stats_srcs,+ deps = cxx_attr_deps(ctx),+ cycle_mode = CycleMode("file"),+ module_name = ctx.label.name,+ )+ output.sub_targets.update(target_stats_subtargets)++ command = [cmd_args(output.binary, hidden = output.runtime_files)] + ctx.attrs.args++ # Setup RE executors based on the `remote_execution` param.+ re_executors = get_re_executors_from_props(ctx)++ providers = [+ DefaultInfo(+ default_output = output.binary,+ other_outputs = output.runtime_files + (output.external_debug_info_artifacts if get_cxx_toolchain_info(ctx).materialize_external_debug_info else []),+ sub_targets = output.sub_targets,+ ),+ output.compilation_db,+ output.dist_info,+ ]+ if output.xcode_data:+ providers.append(output.xcode_data)+ providers.extend(+ inject_test_run_info(+ ctx,+ ExternalRunnerTestInfo(+ type = "gtest",+ command = command,+ env = ctx.attrs.env,+ labels = ctx.attrs.labels,+ contacts = ctx.attrs.contacts,+ default_executor = re_executors.default_executor,+ executor_overrides = re_executors.executor_overrides,+ # We implicitly make this test via the project root, instead of+ # the cell root (e.g. fbcode root). `network_access` is carried on+ # the executor config (see `get_re_executors_from_props`).+ run_from_project_root = ("buck2_run_from_project_root" in (ctx.attrs.labels or []) or re_executors.run_from_project_root),+ use_project_relative_paths = re_executors.use_project_relative_paths,+ supports_test_execution_caching = ctx.attrs.supports_test_execution_caching,+ ),+ )+ )+ if output.validation_specs:+ providers.append(ValidationInfo(validations = output.validation_specs))++ if get_cxx_toolchain_info(ctx).gcno_files and output.gcno_files:+ providers.append(GcnoFilesInfo(gcno_files = output.gcno_files))++ providers.extend(target_stats_providers)++ return providers++def _get_params_for_android_binary_cxx_library() -> (CxxRuleSubTargetParams, CxxRuleProviderParams):+ sub_target_params = CxxRuleSubTargetParams(+ argsfiles = False,+ compilation_database = False,+ headers = False,+ link_group_map = False,+ xcode_data = False,+ clang_traces = False,+ objects = False,+ bitcode_bundle = False,+ )+ provider_params = CxxRuleProviderParams(+ compilation_database = False,+ omnibus_root = False,+ preprocessor_for_tests = False,+ cxx_resources_as_apple_resources = False,+ )++ return sub_target_params, provider_params
@@ -0,0 +1,96 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++_PLATFORM_TARGET_TRIPLE_MAP = {+ "appletvos": "{architecture}-apple-tvos{version}",+ "appletvsimulator": "{architecture}-apple-tvos{version}-simulator",+ "iphoneos": "{architecture}-apple-ios{version}",+ "iphonesimulator": "{architecture}-apple-ios{version}-simulator",+ "maccatalyst": "{architecture}-apple-ios{version}-macabi",+ "macosx": "{architecture}-apple-macosx{version}",+ "visionos": "{architecture}-apple-xros{version}",+ "visionsimulator": "{architecture}-apple-xros{version}-simulator",+ "watchos": "{architecture}-apple-watchos{version}",+ "watchsimulator": "{architecture}-apple-watchos{version}-simulator",+}++# - Metal arch is always `air64`, regardless of target arch+# - watchOS does not support targeting Metal+_METAL_PLATFORM_TARGET_TRIPLE_MAP = {+ "appletvos": "air64-apple-tvos{version}",+ "appletvsimulator": "air64-apple-tvos{version}-simulator",+ "iphoneos": "air64-apple-ios{version}",+ "iphonesimulator": "air64-apple-ios{version}-simulator",+ "maccatalyst": "air64-apple-ios{version}-macabi",+ "macosx": "air64-apple-macosx{version}",+ "visionos": "air64-apple-xros{version}",+ "visionsimulator": "air64-apple-xros{version}-simulator",+}++def is_valid_apple_platform_name(platform_name: str | None) -> bool:+ platform_components = (platform_name or "").split("-")+ return platform_components[0] in _PLATFORM_TARGET_TRIPLE_MAP and len(platform_components) == 2++def apple_format_target_triple(platform_name: str, version: str) -> str:+ platform_components = platform_name.split("-")+ if platform_components[0] not in _PLATFORM_TARGET_TRIPLE_MAP:+ fail("missing target triple for {} ({})".format(platform_components[0], platform_name))++ triple_format_str = _PLATFORM_TARGET_TRIPLE_MAP[platform_components[0]]+ return triple_format_str.format(architecture = platform_components[1], version = version)++def apple_format_metal_target_triple(platform: str, version: str) -> str:+ platform_name_and_arch_components = platform.split("-")+ platform_name = platform_name_and_arch_components[0]+ if platform_name not in _METAL_PLATFORM_TARGET_TRIPLE_MAP:+ fail("Missing Metal target triple for {} ({})".format(platform_name, platform))++ metal_triple_format_str = _METAL_PLATFORM_TARGET_TRIPLE_MAP[platform_name]+ return metal_triple_format_str.format(version = version)++def apple_target_triple_flags(target_triple: str | None) -> list[str]:+ return (+ [+ "-target",+ target_triple,+ ]+ if target_triple+ else []+ )++def apple_extra_darwin_linker_flags(target_triple: str | None) -> list[str]:+ """+ Returns a list of linker flags that should be used for all links with a Darwin toolchain.+ """++ # Darwin requires a target triple specified to+ # control the deployment target being linked for.+ extra_linker_flags = apple_target_triple_flags(target_triple)++ # On Apple platforms, DWARF data is contained in the object files+ # and executables contains paths to the object files (N_OSO stab).+ #+ # By default, ld64 will use absolute file paths in N_OSO entries+ # which machine-dependent executables. Such executables would not+ # be debuggable on any host apart from the host which performed+ # the linking. Instead, we want produce machine-independent+ # hermetic executables, so we need to relativize those paths.+ #+ # This is accomplished by passing the `oso-prefix` flag to ld64,+ # which will strip the provided prefix from the N_OSO paths.+ #+ # The flag accepts a special value, `.`, which means it will+ # use the current workding directory. This will make all paths+ # relative to the parent of `buck-out`.+ #+ # Because all actions in Buck2 are run from the project root+ # and `buck-out` is always inside the project root, we can+ # safely pass `.` as the `-oso_prefix` without having to+ # write a wrapper script to compute it dynamically.+ extra_linker_flags.append("-Wl,-oso_prefix,.")+ return extra_linker_flags
@@ -0,0 +1,104 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# BOLT (Binary Optimization Layout Tool) is a post link profile guided optimizer used for+# performance-critical services in fbcode: https://www.internalfb.com/intern/wiki/HHVM-BOLT/++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactTSet",+ "project_artifacts",+)+load(":cxx_context.bzl", "get_cxx_toolchain_info")++PRE_BOLT_SUFFIX = "-wrapper"++CxxBoltOutput = record(+ output = field(Artifact),+ dwo_output = field(Artifact | None),+)++def cxx_use_bolt(ctx: AnalysisContext) -> bool:+ cxx_toolchain_info = get_cxx_toolchain_info(ctx)+ return cxx_toolchain_info.bolt_enabled and ctx.attrs.bolt_profile != None++def bolt(+ ctx: AnalysisContext,+ prebolt_output: Artifact,+ external_debug_info: ArtifactTSet,+ identifier: [str, None],+ generate_dwp: bool,+ allow_cache_upload: bool = False,+) -> CxxBoltOutput:+ output_name = prebolt_output.short_path.removesuffix(PRE_BOLT_SUFFIX)+ postbolt_output = ctx.actions.declare_output(output_name, has_content_based_path = False)+ dwo_output = None+ cxx_toolchain_info = get_cxx_toolchain_info(ctx)+ bolt_tool = cxx_toolchain_info.binary_utilities_info.bolt++ if not bolt_tool or not cxx_use_bolt(ctx):+ fail("Cannot use bolt if bolt tool is not available or bolt profile is not available")++ materialized_external_debug_info = project_artifacts(ctx.actions, external_debug_info)++ # bolt command format:+ # {llvm_bolt} {input_bin} -o $OUT -data={fdata} {args}+ args = cmd_args(+ bolt_tool,+ prebolt_output,+ "-o",+ postbolt_output.as_output(),+ cmd_args(ctx.attrs.bolt_profile, format = "-data={}"),+ ctx.attrs.bolt_flags,+ hidden = materialized_external_debug_info,+ )++ if generate_dwp:+ dwo_output = ctx.actions.declare_output(output_name + ".dwo.d", dir = True, has_content_based_path = False)+ args.add(cmd_args(dwo_output.as_output(), format = "--dwarf-output-path={}"))+ args = cmd_args(+ "/bin/sh",+ "-c",+ cmd_args(dwo_output.as_output(), format = 'mkdir -p {}; "$@"'),+ '""',+ args,+ )++ strip_stapsdt = hasattr(ctx.attrs, "strip_stapsdt") and ctx.attrs.strip_stapsdt+ ctx.actions.run(+ args,+ category = "bolt",+ identifier = identifier,+ local_only = get_cxx_toolchain_info(ctx).linker_info.link_binaries_locally,+ allow_cache_upload = allow_cache_upload and not strip_stapsdt,+ )++ output = postbolt_output++ if strip_stapsdt:+ stripped_postbolt_output = ctx.actions.declare_output(output_name + "-nostapsdt", has_content_based_path = False)+ ctx.actions.run(+ # We --rename-section instead of --remove-section because objcopy's processing+ # in an invalid ELF file+ cmd_args([+ get_cxx_toolchain_info(ctx).binary_utilities_info.objcopy,+ "--rename-section",+ ".stapsdt.base=.deleted_stapsdt_base_section",+ postbolt_output,+ stripped_postbolt_output.as_output(),+ ]),+ category = "bolt_strip_stapsdt",+ identifier = identifier,+ # This can execute in RE, but is cheaper to do locally especially for large binaries that+ # are already locally materialized+ prefer_local = True,+ allow_cache_upload = allow_cache_upload,+ )+ output = stripped_postbolt_output++ return CxxBoltOutput(output = output, dwo_output = dwo_output)
@@ -0,0 +1,44 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxPlatformInfo", "CxxToolchainInfo")++# The functions below allow the Cxx rules to find toolchain providers+# from different rule contexts. For example, the Cxx functions are+# re-used by non-`cxx_` rules (e.g., the Apple rules) but the toolchain+# setup on such rules might/would be different.+#+# The functions should be used throughout the Cxx rules to get+# the required providers instead of going via the `_cxx_toolchain`+# field of the `ctx`.+#+# In an ideal world, we would have been injecting all these from+# the top level but as part of the transition to support+# `apple_toolchain`, we want to make progress now.++def get_cxx_platform_info(ctx: AnalysisContext) -> CxxPlatformInfo:+ apple_toolchain = getattr(ctx.attrs, "_apple_toolchain", None)+ if apple_toolchain:+ return apple_toolchain[AppleToolchainInfo].cxx_platform_info+ return ctx.attrs._cxx_toolchain[CxxPlatformInfo]++def get_opt_cxx_toolchain_info(ctx: AnalysisContext) -> CxxToolchainInfo | None:+ apple_toolchain = getattr(ctx.attrs, "_apple_toolchain", None)+ if apple_toolchain:+ return apple_toolchain[AppleToolchainInfo].cxx_toolchain_info+ cxx_toolchain = getattr(ctx.attrs, "_cxx_toolchain", None)+ if cxx_toolchain:+ return cxx_toolchain.get(CxxToolchainInfo)+ return None++def get_cxx_toolchain_info(ctx: AnalysisContext) -> CxxToolchainInfo:+ info = get_opt_cxx_toolchain_info(ctx)+ if not info:+ fail("no cxx toolchain info in this ctx")+ return info
@@ -0,0 +1,201 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++CxxGenericErrorType = record(+ matcher = str | BuckRegex,+ category_suffix = str,+)++def make_error_type(matcher = None, category_suffix = str) -> CxxGenericErrorType:+ return CxxGenericErrorType(+ matcher = matcher,+ category_suffix = category_suffix,+ )++def _match(matcher: str | BuckRegex, lowercase_stderr: str) -> bool:+ if isinstance(matcher, str):+ return matcher in lowercase_stderr+ elif isinstance(matcher, BuckRegex):+ return matcher.match(lowercase_stderr)+ else:+ fail("Unknown matcher type: {}", type(matcher))++# Not applied automatically by the prelude; add them in your toolchain if you want them+#+# FIXME(JakobDegen): Change that?+def cxx_generic_error_handler(ctx: ActionErrorCtx) -> list[ActionSubError]:+ structured_error = ctx.parse_with_errorformat(+ category = "cxx_compiler_error",+ error = ctx.stderr,+ # reference partially: https://github.com/neovim/neovim/blob/07915941014307b054cbbb131369377647b7fb06/runtime/compiler/gcc.vim#L19-L37+ errorformats = [+ "%f:%l:%c:\\ %trror:\\ %m",+ "%f:%l:%c:\\ %tarning:\\ %m",+ "%f(%l,%c):\\ %trror:\\ %m",+ "%f(%l,%c):\\ %tarning:\\ %m",+ "%f:%l:\\ %trror:\\ %m",+ "%f:%l:\\ %tarning:\\ %m",+ ],+ )++ for e in structured_error:+ if e.error_type != None and e.error_type.lower() == "w":+ e.category = "cxx_compiler_warning"+ else:+ for error_type in CXX_GENERIC_ERROR_TYPES:+ if _match(error_type.matcher, e.message.lower()):+ e.category = "cxx_{}".format(error_type.category_suffix)+ break++ # If we didn't match any of the structured errors, try to get the category from the error message+ categories = []+ if len(structured_error) == 0:+ for error_type in CXX_GENERIC_ERROR_TYPES:+ if _match(error_type.matcher, ctx.stderr.lower()):+ categories.append(+ ctx.new_sub_error(+ category = "cxx_{}".format(error_type.category_suffix),+ )+ )++ return structured_error + categories++# PLEASE READ BEFORE ADDING NEW ERROR TYPES!+#+# Error types added here should be generic across all cxx toolchains, toolchain/platform specific errors+# should be defined in a separate toolchain and provided accordingly, these generic errors will automatically+# be added to all types. If you wish to add messages, it must be applicable to ALL scenarios, including OSS.+CXX_GENERIC_ERROR_TYPES = [+ # linker errors+ make_error_type(+ matcher = "error: duplicate symbol",+ category_suffix = "linker_duplicate_symbol",+ ),+ make_error_type(+ matcher = "error: undefined symbol",+ category_suffix = "linker_undefined_symbol",+ ),+ make_error_type(+ matcher = "error: unable to find library",+ category_suffix = "linker_missing_library",+ ),+ make_error_type(+ matcher = "cannot be used against local symbol",+ category_suffix = "linker_relocation",+ ),+ # compilation errors+ make_error_type(+ matcher = "file not found",+ category_suffix = "file_not_found",+ ),+ make_error_type(+ matcher = "extra-semi",+ category_suffix = "extra_semicolon",+ ),+ make_error_type(+ matcher = "cannot open file",+ category_suffix = "cannot_open_file",+ ),+ make_error_type(+ matcher = "too few arguments to function call",+ category_suffix = "too_few_arguments",+ ),+ make_error_type(+ matcher = "use of undeclared identifier",+ category_suffix = "undeclared_identifier",+ ),+ make_error_type(+ matcher = "macro redefined",+ category_suffix = "macro_redefined",+ ),+ make_error_type(+ matcher = "no type named",+ category_suffix = "missing_type",+ ),+ make_error_type(+ matcher = "no template named",+ category_suffix = "missing_template",+ ),+ make_error_type(+ matcher = "no matching function for call",+ category_suffix = "missing_function",+ ),+ make_error_type(+ matcher = "a type specifier is required for all declarations",+ category_suffix = "type_specifier_required",+ ),+ make_error_type(+ matcher = "definition of implicit copy constructor for",+ category_suffix = "definition_deprecated",+ ),+ make_error_type(+ matcher = "Permission denied",+ category_suffix = "permission_denied",+ ),+ make_error_type(+ matcher = "incomplete type",+ category_suffix = "incomplete_type",+ ),+ make_error_type(+ matcher = "C2440",+ category_suffix = "type_conversion_failed",+ ),+ make_error_type(+ matcher = "cannot initialize a member subobject of type",+ category_suffix = "type_mismatch",+ ),+ make_error_type(+ matcher = "no matching member function",+ category_suffix = "missing_member_function",+ ),+ make_error_type(+ matcher = "unused variable",+ category_suffix = "unused_variable",+ ),+ make_error_type(+ matcher = "Wheader-hygiene",+ category_suffix = "header_hygiene_violated",+ ),+ make_error_type(+ matcher = "call to non-static member function",+ category_suffix = "non_static_member_function_call",+ ),+ make_error_type(+ matcher = "too many template arguments for class template",+ category_suffix = "too_many_template_arguments",+ ),+ make_error_type(+ matcher = "possible misuse of comma operator",+ category_suffix = "comma_operator_misuse",+ ),+ make_error_type(+ matcher = "no such file or directory",+ category_suffix = "no_such_file_or_directory",+ ),+ make_error_type(+ matcher = "Wpadded",+ category_suffix = "padding_error",+ ),+ # compiler errors matched by regex+ make_error_type(+ matcher = regex("no member named '.+' in"),+ category_suffix = "missing_member",+ ),+ make_error_type(+ matcher = regex("reference to '.+' is ambiguous"),+ category_suffix = "ambiguous_reference",+ ),+ make_error_type(+ matcher = regex("use of overloaded operator '.+' is ambiguous"),+ category_suffix = "ambiguous_overload_operator",+ ),+ make_error_type(+ matcher = regex("call to constructor of '.+' is ambiguous"),+ category_suffix = "ambiguous_constructor_call",+ ),+]
@@ -0,0 +1,1262 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactTSet",+ "make_artifact_tset",+ "project_artifacts",+)+load("@prelude//:attrs_validators.bzl", "get_attrs_validation_specs")+load("@prelude//:local_only.bzl", "get_resolved_cxx_binary_link_execution_preference")+load(+ "@prelude//:resources.bzl",+ "create_relocatable_resources_info",+ "create_resource_db",+ "gather_resources",+)+load(+ "@prelude//apple:apple_frameworks.bzl",+ "apple_build_link_args_with_deduped_flags",+ "apple_create_frameworks_linkable",+ "apple_get_link_info_by_deduping_link_infos",+ "get_framework_search_path_flags",+)+load(+ "@prelude//cxx:cxx_bolt.bzl",+ "PRE_BOLT_SUFFIX",+ "cxx_use_bolt",+)+load(+ "@prelude//cxx:cxx_toolchain_types.bzl",+ "IncrementalLinkingMode",+ "PicBehavior",+ "RuntimeDependencyHandling",+)+load(+ "@prelude//cxx:hip_debug_extract.bzl",+ "PRE_EXTRACT_SUFFIX",+ "hip_debug_extract_available",+)+load(+ "@prelude//cxx:link_groups_types.bzl",+ "LinkGroupsDebugLinkInfo",+ "LinkGroupsDebugLinkableItem",+)+load("@prelude//cxx:transformation_spec.bzl", "TransformationKind", "build_transformation_spec_context")+load(+ "@prelude//dist:dist_info.bzl",+ "DistInfo",+)+load(+ "@prelude//ide_integrations/xcode:argsfiles.bzl",+ "XCODE_ARGSFILES_SUB_TARGET",+)+load(+ "@prelude//ide_integrations/xcode:data.bzl",+ "XCODE_DATA_SUB_TARGET",+ "XcodeDataInfo",+ "generate_xcode_data",+)+load("@prelude//linking:add_elf_sections.bzl", "PRE_ADD_ELF_SECTIONS_SUFFIX", "get_elf_sections")+load(+ "@prelude//linking:generated_build_info.bzl",+ "compile_generated_build_info",+ "generate_build_info",+ "generate_build_info_shared_library",+ "generated_build_info_is_shared_library",+)+load(+ "@prelude//linking:link_groups.bzl",+ "gather_link_group_libs",+)+load(+ "@prelude//linking:link_info.bzl",+ "LibOutputStyle",+ "LinkArgs",+ "LinkCommandDebugOutput",+ "LinkInfo",+ "LinkOrdering", # @unused Used as a type+ "LinkStrategy",+ "LinkedObject", # @unused Used as a type+ "ObjectsLinkable",+ "get_lib_output_style",+ "make_link_command_debug_output",+ "make_link_command_debug_output_json_info",+ "process_link_strategy_for_pic_behavior",+ "to_link_strategy",+ "unpack_link_args",+)+load(+ "@prelude//linking:linkable_graph.bzl",+ "LinkableGraph", # @unused Used as a type+ "create_linkable_graph",+ "get_linkable_graph_node_map_func",+ "reduce_linkable_graph",+)+load(+ "@prelude//linking:linkables.bzl",+ "LinkableProviders", # @unused Used as a type+ "linkables",+)+load(+ "@prelude//linking:shared_libraries.bzl",+ "SharedLibrary", # @unused Used as a type+ "SharedLibraryInfo", # @unused Used as a type+ "merge_shared_libraries",+ "traverse_shared_library_info",+)+load("@prelude//linking:stamp_build_info.bzl", "PRE_STAMPED_SUFFIX", "cxx_stamp_build_info")+load("@prelude//utils:arglike.bzl", "ArgLike") # @unused Used as a type+load(+ "@prelude//utils:build_graph_pattern.bzl",+ "new_build_graph_info",+)+load("@prelude//utils:lazy.bzl", "lazy")+load(+ "@prelude//utils:utils.bzl",+ "flatten",+ "flatten_dict",+ "map_val",+)+load("@prelude//xplugins:debug_artifacts.bzl", "xplugins_get_debug_artifacts_info")+load(+ "@prelude//xplugins:types.bzl",+ "XPluginsDebugArtifactsInfo",+)+load(+ ":argsfiles.bzl",+ "ARGSFILES_SUBTARGET",+ "get_argsfiles_output",+)+load(+ ":comp_db.bzl",+ "CxxCompilationDbInfo", # @unused Used as a type+ "create_compilation_database",+ "make_compilation_db_info",+)+load(+ ":compile.bzl",+ "ClangTracesInfo",+ "ClangTracesTSet",+ "PicClangTracesInfo",+ "compile_cxx",+ "create_compile_cmds",+ "cxx_objects_sub_targets",+)+load(":compile_types.bzl", "CxxCompileFlavor")+load(":cxx_context.bzl", "get_cxx_platform_info", "get_cxx_toolchain_info")+load(+ ":cxx_instrumentation.bzl",+ "is_coverage_enabled_by_any_dep",+)+load(+ ":cxx_library_utility.bzl",+ "OBJECTS_SUBTARGET",+ "cxx_attr_deps",+ "cxx_attr_link_style",+ "cxx_attr_linker_flags",+ "cxx_attr_resources",+ "cxx_is_gnu",+)+load(+ ":cxx_link_utility.bzl",+ "executable_shared_lib_arguments",+)+load(+ ":cxx_types.bzl",+ "CxxRuleConstructorParams", # @unused Used as a type+ "LinkPreference",+)+load(":diagnostics.bzl", "check_sub_target")+load(":gcno.bzl", "GcnoFilesInfo")+load(":groups.bzl", "get_dedupped_roots_from_groups")+load(+ ":link.bzl",+ "CxxGcSectionsData",+ "CxxLinkerMapData",+ "collect_hip_debug_from_links",+ "cxx_link_into",+ "link_args_have_hip_device_debug",+)+load(+ ":link_groups.bzl",+ "BuildLinkGroupsContext",+ "FinalLabelsToLinks",+ "LINK_GROUP_MAPPINGS_FILENAME_SUFFIX",+ "LINK_GROUP_MAPPINGS_SUB_TARGET",+ "LINK_GROUP_MAP_DATABASE_SUB_TARGET",+ "LinkGroupContext",+ "build_shared_libs_for_symlink_tree",+ "collect_linkables",+ "create_debug_linkable_entries",+ "create_link_groups",+ "find_relevant_roots",+ "get_filtered_labels_to_links_map",+ "get_filtered_links",+ "get_filtered_targets",+ "get_link_group",+ "get_link_group_map_json",+ "get_link_group_preferred_linkage",+ "get_public_link_group_nodes",+ "get_transitive_deps_matching_labels",+)+load(+ ":link_types.bzl",+ "CxxLinkResultType",+ "LinkOptions",+ "link_options",+ "merge_link_options",+)+load(+ ":linker.bzl",+ "DUMPBIN_SUB_TARGET",+ "PDB_SUB_TARGET",+ "get_dumpbin_providers",+ "get_pdb_providers",+ "get_shared_library_name",+)+load(+ ":preprocessor.bzl",+ "CPreprocessor",+ "CPreprocessorArgs",+ "cxx_inherited_preprocessor_infos",+ "cxx_private_preprocessor_info",+)++CxxExecutableOutput = record(+ binary = Artifact,+ unstripped_binary = Artifact,+ bitcode_bundle = field(Artifact | None, None),+ diagnostics = field(Artifact | None),+ dwp = field(Artifact | None),+ # Files that must be present for the executable to run successfully. These+ # are always materialized, whether the executable is the output of a build+ # or executed as a host tool. They become hidden= arguments when executing+ # the executable via RunInfo().+ runtime_files = list[ArgLike],+ sub_targets = dict[str, list[DefaultInfo]],+ # The LinkArgs used to create the final executable in 'binary'.+ link_args = list[LinkArgs],+ # External components needed to debug the executable.+ external_debug_info = field(ArtifactTSet, ArtifactTSet()),+ # The projection of `external_debug_info`. These files need to be+ # materialized when this executable is the output of a build, not when it is+ # used by other rules. They become other_outputs on DefaultInfo.+ external_debug_info_artifacts = list[TransitiveSetArgsProjection],+ shared_libs = list[SharedLibrary],+ # All link group links that were generated in the executable.+ auto_link_groups = field(dict[str, LinkedObject], {}),+ compilation_db = CxxCompilationDbInfo,+ xcode_data = [XcodeDataInfo, None],+ linker_map_data = [CxxLinkerMapData, None],+ gc_sections_data = [CxxGcSectionsData, None],+ link_command_debug_output = field([LinkCommandDebugOutput, None], None),+ dist_info = DistInfo,+ sanitizer_runtime_files = field(list[Artifact], []),+ index_stores = field(list[Artifact], []),+ validation_specs = field(list[ValidationSpec], []),+ gcno_files = field(list[Artifact], []),+ xplugins_debug_artifacts_info = field(XPluginsDebugArtifactsInfo | None, None),+ build_info_manifest_entries = field(Artifact | None, None),+)++def cxx_executable(ctx: AnalysisContext, impl_params: CxxRuleConstructorParams, is_cxx_test: bool = False) -> CxxExecutableOutput:+ # Gather preprocessor inputs.+ preprocessor_deps = cxx_attr_deps(ctx) + filter(None, [impl_params.precompiled_header])+ (own_preprocessor_info, test_preprocessor_infos) = cxx_private_preprocessor_info(+ ctx,+ impl_params.headers_layout,+ raw_headers = ctx.attrs.raw_headers,+ extra_preprocessors = impl_params.extra_preprocessors,+ non_exported_deps = preprocessor_deps,+ is_test = is_cxx_test,+ )+ inherited_preprocessor_infos = cxx_inherited_preprocessor_infos(preprocessor_deps) + impl_params.extra_preprocessors_info++ # Add framework search paths if frameworks attribute is set.+ # This is needed for the apple_test/apple_binary -> cxx_test/cxx_binary swap.+ frameworks = getattr(ctx.attrs, "frameworks", [])+ framework_search_path_pre = None+ if frameworks:+ framework_search_paths_flags = get_framework_search_path_flags(ctx)+ framework_search_path_pre = CPreprocessor(+ args = CPreprocessorArgs(args = [framework_search_paths_flags]),+ )++ # The link style to use.+ link_strategy = to_link_strategy(cxx_attr_link_style(ctx))+ link_strategy = process_link_strategy_for_pic_behavior(link_strategy, get_cxx_toolchain_info(ctx).pic_behavior)++ sub_targets = {}++ # Compile objects.+ own_preprocessors = [own_preprocessor_info] + test_preprocessor_infos+ if framework_search_path_pre:+ own_preprocessors.insert(0, framework_search_path_pre)+ compile_cmd_output = create_compile_cmds(+ ctx.actions,+ ctx.label,+ get_cxx_toolchain_info(ctx),+ impl_params,+ own_preprocessors,+ inherited_preprocessor_infos,+ is_coverage_enabled_by_any_dep(ctx, preprocessor_deps),+ )+ cxx_deps = cxx_attr_deps(ctx)+ build_graph_info = new_build_graph_info(ctx, cxx_deps)+ transformation_spec_context = build_transformation_spec_context(ctx, build_graph_info)+ compile_flavors = set([CxxCompileFlavor("pic")]) if link_strategy != LinkStrategy("static") else set()++ if transformation_spec_context:+ transformation_kind = transformation_spec_context.provider.determine_transformation(ctx.label, transformation_spec_context.graph_info)+ if transformation_kind == TransformationKind("debug"):+ compile_flavors.add(CxxCompileFlavor("debug"))+ elif transformation_kind == TransformationKind("optimized"):+ compile_flavors.add(CxxCompileFlavor("optimized"))++ cxx_outs = compile_cxx(+ actions = ctx.actions,+ target_label = ctx.label,+ toolchain = get_cxx_toolchain_info(ctx),+ src_compile_cmds = compile_cmd_output.src_compile_cmds,+ flavors = compile_flavors,+ provide_syntax_only = True,+ separate_debug_info = impl_params.separate_debug_info,+ use_header_units = impl_params.use_header_units,+ cuda_compile_style = impl_params.cuda_compile_style,+ )++ gcno_files = [out.gcno_file for out in cxx_outs if out.gcno_file]+ if get_cxx_toolchain_info(ctx).gcno_files:+ gcno_files += flatten([dep[GcnoFilesInfo].gcno_files for dep in cxx_deps if GcnoFilesInfo in dep])++ if impl_params.generate_sub_targets.argsfiles:+ sub_targets[ARGSFILES_SUBTARGET] = [get_argsfiles_output(ctx, compile_cmd_output.argsfiles.relative, ARGSFILES_SUBTARGET)]+ if impl_params.generate_sub_targets.xcode_data:+ sub_targets[XCODE_ARGSFILES_SUB_TARGET] = [get_argsfiles_output(ctx, compile_cmd_output.argsfiles.xcode, XCODE_ARGSFILES_SUB_TARGET)]+ sub_targets[OBJECTS_SUBTARGET] = [DefaultInfo(sub_targets = cxx_objects_sub_targets(cxx_outs))]++ if impl_params.generate_sub_targets and impl_params.generate_sub_targets.clang_traces:+ traces = [out.clang_trace for out in cxx_outs if out.clang_trace != None]+ sub_targets["clang-trace"] = [+ DefaultInfo(+ default_outputs = traces,+ )+ ]++ clang_traces_tset = ctx.actions.tset(+ ClangTracesTSet,+ value = traces,+ children = [+ info.clang_traces+ for info in filter(None, [x.get(PicClangTracesInfo) if link_strategy != LinkStrategy("static") else x.get(ClangTracesInfo) for x in cxx_deps])+ ],+ )++ clang_traces_args = clang_traces_tset.project_as_args("clang_traces")+ all_traces = ctx.actions.write(+ ctx.actions.declare_output("recursive_clang_traces.txt", has_content_based_path = False),+ clang_traces_args,+ )++ sub_targets["clang-traces"] = [+ DefaultInfo(+ default_output = all_traces,+ other_outputs = [clang_traces_args],+ )+ ]++ diagnostics = {+ compile_cmd.src.short_path: out.diagnostics for compile_cmd, out in zip(compile_cmd_output.src_compile_cmds, cxx_outs) if out.diagnostics != None+ }+ clang_tidy_diagnostics = {+ compile_cmd.src.short_path + ".clang-tidy": out.clang_tidy_diagnostics+ for compile_cmd, out in zip(compile_cmd_output.src_compile_cmds, cxx_outs)+ if out.clang_tidy_diagnostics != None+ }+ all_diagnostics = None+ if len(diagnostics) > 0:+ sub_targets["check"], all_diagnostics = check_sub_target(+ ctx,+ diagnostics,+ error_handler = impl_params.error_handler,+ extra_sub_targets = clang_tidy_diagnostics,+ )+ if len(clang_tidy_diagnostics) > 0:+ check_all_diagnostics = dict(diagnostics)+ check_all_diagnostics.update(clang_tidy_diagnostics)+ check_all_subtarget_result = check_sub_target(+ ctx,+ check_all_diagnostics,+ error_handler = impl_params.error_handler,+ output_name = "all_diagnostics.txt",+ )+ sub_targets["check-all"] = check_all_subtarget_result[0]++ # Compilation DB.+ comp_db = create_compilation_database(ctx, compile_cmd_output.src_compile_cmds, "compilation-database")+ sub_targets["compilation-database"] = [comp_db]++ # Compilation DB including headers.+ comp_db = create_compilation_database(ctx, compile_cmd_output.comp_db_compile_cmds, "full-compilation-database")+ sub_targets["full-compilation-database"] = [comp_db]++ # comp_db_compile_cmds can include header files being compiled as C++ which should not be exposed in the [compilation-database] subtarget+ comp_db_info = make_compilation_db_info(compile_cmd_output.comp_db_compile_cmds, get_cxx_toolchain_info(ctx), get_cxx_platform_info(ctx))++ # Index Stores created by cxx compile+ index_stores = [out.index_store for out in cxx_outs if out.index_store]++ # Link deps+ link_deps = linkables(cxx_deps) + impl_params.extra_link_deps++ # Link Groups+ link_group = get_link_group(ctx)+ link_group_info = impl_params.link_group_info++ if link_group_info:+ link_groups = link_group_info.groups+ link_group_mappings = link_group_info.mappings+ link_group_deps = [link_group_info.graph]+ else:+ link_groups = {}+ link_group_mappings = {}+ link_group_deps = []+ link_group_preferred_linkage = get_link_group_preferred_linkage(link_groups.values())++ # Create the linkable graph with the binary's deps and any link group deps.+ linkable_graph = create_linkable_graph(+ ctx,+ deps = filter(+ None,+ # Some subtargets (like :Foo[headers]) do not have a linkable_graph.+ [d.linkable_graph for d in link_deps]+ ++ # We also need to include additional link roots, so that we find+ # deps that might need to be linked into the main executable.+ [d.linkable_graph for d in impl_params.extra_link_roots]+ ++ # For non-auto-link-group cases, also search the targets specified+ # in the link group mappings, as they won't be available in other+ # ways.+ link_group_deps,+ ),+ )++ # Gather link inputs.+ own_link_flags = (+ get_cxx_toolchain_info(ctx).linker_info.binary_linker_flags+ + cxx_attr_linker_flags(ctx, impl_params.cxx_flags)+ + impl_params.extra_link_flags+ + impl_params.extra_exported_link_flags+ )++ own_exe_link_flags = impl_params.extra_binary_link_flags + own_link_flags+ deps_merged_link_infos = [d.merged_link_info for d in link_deps]+ frameworks_linkable = apple_create_frameworks_linkable(ctx)+ swiftmodule_linkable = impl_params.swiftmodule_linkable++ # Link group libs.+ link_group_libs = {}++ # Target label to which link group it was included+ targets_consumed_by_link_groups = {}+ auto_link_groups = {}++ # Linker map data for link group shared libraries, keyed by group name.+ link_group_linker_map_data = {}+ labels_to_links = FinalLabelsToLinks(+ map = {},+ )++ if not link_group_mappings:+ # We cannot support deriving link execution preference off the included links, as we've already+ # lost the information on what is in the link.+ # TODO(T152860998): Derive link_execution_preference based upon the included links+ link_execution_preference = get_resolved_cxx_binary_link_execution_preference(ctx, [], impl_params.force_full_hybrid_if_capable)++ dep_links = apple_build_link_args_with_deduped_flags(+ ctx,+ deps_merged_link_infos,+ frameworks_linkable,+ link_strategy,+ transformation_spec_context,+ swiftmodule_linkable,+ prefer_stripped = impl_params.prefer_stripped_objects,+ )+ else:+ reduced_linkable_graph = reduce_linkable_graph(linkable_graph)+ linkable_graph_node_map = reduced_linkable_graph.nodes++ # Although these aren't really deps, we need to search from the+ # extra link group roots to make sure we find additional libs+ # that should be linked into the main link group.+ link_group_extra_link_roots = [d.linkable_graph.nodes.value.label for d in impl_params.extra_link_roots if d.linkable_graph != None]++ exec_dep_roots = [d.linkable_graph.nodes.value.label for d in link_deps if d.linkable_graph != None]++ # If we're using auto-link-groups, where we generate the link group links+ # in the prelude, the link group map will give us the link group libs.+ # Otherwise, pull them from the `LinkGroupLibInfo` provider from out deps.++ public_link_group_nodes = get_public_link_group_nodes(+ linkable_graph_node_map,+ link_group_mappings,+ exec_dep_roots + link_group_extra_link_roots,+ link_group,+ )+ link_group_libs_debug_info = {}+ if impl_params.auto_link_group_specs != None:+ linked_link_groups = create_link_groups(+ ctx = ctx,+ link_groups = link_groups,+ link_strategy = link_strategy,+ linkable_graph = reduced_linkable_graph,+ link_group_mappings = link_group_mappings,+ link_group_preferred_linkage = link_group_preferred_linkage,+ executable_deps = exec_dep_roots,+ linker_flags = own_link_flags,+ link_group_specs = impl_params.auto_link_group_specs,+ other_roots = link_group_extra_link_roots,+ prefer_stripped_objects = impl_params.prefer_stripped_objects,+ anonymous = ctx.attrs.anonymous_link_groups,+ allow_cache_upload = impl_params.exe_allow_cache_upload,+ public_nodes = public_link_group_nodes,+ transformation_spec_context = transformation_spec_context,+ error_handler = impl_params.error_handler,+ )+ link_group_libs_debug_info = linked_link_groups.libs_debug_info+ for name, linked_link_group in linked_link_groups.libs.items():+ auto_link_groups[name] = linked_link_group.artifact+ if linked_link_group.library != None:+ link_group_libs[name] = linked_link_group.library+ if linked_link_group.linker_map_data != None:+ link_group_linker_map_data[name] = linked_link_group.linker_map_data+ own_exe_link_flags += linked_link_groups.symbol_ldflags+ targets_consumed_by_link_groups = linked_link_groups.targets_consumed_by_link_groups++ else:+ # NOTE(agallagher): We don't use version scripts and linker scripts+ # for non-auto-link-group flow, as it's note clear it's useful (e.g.+ # it's mainly for supporting dlopen-enabled libs and extensions).+ link_group_libs = gather_link_group_libs(+ children = [d.link_group_lib_info for d in link_deps],+ )++ pic_behavior = get_cxx_toolchain_info(ctx).pic_behavior++ roots = set(+ exec_dep_roots+ + find_relevant_roots(+ link_group = link_group,+ linkable_graph_node_map = linkable_graph_node_map,+ link_group_mappings = link_group_mappings,+ roots = link_group_extra_link_roots,+ ),+ )+ is_executable_link = True+ exec_linkables = collect_linkables(+ reduced_linkable_graph,+ is_executable_link,+ link_strategy,+ link_group_preferred_linkage,+ pic_behavior,+ roots,+ )++ build_context = BuildLinkGroupsContext(+ public_nodes = public_link_group_nodes,+ linkable_graph = reduced_linkable_graph,+ link_groups = link_groups,+ link_group_mappings = link_group_mappings,+ link_group_preferred_linkage = link_group_preferred_linkage,+ link_strategy = link_strategy,+ pic_behavior = pic_behavior,+ link_group_libs = {name: (lib.label, lib.shared_link_infos) for name, lib in link_group_libs.items()},+ prefer_stripped = impl_params.prefer_stripped_objects,+ prefer_optimized = False,+ transformation_spec_context = transformation_spec_context,+ )++ # TODO(T110378098): Similar to shared libraries, we need to identify all the possible+ # scenarios for which we need to propagate up link info and simplify this logic. For now+ # base which links to use based on whether link groups are defined.+ labels_to_links = get_filtered_labels_to_links_map(+ link_group,+ linkables = exec_linkables,+ is_executable_link = is_executable_link,+ build_context = build_context,+ force_static_follows_dependents = impl_params.link_groups_force_static_follows_dependents,+ )++ link_groups_binary_debug_info = LinkGroupsDebugLinkableItem(+ ordered_linkables = create_debug_linkable_entries(labels_to_links.map, root = None),+ )+ link_groups_debug_info = LinkGroupsDebugLinkInfo(+ binary = link_groups_binary_debug_info,+ libs = link_group_libs_debug_info,+ )+ link_groups_libs_sub_targets = {}+ for name, lib in link_group_libs_debug_info.items():+ link_groups_libs_sub_targets[name] = [+ DefaultInfo(+ default_output = ctx.actions.write_json(+ ctx.label.name + ".link-groups-info.libs.{}.json".format(name),+ lib,+ has_content_based_path = False,+ ),+ ),+ ]+ sub_targets["link-groups-info"] = [+ DefaultInfo(+ default_output = ctx.actions.write_json(+ ctx.label.name + ".link-groups-info.json",+ link_groups_debug_info,+ has_content_based_path = False,+ ),+ sub_targets = {+ "bin": [+ DefaultInfo(+ default_output = ctx.actions.write_json(+ ctx.label.name + ".link-groups-info.bin.json",+ link_groups_binary_debug_info,+ has_content_based_path = False,+ ),+ )+ ],+ "shared-libraries": [DefaultInfo(sub_targets = link_groups_libs_sub_targets)],+ },+ )+ ]++ if is_cxx_test and link_group != None:+ # if a cpp_unittest is part of the link group, we need to traverse through all deps+ # from the root again to ensure we link in gtest deps+ roots = set([d.linkable_graph.nodes.value.label for d in link_deps])+ exec_linkables = collect_linkables(+ linkable_graph_node_map,+ is_executable_link,+ link_strategy,+ link_group_preferred_linkage,+ pic_behavior,+ roots,+ )+ labels_to_links_to_merge = get_filtered_labels_to_links_map(+ link_group = None,+ linkables = exec_linkables,+ is_executable_link = False,+ build_context = build_context,+ )+ labels_to_links.map |= labels_to_links_to_merge.map++ # NOTE: Our Haskell DLL support impl currently links transitive haskell+ # deps needed by DLLs which get linked into the main executable as link-+ # whole. To emulate this, we mark Haskell rules with a special label+ # and traverse this to find all the nodes we need to link whole.+ public_nodes = []+ if ctx.attrs.link_group_public_deps_label != None:+ public_nodes = get_transitive_deps_matching_labels(+ linkable_graph_node_map = linkable_graph_node_map,+ label = ctx.attrs.link_group_public_deps_label,+ roots = get_dedupped_roots_from_groups(link_group_info.groups.values()),+ )++ filtered_links = get_filtered_links(labels_to_links.map, set(public_nodes))+ filtered_targets = get_filtered_targets(labels_to_links.map)++ link_execution_preference = get_resolved_cxx_binary_link_execution_preference(ctx, labels_to_links.map.keys(), impl_params.force_full_hybrid_if_capable)++ # Unfortunately, link_groups does not use MergedLinkInfo to represent the args+ # for the resolved nodes in the graph.+ # Thus, we have no choice but to traverse all the nodes to dedupe the framework linker args.+ additional_links = apple_get_link_info_by_deduping_link_infos(ctx, filtered_links, frameworks_linkable, swiftmodule_linkable)+ if additional_links:+ filtered_links.append(additional_links)++ dep_links = LinkArgs(infos = filtered_links)+ sub_targets[LINK_GROUP_MAP_DATABASE_SUB_TARGET] = [get_link_group_map_json(ctx, filtered_targets)]++ gnu_use_link_groups = cxx_is_gnu(ctx) and len(link_group_mappings) > 0+ shlib_deps = _get_shared_library_symlink_deps(+ ctx,+ gnu_use_link_groups,+ impl_params,+ link_strategy,+ link_deps,+ linkable_graph,+ )++ shlib_info = merge_shared_libraries(ctx.actions, deps = shlib_deps)++ link_group_ctx = LinkGroupContext(+ link_group_mappings = link_group_mappings,+ link_group_libs = link_group_libs,+ link_group_preferred_linkage = link_group_preferred_linkage,+ labels_to_links_map = labels_to_links.map,+ targets_consumed_by_link_groups = targets_consumed_by_link_groups,+ )++ # Set up shared libraries symlink tree only when needed+ shared_libs = build_shared_libs_for_symlink_tree(+ gnu_use_link_groups,+ link_group_ctx,+ link_strategy,+ traverse_shared_library_info(shlib_info, transformation_provider = transformation_spec_context),+ impl_params.extra_shared_libs,+ )++ toolchain_info = get_cxx_toolchain_info(ctx)+ linker_info = toolchain_info.linker_info+ generated_build_info_external_debug_info = []+ binary_linker_flags = ctx.attrs.binary_linker_flags+ generated_build_info_args = []+ if getattr(ctx.attrs, "_generated_build_info_enabled", False):+ generated_build_info_args = [flag for flag in binary_linker_flags if _is_build_info_linker_flag(flag)]+ binary_linker_flags = [flag for flag in binary_linker_flags if not _is_build_info_linker_flag(flag)]+ generated_build_info_invalidation_inputs = (+ [out.object for out in cxx_outs]+ + [unpack_link_args(dep_links)]+ + [shared_lib.lib.output for shared_lib in shared_libs]+ + impl_params.generated_build_info_invalidation_inputs+ )+ generated_build_info_shared_library = None+ if generated_build_info_is_shared_library(ctx):+ binary_linker_flags += ["--build-info=none"]+ generated_build_info_shared_library = generate_build_info_shared_library(+ ctx,+ dep_links,+ generator_args = generated_build_info_args,+ invalidation_inputs = generated_build_info_invalidation_inputs,+ )+ if generated_build_info_shared_library:+ shared_libs.append(generated_build_info_shared_library.library)+ sub_targets["generated_build_info"] = [+ DefaultInfo(default_output = generated_build_info_shared_library.library.lib.output),+ ]+ else:+ generated_build_info = generate_build_info(+ ctx,+ generator_args = generated_build_info_args,+ invalidation_inputs = generated_build_info_invalidation_inputs,+ )+ if generated_build_info:+ generated_build_info_compile_output = compile_generated_build_info(ctx, generated_build_info)+ generated_build_info_external_debug_info = generated_build_info_compile_output.external_debug_info+ binary_linker_flags += generated_build_info_compile_output.objects + generated_build_info.linker_flags++ links = [+ LinkArgs(+ infos = [+ LinkInfo(+ dist_thin_lto_codegen_flags = getattr(ctx.attrs, "dist_thin_lto_codegen_flags", []),+ pre_flags = own_exe_link_flags,+ linkables = [+ ObjectsLinkable(+ objects = [out.object for out in cxx_outs] + impl_params.extra_link_input,+ linker_type = linker_info.type,+ link_whole = True,+ )+ ],+ external_debug_info = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ artifacts = (+ [out.object for out in cxx_outs if out.object_has_external_debug_info]+ + [out.external_debug_info for out in cxx_outs if out.external_debug_info != None]+ + generated_build_info_external_debug_info+ + (impl_params.extra_link_input if impl_params.extra_link_input_has_external_debug_info else [])+ ),+ ),+ ),+ ]+ ),+ ]+ if generated_build_info_shared_library:+ links.append(generated_build_info_shared_library.link_args)+ links += [dep_links] + impl_params.extra_link_args++ # If there are hidden dependencies to this target then add them as+ # hidden link args.+ if impl_params.extra_hidden:+ links.append(+ LinkArgs(flags = cmd_args(hidden = impl_params.extra_hidden)),+ )++ incremental_linking_mode = IncrementalLinkingMode(linker_info.incremental_linking)+ if impl_params.link_preference == LinkPreference("incremental"):+ incremental_link = incremental_linking_mode != IncrementalLinkingMode("disabled")+ elif impl_params.link_preference == LinkPreference("full"):+ incremental_link = False+ else:+ incremental_link = incremental_linking_mode == IncrementalLinkingMode("enabled")++ has_hip_device_debug = lazy.is_any(lambda out: out.hip_device_debug, cxx_outs) or link_args_have_hip_device_debug(links)+ link_result = _link_into_executable(+ ctx,+ # If shlib lib tree generation is enabled, pass in the shared libs (which+ # will trigger the necessary link tree and link args).+ shared_libs if impl_params.exe_shared_libs_link_tree else [],+ impl_params.executable_name,+ linker_info.binary_extension,+ binary_linker_flags,+ link_options(+ links = links,+ link_weight = linker_info.link_weight,+ link_ordering = map_val(LinkOrdering, ctx.attrs.link_ordering),+ link_execution_preference = link_execution_preference,+ enable_distributed_thinlto = ctx.attrs.enable_distributed_thinlto,+ strip = impl_params.strip_executable,+ strip_args_factory = impl_params.strip_args_factory,+ category_suffix = impl_params.exe_category_suffix,+ allow_cache_upload = impl_params.exe_allow_cache_upload,+ error_handler = impl_params.error_handler,+ extra_linker_outputs_factory = impl_params.extra_linker_outputs_factory,+ extra_linker_outputs_flags_factory = impl_params.extra_linker_outputs_flags_factory,+ extra_distributed_thin_lto_opt_outputs_merger = impl_params.extra_distributed_thin_lto_opt_outputs_merger,+ incremental_link = incremental_link,+ has_hip_device_debug = has_hip_device_debug,+ ),+ build_info_json = (generated_build_info_shared_library.json if generated_build_info_shared_library else None),+ )+ binary = link_result.exe+ runtime_files = link_result.runtime_files+ shared_libs_symlink_tree = link_result.shared_libs_symlink_tree+ linker_map_data = link_result.linker_map_data+ gc_sections_data = link_result.gc_sections_data++ # Define the xcode data sub target+ xcode_data_info = None+ if impl_params.generate_sub_targets.xcode_data:+ xcode_data_default_info, xcode_data_info = generate_xcode_data(+ ctx,+ rule_type = impl_params.rule_type,+ output = binary.output,+ populate_rule_specific_attributes_func = impl_params.cxx_populate_xcode_attributes_func,+ srcs = impl_params.srcs + impl_params.additional.srcs,+ argsfiles = compile_cmd_output.argsfiles.xcode,+ product_name = get_cxx_executable_product_name(ctx, has_hip_device_debug),+ )+ sub_targets[XCODE_DATA_SUB_TARGET] = xcode_data_default_info++ # Info about dynamic-linked libraries for fbpkg integration:+ # - the symlink dir that's part of RPATH+ # - sub-sub-targets that reference shared library dependencies and their respective dwp+ # - [shared-libraries] - a json map that references the above rules.+ if isinstance(shared_libs_symlink_tree, Artifact):+ sub_targets["rpath-tree"] = [+ DefaultInfo(+ default_output = shared_libs_symlink_tree,+ other_outputs = [shlib.lib.output for shlib in shared_libs] + [shlib.lib.dwp for shlib in shared_libs if shlib.lib.dwp],+ )+ ]++ # TODO(agallagher) There appears to be pre-existing soname conflicts+ # when building this (when using link groups), which prevents using+ # `with_unique_str_sonames`.+ str_soname_shlibs = {shlib.soname.ensure_str(): shlib for shlib in shared_libs if shlib.soname.is_str}++ readable_mappings = {}+ soname_to_group_mappings = {}+ if link_group_mappings:+ for node, group in link_group_mappings.items():+ soname = get_shared_library_name(linker_info, group, True)+ soname_to_group_mappings[soname] = group+ readable_mappings.setdefault(group, []).append(node.raw_target())++ sub_targets[LINK_GROUP_MAPPINGS_SUB_TARGET] = [+ DefaultInfo(+ default_output = ctx.actions.write_json(+ binary.output.basename + LINK_GROUP_MAPPINGS_FILENAME_SUFFIX,+ readable_mappings,+ has_content_based_path = False,+ ),+ )+ ]++ linkable_graph_node_map = get_linkable_graph_node_map_func(linkable_graph)()+ sub_targets["binary_node_count"] = [+ DefaultInfo(+ default_output = ctx.actions.write_json(+ binary.output.basename + ".binary_node_count.json",+ {+ "binary_node_count": len(linkable_graph_node_map),+ },+ has_content_based_path = False,+ ),+ )+ ]++ shared_libraries_sub_targets = {}+ for soname, shlib in str_soname_shlibs.items():+ targets = {"dwp": [DefaultInfo(default_output = shlib.lib.dwp)]} if shlib.lib.dwp else {}++ group = soname_to_group_mappings.get(soname)+ if group in readable_mappings:+ output_json_file = binary.output.basename + "." + group + LINK_GROUP_MAPPINGS_FILENAME_SUFFIX+ targets[LINK_GROUP_MAPPINGS_SUB_TARGET] = [+ DefaultInfo(+ default_output = ctx.actions.write_json(+ output_json_file,+ {group: readable_mappings[group]},+ has_content_based_path = False,+ ),+ )+ ]+ if group in link_group_linker_map_data:+ lm_data = link_group_linker_map_data[group]+ targets["linker-map"] = [DefaultInfo(default_output = lm_data.map, other_outputs = [lm_data.binary])]+ shared_libraries_sub_targets[soname] = [+ DefaultInfo(+ default_output = shlib.lib.output,+ sub_targets = targets,+ )+ ]++ sub_targets["shared-libraries"] = [+ DefaultInfo(+ default_output = ctx.actions.write_json(+ binary.output.basename + ".shared-libraries.json",+ {+ "libraries": ["{}:{}[shared-libraries][{}]".format(ctx.label.path, ctx.label.name, soname) for soname in str_soname_shlibs],+ "librariesdwp": [+ "{}:{}[shared-libraries][{}][dwp]".format(ctx.label.path, ctx.label.name, soname)+ for soname, shlib in str_soname_shlibs.items()+ if shlib.lib.dwp+ ],+ "rpathtree": ["{}:{}[rpath-tree]".format(ctx.label.path, ctx.label.name)] if shared_libs_symlink_tree else [],+ },+ has_content_based_path = False,+ ),+ sub_targets = shared_libraries_sub_targets,+ )+ ]++ # If we have some resources, write it to the resources JSON file and add+ # it and all resources to "runtime_files" so that we make to materialize+ # them with the final binary.+ resources = flatten_dict(+ gather_resources(+ label = ctx.label,+ resources = cxx_attr_resources(ctx),+ deps = cxx_attr_deps(ctx),+ ).values()+ )+ relocatable_resources_json = None+ relocatable_resources_contents = None+ if resources:+ runtime_files.append(+ create_resource_db(+ ctx = ctx,+ name = binary.output.basename + ".resources.json",+ binary = binary.output,+ resources = resources,+ )+ )+ for resource in resources.values():+ runtime_files.append(resource.default_output)+ runtime_files.extend(resource.other_outputs)+ relocatable_resources_json, relocatable_resources_contents = create_relocatable_resources_info(+ ctx = ctx,+ name = ctx.label.name,+ resources = resources,+ )++ if binary.dwp:+ # A `dwp` sub-target which generates the `.dwp` file for this binary and its shared lib dependencies.+ shared_libraries_dwp = [shlib.lib.dwp for shlib in shared_libs if shlib.lib.dwp] + (+ [link_result.dwp_symlink_tree] if link_result.dwp_symlink_tree else []+ )++ sub_targets["dwp"] = [+ DefaultInfo(+ default_output = binary.dwp,+ other_outputs = shared_libraries_dwp,+ ),+ ]++ # Own TU sidecars + transitive deps' sidecars.+ hip_all_debug_files = {}+ for out in cxx_outs:+ for arch, debug_file in out.hip_arch_debug_files.items():+ hip_all_debug_files.setdefault(arch, [])+ hip_all_debug_files[arch].append(debug_file)+ for arch, files in collect_hip_debug_from_links(links).items():+ hip_all_debug_files.setdefault(arch, [])+ hip_all_debug_files[arch].extend(files)++ if hip_all_debug_files:+ per_arch_debug_subs = {arch: [DefaultInfo(default_outputs = files)] for arch, files in hip_all_debug_files.items()}+ all_files = [f for files in hip_all_debug_files.values() for f in files]+ hip_debug_manifest = ctx.actions.write(+ "__hip_debug_manifest__.txt",+ cmd_args(all_files, delimiter = "\n"),+ )+ sub_targets["hip_debug"] = [+ DefaultInfo(+ default_output = hip_debug_manifest,+ other_outputs = all_files,+ sub_targets = per_arch_debug_subs,+ ),+ ]++ if binary.pdb:+ # A `pdb` sub-target which generates the `.pdb` file for this binary.+ sub_targets[PDB_SUB_TARGET] = get_pdb_providers(pdb = binary.pdb, binary = binary.output)++ if binary.ilk:+ sub_targets["ilk"] = [DefaultInfo(default_output = binary.ilk)]++ if toolchain_info.dumpbin_toolchain_path:+ sub_targets[DUMPBIN_SUB_TARGET] = get_dumpbin_providers(ctx, binary.output, toolchain_info.dumpbin_toolchain_path)++ # If bolt is not ran, binary.prebolt_output will be the same as binary.output. Only+ # expose binary.prebolt_output if cxx_use_bolt(ctx) is True to avoid confusion+ if cxx_use_bolt(ctx):+ sub_targets["prebolt"] = [DefaultInfo(default_output = binary.prebolt_output)]++ if linker_map_data:+ sub_targets["linker-map"] = [DefaultInfo(default_output = linker_map_data.map, other_outputs = [linker_map_data.binary])]++ if gc_sections_data:+ sub_targets["gc-sections"] = [DefaultInfo(default_output = gc_sections_data.gc_sections, other_outputs = [gc_sections_data.binary])]++ sub_targets["linker.argsfile"] = [+ DefaultInfo(+ default_output = binary.linker_argsfile,+ )+ ]++ link_cmd_debug_output = make_link_command_debug_output(binary)+ if link_cmd_debug_output != None:+ link_cmd_debug_output_file = make_link_command_debug_output_json_info(ctx.actions, [link_cmd_debug_output])+ sub_targets["linker.command"] = [+ DefaultInfo(+ default_outputs = filter(None, [link_cmd_debug_output_file]),+ )+ ]++ if linker_info.supports_distributed_thinlto and ctx.attrs.enable_distributed_thinlto:+ sub_targets["index.argsfile"] = [+ DefaultInfo(+ default_output = binary.index_argsfile,+ )+ ]++ # Provide a debug info target to make sure unpacked external debug info+ # (dwo) is materialized.+ external_debug_info = make_artifact_tset(+ actions = ctx.actions,+ children = ([binary.external_debug_info] + [s.lib.external_debug_info for s in shared_libs] + impl_params.additional.static_external_debug_info),+ )+ external_debug_info_artifacts = project_artifacts(ctx.actions, external_debug_info)+ materialize_external_debug_info = ctx.actions.write(+ "debuginfo.artifacts",+ external_debug_info_artifacts,+ with_inputs = True,+ has_content_based_path = False,+ )+ sub_targets["debuginfo"] = [+ DefaultInfo(+ default_output = materialize_external_debug_info,+ )+ ]+ sub_targets["debug_coverage_instrumentation"] = [+ DefaultInfo(+ default_output = materialize_external_debug_info,+ )+ ]++ sub_targets["exe"] = [+ DefaultInfo(+ default_output = binary.output,+ other_outputs = runtime_files,+ )+ ]++ for additional_subtarget, subtarget_providers in impl_params.additional.subtargets.items():+ sub_targets[additional_subtarget] = subtarget_providers++ sub_targets.update(link_result.extra_outputs)++ xplugins_debug_artifacts_info = xplugins_get_debug_artifacts_info(ctx, cxx_deps)++ return CxxExecutableOutput(+ binary = binary.output,+ unstripped_binary = binary.unstripped_output,+ dwp = binary.dwp,+ runtime_files = runtime_files,+ sub_targets = sub_targets,+ link_args = links,+ external_debug_info = external_debug_info,+ external_debug_info_artifacts = external_debug_info_artifacts,+ shared_libs = shared_libs,+ auto_link_groups = auto_link_groups,+ compilation_db = comp_db_info,+ xcode_data = xcode_data_info,+ linker_map_data = linker_map_data,+ gc_sections_data = gc_sections_data,+ link_command_debug_output = link_cmd_debug_output,+ dist_info = DistInfo(+ shared_libs = shlib_info.set,+ nondebug_runtime_files = runtime_files,+ relocatable_resources_json = relocatable_resources_json,+ relocatable_resources_contents = relocatable_resources_contents,+ ),+ sanitizer_runtime_files = link_result.sanitizer_runtime_files,+ index_stores = index_stores,+ diagnostics = all_diagnostics,+ validation_specs = get_attrs_validation_specs(ctx),+ gcno_files = dedupe(gcno_files),+ xplugins_debug_artifacts_info = xplugins_debug_artifacts_info,+ build_info_manifest_entries = (generated_build_info_shared_library.manifest_entries if generated_build_info_shared_library else None),+ )++_CxxLinkExecutableResult = record(+ # The resulting executable+ exe = LinkedObject,+ # Files that must be present for the executable to run successfully. These+ # are always materialized, whether the executable is the output of a build+ # or executed as a host tool.+ runtime_files = list[ArgLike],+ # Files needed to debug the executable. These need to be materialized when+ # this executable is the output of a build, but not when it is used by other+ # rules.+ external_debug_info = list[TransitiveSetArgsProjection],+ dwp_symlink_tree = field(list[Artifact] | Artifact | None),+ # Optional shared libs symlink tree symlinked_dir action+ shared_libs_symlink_tree = [list[Artifact], Artifact, None],+ linker_map_data = [CxxLinkerMapData, None],+ gc_sections_data = [CxxGcSectionsData, None],+ sanitizer_runtime_files = list[Artifact],+ # Extra output providers produced by extra_linker_outputs_factory+ extra_outputs = dict[str, list[DefaultInfo]],+)++def _get_shared_library_symlink_deps(+ ctx: AnalysisContext,+ gnu_use_link_groups: bool,+ impl_params: CxxRuleConstructorParams,+ link_strategy: LinkStrategy,+ link_deps: list[LinkableProviders],+ linkable_graph: LinkableGraph,+) -> list[SharedLibraryInfo]:+ """+ Determine which shared library deps need a symlink tree alongside the executable.+ """++ # Only setup a shared library symlink tree when shared linkage or link_groups is used+ shlib_deps = []+ if link_strategy == LinkStrategy("shared") or gnu_use_link_groups:+ shlib_deps = [d.shared_library_info for d in link_deps] + [d.shared_library_info for d in impl_params.extra_link_roots]+ elif impl_params.runtime_dependency_handling == RuntimeDependencyHandling("no_symlink"):+ # Do not create a shared library symlink tree alongside the executable.+ pass+ elif impl_params.runtime_dependency_handling == RuntimeDependencyHandling("symlink"):+ # Include all transitive runtime shared library deps in a symlink tree.+ for linkable_node in linkable_graph.nodes.traverse():+ if linkable_node.linkable == None:+ continue+ preferred_linkage = linkable_node.linkable.preferred_linkage+ output_style = get_lib_output_style(link_strategy, preferred_linkage, PicBehavior("supported"))+ if output_style == LibOutputStyle("shared_lib") and not linkable_node.linkable.stub:+ shlib_deps.append(merge_shared_libraries(ctx.actions, node = linkable_node.linkable.shared_libs))+ elif impl_params.runtime_dependency_handling == RuntimeDependencyHandling("symlink_single_level_only"):+ # Include only first-level (direct) runtime shared library deps in a symlink tree.+ for d in link_deps + impl_params.extra_link_roots:+ if d.linkable_graph == None:+ continue+ preferred_linkage = d.linkable_graph.nodes.value.linkable.preferred_linkage+ output_style = get_lib_output_style(link_strategy, preferred_linkage, PicBehavior("supported"))+ if output_style == LibOutputStyle("shared_lib"):+ shlib_deps.append(d.shared_library_info)++ return shlib_deps++def _link_into_executable(+ ctx: AnalysisContext,+ shared_libs: list[SharedLibrary],+ executable_name: [str, None],+ binary_extension: str,+ binary_linker_flags: list[typing.Any],+ opts: LinkOptions,+ build_info_json: Artifact | None = None,+) -> _CxxLinkExecutableResult:+ if executable_name and binary_extension and executable_name.endswith(binary_extension):+ # don't append .exe if it already is .exe+ output_name = executable_name+ else:+ output_name = "{}{}".format(+ executable_name if executable_name else get_cxx_executable_product_name(ctx, opts.has_hip_device_debug),+ "." + binary_extension if binary_extension else "",+ )+ output = ctx.actions.declare_output(output_name, has_content_based_path = False)+ executable_args = executable_shared_lib_arguments(+ ctx,+ get_cxx_toolchain_info(ctx),+ output,+ shared_libs,+ )++ link_result = cxx_link_into(+ ctx = ctx,+ output = output,+ result_type = CxxLinkResultType("executable"),+ # Binary linker flags should come after default link flags so they can override default settings.+ opts = merge_link_options(+ opts,+ binary_links = [+ LinkArgs(+ infos = [+ LinkInfo(+ pre_flags = binary_linker_flags,+ ),+ ]+ ),+ ],+ links = [LinkArgs(flags = executable_args.extra_link_args)] + opts.links,+ ),+ build_info_json = build_info_json,+ )++ return _CxxLinkExecutableResult(+ exe = link_result.linked_object,+ runtime_files = executable_args.runtime_files + link_result.sanitizer_runtime_files,+ external_debug_info = executable_args.external_debug_info,+ shared_libs_symlink_tree = executable_args.shared_libs_symlink_tree,+ dwp_symlink_tree = executable_args.dwp_symlink_tree,+ linker_map_data = link_result.linker_map_data,+ gc_sections_data = link_result.gc_sections_data,+ sanitizer_runtime_files = link_result.sanitizer_runtime_files,+ extra_outputs = link_result.extra_outputs if link_result.extra_outputs else {},+ )++def get_cxx_post_link_suffix(ctx: AnalysisContext, has_hip_device_debug: bool = False) -> str:+ """+ The suffix the linker's output must carry so that each post-link stage of+ `cxx_link_into` can strip the part it owns, leaving the canonical name.++ Appended in reverse of the order the stages run, so the outermost suffix+ belongs to the stage that runs first.+ """+ suffix = ""+ if cxx_stamp_build_info(ctx):+ suffix += PRE_STAMPED_SUFFIX+ if get_elf_sections(ctx):+ suffix += PRE_ADD_ELF_SECTIONS_SUFFIX+ if has_hip_device_debug and hip_debug_extract_available(get_cxx_toolchain_info(ctx)):+ suffix += PRE_EXTRACT_SUFFIX+ if cxx_use_bolt(ctx):+ suffix += PRE_BOLT_SUFFIX+ return suffix++def get_cxx_executable_product_name(ctx: AnalysisContext, has_hip_device_debug: bool = False) -> str:+ return ctx.label.name + get_cxx_post_link_suffix(ctx, has_hip_device_debug)++def _is_build_info_linker_flag(flag) -> bool:+ return flag.startswith("--build-info")
@@ -0,0 +1,113 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(":attr_selection.bzl", "cxx_by_language_ext")++CxxFlags = record(+ compiler_flags = field(list[typing.Any], []),+ lang_compiler_flags = field(dict[typing.Any, typing.Any], {}),+ lang_preprocessor_flags = field(dict[typing.Any, typing.Any], {}),+ linker_flags = field(list[typing.Any], []),+ preprocessor_flags = field(list[typing.Any], []),+)++def _compiler_flags(flags: CxxFlags):+ return cmd_args(flags.compiler_flags)++def _linker_flags(flags: CxxFlags):+ return cmd_args(flags.linker_flags)++def _preprocessor_flags(flags: CxxFlags):+ return cmd_args(flags.preprocessor_flags)++def _flags_for_ext(ext: str):+ def project(flags: CxxFlags):+ return cmd_args(+ flags.preprocessor_flags,+ cxx_by_language_ext(flags.lang_preprocessor_flags, ext),+ cxx_by_language_ext(flags.lang_compiler_flags, ext),+ flags.compiler_flags,+ )++ return project++CxxFlagsTSet = transitive_set(+ args_projections = {+ "asm": _flags_for_ext(".asm"),+ "asmpp": _flags_for_ext(".S"),+ "c": _flags_for_ext(".c"),+ "compiler_flags": _compiler_flags,+ "cuda": _flags_for_ext(".cu"),+ "cxx": _flags_for_ext(".cpp"),+ "hip": _flags_for_ext(".hip"),+ "linker_flags": _linker_flags,+ "objc": _flags_for_ext(".m"),+ "objcxx": _flags_for_ext(".mm"),+ "preprocessor_flags": _preprocessor_flags,+ },+)++CxxFlagsInfo = provider(+ fields = {+ "flags": provider_field(typing.Any), # CxxFlagsTSet+ },+)++def cxx_flags_impl(ctx: AnalysisContext) -> list[Provider]:+ return [+ DefaultInfo(),+ CxxFlagsInfo(+ flags = ctx.actions.tset(+ CxxFlagsTSet,+ value = CxxFlags(+ compiler_flags = ctx.attrs.compiler_flags,+ lang_compiler_flags = ctx.attrs.lang_compiler_flags,+ lang_preprocessor_flags = ctx.attrs.lang_preprocessor_flags,+ linker_flags = ctx.attrs.linker_flags,+ preprocessor_flags = ctx.attrs.preprocessor_flags,+ ),+ children = [dep[CxxFlagsInfo].flags for dep in ctx.attrs.deps],+ ),+ ),+ ]++def cxx_attr_flags(ctx: AnalysisContext) -> list[Dependency]:+ return getattr(ctx.attrs, "flags", [])++def cxx_flags_tset(actions: AnalysisActions, flag_deps: list[Dependency]):+ if not flag_deps:+ return None+ return actions.tset(+ CxxFlagsTSet,+ children = [dep[CxxFlagsInfo].flags for dep in flag_deps],+ )++def cxx_flags_projection_name(ext: str) -> str:+ if ext == ".c":+ return "c"+ elif ext in (".cpp", ".cc", ".cl", ".cxx", ".c++", ".bc"):+ return "cxx"+ elif ext == ".m":+ return "objc"+ elif ext == ".mm":+ return "objcxx"+ elif ext in (".s", ".sx", ".S"):+ return "asmpp"+ elif ext == ".cu":+ return "cuda"+ elif ext == ".hip":+ return "hip"+ elif ext in (".asm", ".asmpp"):+ return "asm"+ fail("Unexpected file extension: " + ext)++def cxx_flags_linker_flags(actions: AnalysisActions, flag_deps: list[Dependency]) -> list[typing.Any]:+ flags = cxx_flags_tset(actions, flag_deps)+ if flags == None:+ return []+ return [flags.project_as_args("linker_flags", ordering = "postorder")]
@@ -0,0 +1,42 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++def needs_instrumentation(children: list[bool], contains_headers_selected_for_coverage_instrumentation: bool) -> bool:+ return contains_headers_selected_for_coverage_instrumentation or any(children)++CxxExportedNeedsCoverageInstrumentationTSet = transitive_set(+ reductions = {+ "needs_instrumentation": needs_instrumentation,+ },+)++CxxExportedNeedsCoverageInstrumentation = provider(+ fields = {+ "nodes": CxxExportedNeedsCoverageInstrumentationTSet,+ }+)++def build_needs_coverage_tset(ctx: AnalysisContext, deps: list[Dependency]) -> CxxExportedNeedsCoverageInstrumentationTSet:+ return ctx.actions.tset(+ CxxExportedNeedsCoverageInstrumentationTSet,+ value = ctx.attrs.exported_needs_coverage_instrumentation if hasattr(ctx.attrs, "exported_needs_coverage_instrumentation") else False,+ children = [d.get(CxxExportedNeedsCoverageInstrumentation).nodes for d in deps if d.get(CxxExportedNeedsCoverageInstrumentation) != None],+ )++def build_exported_needs_coverage(ctx: AnalysisContext, deps: list[Dependency]) -> CxxExportedNeedsCoverageInstrumentation:+ return CxxExportedNeedsCoverageInstrumentation(+ nodes = build_needs_coverage_tset(ctx, deps),+ )++def is_coverage_enabled_by_any_dep(ctx: AnalysisContext, deps: list[Dependency]) -> bool:+ tset = build_needs_coverage_tset(ctx, deps)++ return tset.reduce("needs_instrumentation")++def needs_coverage(cxx_exported_needs_coverage: CxxExportedNeedsCoverageInstrumentation) -> bool:+ return cxx_exported_needs_coverage.nodes.reduce("needs_instrumentation")
@@ -0,0 +1,2566 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactTSet", # @unused Used as a type+ "make_artifact_tset",+)+load("@prelude//:attrs_validators.bzl", "get_attrs_validation_specs")+load("@prelude//:paths.bzl", "paths")+load(+ "@prelude//:resources.bzl",+ "gather_resources",+ "make_resource_info",+)+load(+ "@prelude//android:android_providers.bzl",+ "merge_android_packageable_info",+)+load(+ "@prelude//apple:apple_frameworks.bzl",+ "apple_build_link_args_with_deduped_flags",+ "apple_create_frameworks_linkable",+ "apple_get_link_info_by_deduping_link_infos",+ "get_framework_search_path_flags",+)+load(+ "@prelude//apple:apple_resource_types.bzl",+ "CxxResourceSpec",+)+load(+ "@prelude//apple:modularization_dependency_graph.bzl",+ "ModularizationDependencyGraphInfo",+ "create_modularization_dep_graph_subtargets_and_provider",+)+load("@prelude//apple:resource_groups.bzl", "create_resource_graph")+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")+load(+ "@prelude//cxx:headers.bzl",+ "CPrecompiledHeaderInfo",+ "CxxPrecompiledHeader",+ "cxx_attr_precompiled_headers",+)+load(+ "@prelude//ide_integrations/xcode:argsfiles.bzl",+ "XCODE_ARGSFILES_SUB_TARGET",+)+load(+ "@prelude//ide_integrations/xcode:data.bzl",+ "XCODE_DATA_SUB_TARGET",+ "XcodeDataInfo",+ "generate_xcode_data",+)+load(+ "@prelude//java:java_providers.bzl",+ "get_java_packaging_info",+ "propagate_global_code_info",+)+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference", "get_link_execution_preference")+load(+ "@prelude//linking:link_groups.bzl",+ "EMPTY_LINK_GROUP_LIB_INFO",+ "LinkGroupLib", # @unused Used as a type+ "gather_link_group_libs",+ "merge_link_group_lib_info",+)+load(+ "@prelude//linking:link_info.bzl",+ "ArchiveContentsType",+ "ArchiveLinkable",+ "FrameworksLinkable", # @unused Used as a type+ "LibOutputStyle",+ "LinkArgs",+ "LinkCommandDebugOutputInfo",+ "LinkInfo",+ "LinkInfos",+ "LinkOrdering",+ "LinkStrategy",+ "LinkableFlavor", # @unused Used as a type+ "LinkedObject",+ "ObjectsLinkable",+ "SharedLibLinkable",+ "SwiftmoduleLinkable", # @unused Used as a type+ "UnstrippedLinkOutputInfo",+ "create_merged_link_info",+ "get_lib_output_style",+ "get_link_args_for_strategy",+ "get_output_styles_for_linkage",+ "make_link_command_debug_output",+ "make_link_command_debug_output_json_info",+ "process_link_strategy_for_pic_behavior",+ "subtarget_for_output_style",+ "to_link_strategy",+ "unpack_link_args",+ "wrap_link_info",+)+load(+ "@prelude//linking:linkable_graph.bzl",+ "DLOPENABLE_LIBRARY_INFO_MARKER",+ "LinkableRootInfo",+ "ReducedLinkableGraph", # @unused used as a type+ "create_linkable_graph",+ "create_linkable_graph_node",+ "create_linkable_node",+ "linkable_deps",+ "reduce_linkable_graph",+)+load(+ "@prelude//linking:shared_libraries.bzl",+ "EMPTY_SHARED_LIBRARY_INFO",+ "NamedLinkedObject",+ "SharedLibraryInfo",+ "create_flavored_shared_libraries",+ "merge_shared_libraries",+)+load("@prelude//linking:strip.bzl", "strip_debug_info")+load("@prelude//linking:types.bzl", "Linkage")+load("@prelude//target_stats:target_stats.bzl", "CycleMode", "target_stats_providers_and_subtargets")+load("@prelude//target_stats:target_stats_config.bzl", "TARGET_STATS_ENABLED")+load(+ "@prelude//third-party:build.bzl",+ "create_third_party_build_info",+)+load("@prelude//unix:providers.bzl", "UnixEnv", "create_unix_env_info")+load("@prelude//utils:expect.bzl", "expect")+load("@prelude//utils:lazy.bzl", "lazy")+load(+ "@prelude//utils:utils.bzl",+ "filter_and_map_idx",+ "flatten",+ "map_val",+ "value_or",+)+load("@prelude//xplugins:debug_artifacts.bzl", "xplugins_get_debug_artifacts_info")+load("@prelude//xplugins:utils.bzl", "get_xplugins_usage_info")+load(":archive.bzl", "make_archive")+load(+ ":argsfiles.bzl",+ "ARGSFILES_SUBTARGET",+ "get_argsfiles_output",+)+load(":bitcode.bzl", "BitcodeBundle", "BitcodeBundleInfo", "BitcodeTSet", "make_bitcode_bundle")+load(+ ":comp_db.bzl",+ "CxxCompilationDbInfo",+ "create_compilation_database",+ "make_compilation_db_info",+)+load(+ ":compile.bzl",+ "ClangTracesInfo",+ "ClangTracesTSet",+ "PicClangTracesInfo",+ "compile_cxx",+ "create_compile_cmds",+ "cxx_objects_sub_targets",+ "precompile_cxx",+ "toolchain_supports_flavor",+)+load(+ ":compile_types.bzl",+ "CxxCompileCommandOutput",+ "CxxCompileFlavor",+ "CxxCompileOutput", # @unused Used as a type+ "CxxExtension",+ "CxxSrcCompileCommand",+)+load(":cxx_context.bzl", "get_cxx_platform_info", "get_cxx_toolchain_info")+load(":cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload")+load(+ ":cxx_instrumentation.bzl",+ "build_exported_needs_coverage",+ "needs_coverage",+)+load(+ ":cxx_library_utility.bzl",+ "EMPTY_DEFAULT_INFO",+ "OBJECTS_SUBTARGET",+ "cxx_attr_dep_metadata",+ "cxx_attr_deps",+ "cxx_attr_exported_deps",+ "cxx_attr_link_style",+ "cxx_attr_linker_flags_all",+ "cxx_attr_preferred_linkage",+ "cxx_attr_resources",+ "cxx_inherited_link_info",+ "cxx_is_gnu",+ "cxx_platform_supported",+ "cxx_use_shlib_intfs",+)+load(":cxx_sources.bzl", "CxxSrcWithFlags")+load(+ ":cxx_toolchain_types.bzl",+ "LinkerType",+ "ShlibInterfacesMode",+ "is_bitcode_format",+)+load(+ ":cxx_transitive_diagnostics.bzl",+ "cxx_transitive_diagnostics_combine",+)+load(+ ":cxx_types.bzl",+ "CxxLibraryInfo",+ "CxxRuleConstructorParams", # @unused Used as a type+)+load(":diagnostics.bzl", "check_sub_target")+load(":gcno.bzl", "GcnoFilesInfo")+load(":hip_debug_extract.bzl", "PRE_EXTRACT_SUFFIX", "hip_debug_extract_available")+load(":index_store.bzl", "IndexStoreInfo", "create_index_store_subtargets_and_provider")+load(+ ":link.bzl",+ "CxxLinkResult", # @unused Used as a type+ "CxxLinkerMapData",+ "cxx_link_shared_library",+ "link_args_have_hip_device_debug",+)+load(+ ":link_groups.bzl",+ "BuildLinkGroupsContext",+ "LINK_GROUP_MAP_DATABASE_SUB_TARGET",+ "collect_linkables",+ "get_filtered_labels_to_links_map",+ "get_filtered_links",+ "get_filtered_targets",+ "get_link_group",+ "get_link_group_info",+ "get_link_group_map_json",+ "get_link_group_preferred_linkage",+)+load(+ ":link_types.bzl",+ "link_options",+)+load(+ ":linker.bzl",+ "get_default_shared_library_name",+ "get_ignore_undefined_symbols_flags",+ "get_shared_library_name",+ "get_shared_library_name_for_param",+ "sandbox_exported_linker_flags",+)+load(+ ":omnibus.bzl",+ "create_linkable_root",+)+load(+ ":preprocessor.bzl",+ "CPreprocessor", # @unused Used as a type+ "CPreprocessorArgs",+ "CPreprocessorForTestsInfo",+ "CPreprocessorInfo", # @unused Used as a type+ "cxx_exported_preprocessor_info",+ "cxx_inherited_preprocessor_infos",+ "cxx_merge_cpreprocessors",+ "cxx_private_preprocessor_info",+)+load(+ ":shared_library_interface.bzl",+ "shared_library_interface",+)++# A possible output of a `cxx_library`. This could be an archive or a shared library. Generally for an archive+# it represents just the sources of the library target itself, while a shared library will bundle multiple libraries+# together.+CxxLibraryOutput = record(+ # The output style of this output.+ output_style = field(LibOutputStyle),+ # The main output.+ default = field(Artifact),+ unstripped = field(Artifact),+ # Additional outputs that are implicitly used along with the above output+ # (e.g. external object files referenced by a thin archive).+ #+ # Note: It's possible that this can contain some of the artifacts which are+ # also present in object_files.+ other = field(list[Artifact], []),+ # The bitcode bundle. This only available for archive outputs.+ # TODO(cjhopman): always available? when is it/is it not available?+ bitcode_bundle = field([BitcodeBundle, None], None),+ # Additional debug info which referenced by but not included in the library output.+ external_debug_info = field(ArtifactTSet, ArtifactTSet()),+ # A shared shared library may have an associated dwp file with+ # its corresponding DWARF debug info.+ # May be None when Split DWARF is disabled, for static/static-pic libraries,+ # for some types of synthetic link objects or for pre-built shared libraries.+ dwp = field(Artifact | None, None),+ hip_arch_debug_files = field(dict[str, list[Artifact]], {}),+ # A shared shared library may have an associated PDB file with+ # its corresponding Windows debug info.+ pdb = field(Artifact | None, None),+ # The import library is the linkable output of a Windows shared library build.+ implib = field(Artifact | None, None),+ # Data about the linker map, only available on shared libraries+ # TODO(cjhopman): always available? when is it/is it not available?+ linker_map = field([CxxLinkerMapData, None], None),+ # Extra sub targets to be returned as outputs of this rule, by link style.+ sub_targets = field(dict[str, list[DefaultInfo]]),+ # The object files used to create the artifact in `default`. This only includes the object files+ # for this library itself, so it's not particularly meaningful for a shared lib output.+ object_files = field(list[Artifact], []),+)++# The outputs of either archiving or linking the outputs of the library+_CxxAllLibraryOutputs = record(+ # The outputs for each lib output style.+ # For 'static'/'static_pic', these will be archives containing just this library's object files.+ # For 'shared', the output as a shared library. That output will be built using either this library's link_strategy link strategy+ # or via the link group strategy if this library has link group mapping.+ # A header-only lib won't produce any outputs (but it may still provide LinkInfos below).+ # TODO(cjhopman): make library-level link_group shared lib not put its output here+ outputs = field(dict[LibOutputStyle, dict[LinkableFlavor, CxxLibraryOutput]]),+ # The link infos for linking against this lib of each output style. It's possible for a library to+ # add link_infos even when it doesn't produce an output itself.+ link_infos = field(dict[LibOutputStyle, LinkInfos]),+ # Extra providers to be returned consumers of this rule.+ providers = field(list[Provider], default = []),+ # Shared object name to shared library mapping if this target produces a shared library.+ solibs = field(dict[LinkableFlavor, NamedLinkedObject]),+ sanitizer_runtime_files = field(list[Artifact], []),+)++_CxxLibraryCompileOutput = record(+ # object files+ objects = field(list[Artifact]),+ # linkable object files from pch compilation+ pch_object_output = field(list[Artifact]),+ # object files stripped of debug information+ stripped_objects = field(list[Artifact]),+ # Those outputs which are bitcode+ bitcode_objects = field([list[Artifact], None]),+ # yaml file with optimization remarks about clang compilation+ clang_remarks = field([list[Artifact], None]),+ # llvm statistics about clang compilation+ clang_llvm_statistics = field([list[Artifact], None]),+ gcno_files = field([list[Artifact], None]),+ # json file with trace information about clang compilation+ clang_traces = field(list[Artifact]),+ # Externally referenced debug info, which doesn't get linked with the+ # object (e.g. the above `.o` when using `-gsplit-dwarf=single` or the+ # the `.dwo` when using `-gsplit-dwarf=split`).+ external_debug_info = field(list[Artifact]),+ # Whether there is any debug info+ objects_have_external_debug_info = field(bool),+ # sub_target for each object+ objects_sub_targets = field(dict[str, list[DefaultInfo]]),+ # the generated index stores+ index_stores = field(list[Artifact]),+ # diagnostics produced by a typecheck-only build (-fsyntax-only)+ diagnostics = field(dict[str, Artifact]),+ # diagnostics produced by clang-tidy+ clang_tidy_diagnostics = field(dict[str, Artifact]),+ has_hip_device_debug = field(bool, False),+ hip_arch_debug_files = field(dict[str, list[Artifact]], {}),+)++# The output of compiling all the source files in the library, containing+# the commands use to compile them and all the object file variants.+_CxxCompiledSourcesOutput = record(+ # Compile commands used to compile the source files or generate object files+ compile_cmds = field(CxxCompileCommandOutput),+ # PIC compile outputs+ pic = field(_CxxLibraryCompileOutput),+ # PIC optimized compile outputs+ pic_optimized = field([_CxxLibraryCompileOutput, None]),+ # PIC debuggable compile outputs+ pic_debuggable = field([_CxxLibraryCompileOutput, None]),+ # Non PIC compile outputs+ non_pic = field([_CxxLibraryCompileOutput, None]),+ # Header unit outputs+ header_unit_preprocessors = field(list[CPreprocessor]),+)++# The outputs of a cxx_library_parameterized rule.+_CxxLibraryParameterizedOutput = record(+ # The default output of a cxx library rule+ default_output = field([CxxLibraryOutput, None], None),+ # The other outputs available+ all_outputs = field([_CxxAllLibraryOutputs, None], None),+ # Any generated sub targets as requested by impl_params. Most of these will just be a+ # DefaultInfo to expose outputs to be consumed or built individually, but some (like "headers")+ # will have richer providers.+ sub_targets = field(dict[str, list[Provider]]),+ # A bundle of all bitcode files as a subtarget+ bitcode_bundle = field([BitcodeBundle, None], None),+ # Any generated providers as requested by impl_params.+ providers = field(list[Provider]),+ # XcodeDataInfo provider, returned separately as we cannot check+ # provider type from providers above+ xcode_data_info = field([XcodeDataInfo, None], None),+ # IndexStoreInfo provider, so we can access the paths of all the index stores+ # or Swift-specific index stores.+ index_store_info = field([IndexStoreInfo, None], None),+ # ModularizationDependencyGraphInfo provider for transitive modularization graphs.+ modularization_dep_graph_info = field([ModularizationDependencyGraphInfo, None], None),+ # CxxCompilationDbInfo provider, returned separately as we cannot check+ # provider type from providers above+ cxx_compilationdb_info = field([CxxCompilationDbInfo, None], None),+ # LinkableRootInfo provider, same as above.+ linkable_root = field([LinkableRootInfo, None], None),+ # List of shared libraries for the sanitizer runtime linked into the library+ sanitizer_runtime_files = field(list[Artifact], []),+)++def valid_pch_clanguage(val: typing.Any) -> bool:+ if not val:+ return False+ return val in [ext.value for ext in CxxExtension]++# FIXME(JakobDegen): This is used in place of `cxx_attr_link_style` in some places in a way that+# makes no sense to me and is not really in keeping with the rest of this API. But we rely on it.+# If you can justify it, replace with a comment.+def _link_strategy_for_some_shared_links(attrs: typing.Any) -> LinkStrategy:+ value = attrs.link_style if attrs.link_style != None else "shared"+ if value == "static":+ value = "static_pic"+ return LinkStrategy(value)++def cxx_library_parameterized(ctx: AnalysisContext, impl_params: CxxRuleConstructorParams) -> _CxxLibraryParameterizedOutput:+ """+ Defines the outputs for a cxx library, return the default output and any subtargets and providers based upon the requested params.+ """+ if not cxx_platform_supported(ctx):+ sub_targets = {}++ # Needed to handle cases of the named output (e.g. [static-pic]) being called directly.+ for output_style in get_output_styles_for_linkage(cxx_attr_preferred_linkage(ctx)):+ sub_targets[subtarget_for_output_style(output_style)] = [DefaultInfo(default_output = None)]++ return _CxxLibraryParameterizedOutput(+ providers = [+ DefaultInfo(default_output = None, sub_targets = sub_targets),+ EMPTY_SHARED_LIBRARY_INFO,+ ],+ sub_targets = sub_targets,+ )++ non_exported_deps = cxx_attr_deps(ctx)+ exported_deps = cxx_attr_exported_deps(ctx)+ deps_all_exported_first = exported_deps + non_exported_deps+ deps_all_non_exported_first = non_exported_deps + exported_deps++ compile_pch = None+ pch_clanguage = None+ if impl_params.rule_type == "cxx_precompiled_header":+ if len(ctx.attrs.srcs) != 1:+ fail("cxx_precompiled_header must have exactly one source file, got: {}".format(len(ctx.attrs.srcs)))++ pch_clanguage = ctx.attrs.pch_clanguage+ if not valid_pch_clanguage(pch_clanguage):+ fail("pch_clanguage was: {}, must be one of: {}".format(pch_clanguage, [ext.value for ext in CxxExtension]))++ pch_artifact = ctx.attrs.srcs[0]+ pch_header = cxx_attr_precompiled_headers(ctx, impl_params.headers_layout)+ basename = "{}{}".format(pch_artifact.basename, pch_clanguage)+ path = paths.join(pch_header.namespace, pch_header.name)++ pch_wrapper = ctx.actions.declare_output("pch_wrapper.cpp", has_content_based_path = False)+ ctx.actions.write(pch_wrapper, '#include "{}"'.format(path))++ ctx.attrs.headers.append(pch_artifact)+ impl_params.srcs[0] = CxxSrcWithFlags(file = pch_wrapper)++ compile_pch = CxxPrecompiledHeader(+ header = ctx.attrs.srcs[0],+ basename = basename,+ basename_src = pch_artifact.basename,+ path = path,+ namespace = pch_header.namespace,+ clanguage = pch_clanguage,+ )++ # TODO(T110378095) right now we implement reexport of exported_* flags manually, we should improve/automate that in the macro layer++ # Gather preprocessor inputs.+ (own_non_exported_preprocessor_info, test_preprocessor_infos) = cxx_private_preprocessor_info(+ ctx = ctx,+ raw_headers = ctx.attrs.raw_headers,+ headers_layout = impl_params.headers_layout,+ extra_preprocessors = impl_params.extra_preprocessors,+ non_exported_deps = non_exported_deps,+ is_test = impl_params.is_test,+ )+ own_exported_preprocessor_info = cxx_exported_preprocessor_info(+ ctx,+ impl_params.headers_layout,+ extra_preprocessors = impl_params.extra_exported_preprocessors,+ )+ own_preprocessors = [own_non_exported_preprocessor_info, own_exported_preprocessor_info] + test_preprocessor_infos+ own_exported_preprocessors = [own_exported_preprocessor_info]++ # Add framework search paths to exported preprocessors if frameworks attribute is set.+ # This is needed for the apple_library -> cxx_library swap in fb_xplat_cxx_library.+ frameworks = getattr(ctx.attrs, "frameworks", [])+ if frameworks:+ framework_search_paths_flags = get_framework_search_path_flags(ctx)+ framework_search_path_pre = CPreprocessor(+ args = CPreprocessorArgs(args = [framework_search_paths_flags]),+ )+ own_exported_preprocessors.insert(0, framework_search_path_pre)+ own_preprocessors.insert(0, framework_search_path_pre)++ inherited_non_exported_preprocessor_infos = cxx_inherited_preprocessor_infos(+ # Legacy precompiled_header implementation is not exported. Proper precompiled headers can have exported linkables.+ non_exported_deps+ + filter(+ None,+ [+ impl_params.precompiled_header+ if impl_params.precompiled_header and not impl_params.precompiled_header[CPrecompiledHeaderInfo].compiled+ else None+ ],+ ),+ )+ inherited_exported_preprocessor_infos = cxx_inherited_preprocessor_infos(exported_deps)++ preferred_linkage = cxx_attr_preferred_linkage(ctx)++ exported_needs_coverage = build_exported_needs_coverage(ctx, deps_all_exported_first)+ compiled_srcs = cxx_compile_srcs(+ actions = ctx.actions,+ target_label = ctx.label,+ cxx_toolchain_info = get_cxx_toolchain_info(ctx),+ impl_params = impl_params,+ own_preprocessors = own_preprocessors,+ own_exported_preprocessors = own_exported_preprocessors,+ inherited_non_exported_preprocessor_infos = inherited_non_exported_preprocessor_infos,+ inherited_exported_preprocessor_infos = inherited_exported_preprocessor_infos,+ preferred_linkage = preferred_linkage,+ compile_pch = compile_pch,+ add_coverage_instrumentation_compiler_flags = needs_coverage(exported_needs_coverage),+ )++ sub_targets = {}+ providers = []++ attr_validation_specs = get_attrs_validation_specs(ctx)+ if attr_validation_specs:+ providers.append(ValidationInfo(validations = attr_validation_specs))++ if compile_pch:+ pch_provider = CPrecompiledHeaderInfo(+ header = compile_pch.header,+ basename = compile_pch.basename,+ compiled = True,+ clanguage = pch_clanguage,+ )++ sub_targets["pch"] = [+ DefaultInfo(+ sub_targets = {+ "default": [+ CPrecompiledHeaderInfo(header = compiled_srcs.non_pic.objects[0], basename = compile_pch.basename, compiled = True, clanguage = pch_clanguage)+ ]+ if compiled_srcs.non_pic+ else [],+ CxxCompileFlavor("pic").value: [+ CPrecompiledHeaderInfo(header = compiled_srcs.pic.objects[0], basename = compile_pch.basename, compiled = True, clanguage = pch_clanguage)+ ]+ if compiled_srcs.pic+ else [],+ CxxCompileFlavor("debug").value: [+ CPrecompiledHeaderInfo(+ header = compiled_srcs.pic_debuggable.objects[0], basename = compile_pch.basename, compiled = True, clanguage = pch_clanguage+ )+ ]+ if compiled_srcs.pic_debuggable+ else [],+ CxxCompileFlavor("optimized").value: [+ CPrecompiledHeaderInfo(+ header = compiled_srcs.pic_optimized.objects[0], basename = compile_pch.basename, compiled = True, clanguage = pch_clanguage+ )+ ]+ if compiled_srcs.pic_optimized+ else [],+ },+ )+ ]++ providers.append(pch_provider)++ providers.append(exported_needs_coverage)++ if len(ctx.attrs.tests) > 0 and impl_params.generate_providers.preprocessor_for_tests:+ providers.append(+ CPreprocessorForTestsInfo(+ test_names = [test_target.name for test_target in ctx.attrs.tests],+ own_non_exported_preprocessor = own_non_exported_preprocessor_info,+ ),+ )++ if impl_params.generate_sub_targets.argsfiles:+ sub_targets[ARGSFILES_SUBTARGET] = [get_argsfiles_output(ctx, compiled_srcs.compile_cmds.argsfiles.relative, ARGSFILES_SUBTARGET)]+ if impl_params.generate_sub_targets.xcode_data:+ sub_targets[XCODE_ARGSFILES_SUB_TARGET] = [get_argsfiles_output(ctx, compiled_srcs.compile_cmds.argsfiles.xcode, XCODE_ARGSFILES_SUB_TARGET)]++ if impl_params.generate_sub_targets.clang_remarks:+ if compiled_srcs.non_pic and compiled_srcs.non_pic.clang_remarks:+ sub_targets["clang-remarks"] = [+ DefaultInfo(+ default_outputs = compiled_srcs.non_pic.clang_remarks,+ )+ ]++ if compiled_srcs.pic.clang_remarks:+ sub_targets["pic-clang-remarks"] = [+ DefaultInfo(+ default_outputs = compiled_srcs.pic.clang_remarks,+ )+ ]++ if impl_params.generate_sub_targets.clang_llvm_statistics:+ if compiled_srcs.non_pic and compiled_srcs.non_pic.clang_llvm_statistics:+ sub_targets["clang-llvm-statistics"] = [+ DefaultInfo(+ default_outputs = compiled_srcs.non_pic.clang_llvm_statistics,+ )+ ]++ if compiled_srcs.pic.clang_llvm_statistics:+ sub_targets["pic-clang-llvm-statistics"] = [+ DefaultInfo(+ default_outputs = compiled_srcs.pic.clang_llvm_statistics,+ )+ ]++ if impl_params.generate_sub_targets.clang_traces:+ traces = []+ if compiled_srcs.non_pic and compiled_srcs.non_pic.clang_traces:+ traces = compiled_srcs.non_pic.clang_traces+ sub_targets["clang-trace"] = [+ DefaultInfo(+ default_outputs = traces,+ )+ ]++ clang_traces_tset = ctx.actions.tset(+ ClangTracesTSet,+ value = traces,+ children = [info.clang_traces for info in filter_and_map_idx(ClangTracesInfo, deps_all_exported_first)],+ )+ providers.append(ClangTracesInfo(clang_traces = clang_traces_tset))++ clang_traces_args = clang_traces_tset.project_as_args("clang_traces")+ all_traces = ctx.actions.write(+ ctx.actions.declare_output("recursive_clang_traces.txt", has_content_based_path = False),+ clang_traces_args,+ )++ sub_targets["clang-traces"] = [+ DefaultInfo(+ default_output = all_traces,+ other_outputs = [clang_traces_args],+ )+ ]++ pic_traces = []+ if compiled_srcs.pic.clang_traces:+ pic_traces = compiled_srcs.pic.clang_traces+ sub_targets["pic-clang-trace"] = [+ DefaultInfo(+ default_outputs = pic_traces,+ )+ ]++ pic_clang_traces_tset = ctx.actions.tset(+ ClangTracesTSet,+ value = pic_traces,+ children = [info.clang_traces for info in filter_and_map_idx(PicClangTracesInfo, deps_all_exported_first)],+ )+ providers.append(PicClangTracesInfo(clang_traces = pic_clang_traces_tset))++ pic_clang_traces_args = pic_clang_traces_tset.project_as_args("clang_traces")+ all_pic_traces = ctx.actions.write(+ ctx.actions.declare_output("recursive_pic_clang_traces.txt", has_content_based_path = False),+ pic_clang_traces_args,+ )++ sub_targets["pic-clang-traces"] = [+ DefaultInfo(+ default_output = all_pic_traces,+ other_outputs = [pic_clang_traces_args],+ )+ ]++ all_diagnostics = None++ # Collect source diagnostics; defer check_sub_target until after header-unit diagnostics+ input_diagnostics = {}+ input_clang_tidy_diagnostics = {}+ if impl_params.generate_sub_targets.objects:+ objects_sub_targets = compiled_srcs.pic.objects_sub_targets+ if compiled_srcs.non_pic:+ objects_sub_targets = objects_sub_targets | compiled_srcs.non_pic.objects_sub_targets+ sub_targets[OBJECTS_SUBTARGET] = [DefaultInfo(sub_targets = objects_sub_targets)]+ contains_extra_diagnostics = impl_params.extra_diagnostics and len(impl_params.extra_diagnostics) > 0+ if len(compiled_srcs.pic.diagnostics) > 0 or contains_extra_diagnostics or impl_params.export_header_unit:+ input_diagnostics = compiled_srcs.pic.diagnostics+ if contains_extra_diagnostics or impl_params.export_header_unit:+ # Avoid creation of merged dict unless needed, for efficiency reasons+ input_diagnostics = dict(input_diagnostics)+ if contains_extra_diagnostics:+ input_diagnostics.update(impl_params.extra_diagnostics)+ input_clang_tidy_diagnostics = compiled_srcs.pic.clang_tidy_diagnostics++ # Compilation DB.+ if impl_params.generate_sub_targets.compilation_database:+ comp_db = create_compilation_database(ctx, compiled_srcs.compile_cmds.src_compile_cmds, "compilation-database")+ sub_targets["compilation-database"] = [comp_db]++ # Compilation DB including headers.+ comp_db = create_compilation_database(ctx, compiled_srcs.compile_cmds.comp_db_compile_cmds, "full-compilation-database")+ sub_targets["full-compilation-database"] = [comp_db]++ # comp_db_compile_cmds can include header files being compiled as C++ which should not be exposed in the [compilation-database] subtarget+ comp_db_info = None+ if impl_params.generate_providers.compilation_database:+ comp_db_info = make_compilation_db_info(compiled_srcs.compile_cmds.comp_db_compile_cmds, get_cxx_toolchain_info(ctx), get_cxx_platform_info(ctx))+ providers.append(comp_db_info)++ # Link Groups+ link_group = get_link_group(ctx)+ link_group_info = impl_params.link_group_info or get_link_group_info(ctx)++ if link_group_info:+ link_groups = link_group_info.groups+ link_group_mappings = link_group_info.mappings+ link_group_deps = [link_group_info.graph]+ link_group_libs = gather_link_group_libs(+ deps = deps_all_non_exported_first,+ )+ providers.append(link_group_info)+ else:+ link_groups = {}+ link_group_mappings = {}+ link_group_deps = []+ link_group_libs = {}+ link_group_preferred_linkage = get_link_group_preferred_linkage(link_groups.values())++ # Create the linkable graph from the library's deps, exported deps and any link group deps.+ linkable_graph_deps = deps_all_non_exported_first + link_group_deps+ deps_linkable_graph = create_linkable_graph(+ ctx,+ deps = linkable_graph_deps,+ )++ frameworks_linkable = apple_create_frameworks_linkable(ctx)+ swiftmodule_linkable = impl_params.swiftmodule_linkable+ dep_infos, link_group_map, link_execution_preference = _get_shared_library_links(+ ctx,+ partial(reduce_linkable_graph, deps_linkable_graph),+ link_group,+ link_group_mappings,+ link_group_preferred_linkage,+ link_group_libs,+ exported_deps,+ non_exported_deps,+ impl_params.force_link_group_linking,+ frameworks_linkable,+ swiftmodule_linkable,+ force_static_follows_dependents = impl_params.link_groups_force_static_follows_dependents,+ )+ if impl_params.generate_sub_targets.link_group_map and link_group_map:+ sub_targets[LINK_GROUP_MAP_DATABASE_SUB_TARGET] = [link_group_map]++ extra_static_linkables = []+ if frameworks_linkable:+ extra_static_linkables.append(frameworks_linkable)+ if swiftmodule_linkable:+ extra_static_linkables.append(swiftmodule_linkable)++ library_outputs = _form_library_outputs(+ ctx = ctx,+ impl_params = impl_params,+ compiled_srcs = compiled_srcs,+ preferred_linkage = preferred_linkage,+ dep_infos = dep_infos,+ extra_static_linkables = extra_static_linkables,+ gnu_use_link_groups = cxx_is_gnu(ctx) and bool(link_group_mappings),+ link_execution_preference = link_execution_preference,+ compile_pch = compile_pch,+ )+ shared_libs = create_flavored_shared_libraries(ctx, library_outputs.solibs)++ for link_style_output in library_outputs.outputs.values():+ if LinkableFlavor("default") not in link_style_output:+ continue++ for key in link_style_output[LinkableFlavor("default")].sub_targets.keys():+ if key in sub_targets:+ fail("The subtarget `{}` already exists!".format(key))+ sub_targets.update(link_style_output[LinkableFlavor("default")].sub_targets)++ providers.extend(library_outputs.providers)++ pic_behavior = get_cxx_toolchain_info(ctx).pic_behavior++ # This is the output style for the library's own link_strategy+preferred_linkage.+ default_output_style = get_lib_output_style(to_link_strategy(cxx_attr_link_style(ctx)), preferred_linkage, pic_behavior)++ # Output sub-targets for all output-styles.+ if impl_params.generate_sub_targets.link_style_outputs or impl_params.generate_providers.link_style_outputs:+ default_output_style_providers = []+ for output_style in get_output_styles_for_linkage(preferred_linkage):+ output = library_outputs.outputs.get(output_style, {}).get(LinkableFlavor("default"), None)+ output_style_sub_targets, output_style_providers = impl_params.output_style_sub_targets_and_providers_factory(+ output_style,+ ctx,+ output,+ )+ if output != None and output.unstripped != None:+ output_style_providers.append(+ UnstrippedLinkOutputInfo(artifact = output.unstripped),+ )++ if output:+ # Add any subtargets for this output style.+ output_style_sub_targets.update(output.sub_targets)++ if impl_params.generate_sub_targets.link_style_outputs:+ if output:+ sub_targets[subtarget_for_output_style(output_style)] = [+ DefaultInfo(+ default_output = output.default,+ other_outputs = output.other,+ sub_targets = output_style_sub_targets,+ )+ ] + (output_style_providers if output_style_providers else [])++ if output_style == default_output_style:+ # If we have additional providers for the current link style,+ # add them to the list of default providers+ # TODO(cjhopman): This looks like a bug, adding to providers probably shouldn't depend on generate_sub_target.link_style_outputs+ default_output_style_providers += output_style_providers++ # In addition, ensure any subtargets for the active link style+ # can be accessed as a default subtarget+ for output_style_sub_target_name, output_style_sub_target_providers in output_style_sub_targets.items():+ sub_targets[output_style_sub_target_name] = output_style_sub_target_providers++ if impl_params.generate_providers.link_style_outputs:+ providers += default_output_style_providers++ # Create the default output for the library rule given it's link style and preferred linkage+ # It's possible for a library to not produce any output, for example, a header only library doesn't produce any archive or shared lib+ default_output = library_outputs.outputs.get(default_output_style, {}).get(LinkableFlavor("default"), None)++ if default_output and default_output.bitcode_bundle:+ sub_targets["bitcode"] = [DefaultInfo(default_output = default_output.bitcode_bundle.artifact)]++ # Define the xcode data sub target+ xcode_data_info = None+ if impl_params.generate_sub_targets.xcode_data:+ xcode_data_default_info, xcode_data_info = generate_xcode_data(+ ctx,+ rule_type = impl_params.rule_type,+ output = default_output.default if default_output else None,+ populate_rule_specific_attributes_func = impl_params.cxx_populate_xcode_attributes_func,+ srcs = impl_params.srcs + impl_params.additional.srcs,+ argsfiles = compiled_srcs.compile_cmds.argsfiles.xcode,+ product_name = get_default_cxx_library_product_name(ctx, impl_params),+ )+ sub_targets[XCODE_DATA_SUB_TARGET] = xcode_data_default_info+ providers.append(xcode_data_info)++ # Propagate link info provider.+ if impl_params.generate_providers.merged_native_link_info or impl_params.generate_providers.template_placeholders:+ # Gather link inputs.+ # Windows needs to include a linkable PCH object, this is not required for other platforms+ inherited_non_exported_link = cxx_inherited_link_info(non_exported_deps + filter(None, [impl_params.precompiled_header]))+ inherited_exported_link = cxx_inherited_link_info(exported_deps)++ merged_native_link_info = create_merged_link_info(+ ctx,+ pic_behavior,+ # Add link info for each link style,+ library_outputs.link_infos,+ preferred_linkage = preferred_linkage,+ # Export link info from non-exported deps (when necessary).+ deps = inherited_non_exported_link,+ # Export link info from out (exported) deps.+ exported_deps = inherited_exported_link,+ frameworks_linkable = frameworks_linkable,+ swiftmodule_linkable = swiftmodule_linkable,+ )+ if impl_params.generate_providers.merged_native_link_info:+ providers.append(merged_native_link_info)+ else:+ # This code sets merged_native_link_info only in some cases, leaving it unassigned in others.+ # Add a fake definition set to None so the assignment checker is satisfied.+ merged_native_link_info = None+ inherited_non_exported_link = None+ inherited_exported_link = None++ # Propagate shared libraries up the tree.+ if impl_params.generate_providers.shared_libraries:+ providers.append(+ merge_shared_libraries(+ ctx.actions,+ shared_libs,+ filter_and_map_idx(SharedLibraryInfo, deps_all_non_exported_first),+ )+ )+ providers.append(+ create_unix_env_info(+ actions = ctx.actions,+ env = UnixEnv(+ label = ctx.label,+ native_libs = [shared_libs],+ ),+ deps = deps_all_exported_first,+ ),+ )++ propagated_preprocessor_merge_list = inherited_exported_preprocessor_infos+ if _attr_reexport_all_header_dependencies(ctx):+ propagated_preprocessor_merge_list = inherited_non_exported_preprocessor_infos + propagated_preprocessor_merge_list++ # Header unit PCM.+ header_unit_diagnostics = {}+ if impl_params.generate_sub_targets.header_unit:+ if compiled_srcs.header_unit_preprocessors:+ header_unit_preprocessors = []+ header_unit_sub_targets = []+ header_unit_clang_traces = []++ def header_unit_clang_trace_sub_target(clang_traces):+ if impl_params.generate_sub_targets.clang_traces:+ return {+ "clang-trace": [+ DefaultInfo(default_outputs = clang_traces),+ ],+ }+ else:+ return {}++ def add_header_unit_clang_trace_sub_target(clang_traces):+ header_unit_clang_traces.extend(clang_traces)+ return header_unit_clang_trace_sub_target(clang_traces)++ def add_header_unit_check_sub_target(group_diagnostics, header_unit_group_idx):+ if group_diagnostics:+ header_unit_diagnostics.update(group_diagnostics)+ group_check_providers, _ = check_sub_target(+ ctx,+ group_diagnostics,+ error_handler = impl_params.error_handler,+ output_name = "header_unit{}.diagnostics.txt".format(header_unit_group_idx),+ )+ return {+ "check": group_check_providers,+ }+ else:+ return {}++ header_unit_group_idx = 0+ for x in compiled_srcs.header_unit_preprocessors:+ header_unit_preprocessors.append(x)+ header_unit_group_idx += 1+ header_unit_sub_targets.append([+ DefaultInfo(+ default_outputs = [h.module for h in x.header_units],+ sub_targets = (+ add_header_unit_clang_trace_sub_target(filter(None, [h.clang_trace for h in x.header_units]))+ | add_header_unit_check_sub_target(+ {h.name: h.diagnostics for h in x.header_units if h.diagnostics != None}, header_unit_group_idx+ )+ ),+ ),+ cxx_merge_cpreprocessors(+ ctx.actions,+ own_exported_preprocessors + header_unit_preprocessors,+ propagated_preprocessor_merge_list,+ ),+ ])++ # Build [header-unit][check] from all header unit diagnostics+ header_unit_check_sub = {}+ if header_unit_diagnostics:+ header_unit_check_providers, _ = check_sub_target(+ ctx,+ header_unit_diagnostics,+ error_handler = impl_params.error_handler,+ output_name = "header_unit_diagnostics.txt",+ )+ header_unit_check_sub["check"] = header_unit_check_providers+ sub_targets["header-unit"] = [+ DefaultInfo(+ default_outputs = [h.module for x in header_unit_preprocessors for h in x.header_units],+ sub_targets = {str(i): x for i, x in enumerate(header_unit_sub_targets)}+ | header_unit_clang_trace_sub_target(header_unit_clang_traces)+ | header_unit_check_sub,+ ),+ header_unit_sub_targets[-1][1],+ ]+ if impl_params.export_header_unit:+ own_exported_preprocessors.extend(header_unit_preprocessors)+ else:+ sub_targets["header-unit"] = [+ EMPTY_DEFAULT_INFO,+ cxx_merge_cpreprocessors(+ ctx.actions,+ own_exported_preprocessors,+ propagated_preprocessor_merge_list,+ ),+ ]++ # Build [check]: syntax diagnostics + header unit diagnostics in default output.+ # Clang-tidy diagnostics are accessible as per-file sub_targets only.+ if impl_params.export_header_unit:+ input_diagnostics.update(header_unit_diagnostics)+ if len(input_diagnostics) > 0:+ sub_targets["check"], all_diagnostics = check_sub_target(+ ctx,+ input_diagnostics,+ error_handler = impl_params.error_handler,+ extra_sub_targets = input_clang_tidy_diagnostics,+ )++ # Build [check-all]: syntax + clang-tidy + header unit diagnostics+ # (always includes header-unit diagnostics regardless of export_header_unit).+ check_all_diagnostics = dict(input_diagnostics)+ check_all_diagnostics.update(input_clang_tidy_diagnostics)+ if header_unit_diagnostics:+ check_all_diagnostics.update(header_unit_diagnostics)+ if len(check_all_diagnostics) > len(input_diagnostics):+ check_all_subtarget_result = check_sub_target(+ ctx,+ check_all_diagnostics,+ error_handler = impl_params.error_handler,+ output_name = "all_diagnostics.txt",+ )+ sub_targets["check-all"] = check_all_subtarget_result[0]++ propagated_preprocessor = cxx_merge_cpreprocessors(+ ctx.actions,+ own_exported_preprocessors,+ propagated_preprocessor_merge_list,+ )+ if impl_params.generate_providers.preprocessors:+ providers.append(propagated_preprocessor)++ # Propagated_exported_preprocessor_info is used for pcm compilation, which isn't possible for non-modular targets.+ propagated_exported_preprocessor_info = propagated_preprocessor if impl_params.rule_type == "apple_library" and ctx.attrs.modular else None+ additional_providers = (+ impl_params.additional.additional_providers_factory(propagated_exported_preprocessor_info)+ if impl_params.additional.additional_providers_factory+ else []+ )++ if impl_params.generate_providers.third_party_build:+ third_party_build_info = create_third_party_build_info(+ ctx = ctx,+ cxx_headers = [propagated_preprocessor],+ shared_libs = shared_libs.libraries,+ deps = deps_all_exported_first,+ project = ctx.attrs.third_party_project,+ )+ providers.append(third_party_build_info)+ sub_targets["third-party-build"] = [+ DefaultInfo(+ default_output = third_party_build_info.build.root.artifact,+ sub_targets = dict(+ manifest = [DefaultInfo(default_output = third_party_build_info.build.manifest)],+ ),+ ),+ ]++ # For v1's `#headers` functionality.+ if impl_params.generate_sub_targets.headers:+ sub_targets["headers"] = [+ propagated_preprocessor,+ create_merged_link_info(+ ctx,+ pic_behavior = pic_behavior,+ preferred_linkage = Linkage("static"),+ frameworks_linkable = frameworks_linkable,+ swiftmodule_linkable = swiftmodule_linkable,+ ),+ EMPTY_LINK_GROUP_LIB_INFO,+ EMPTY_SHARED_LIBRARY_INFO,+ ] + additional_providers++ if getattr(ctx.attrs, "supports_header_symlink_subtarget", False):+ package_prefix = str(ctx.label.path)+ header_symlink_mapping = {}+ for records in propagated_preprocessor.set.traverse():+ for record in records:+ for header in record.headers:+ header_path = header.name+ if header.namespace:+ header_path = paths.join(header.namespace, header_path)+ header_symlink_mapping[paths.normalize(header_path)] = header.artifact++ all_include_dirs = record.include_dirs + (record.system_include_dirs.include_dirs if record.system_include_dirs else [])+ for header in record.raw_headers:+ full_header_path = paths.join(package_prefix, header.short_path)+ for include_dir in all_include_dirs:+ include_dir_path = str(include_dir)++ if not paths.starts_with(full_header_path, include_dir_path):+ continue++ mapping_path = paths.relativize(full_header_path, include_dir_path)+ header_symlink_mapping[mapping_path] = header++ sub_targets["header-symlink-tree"] = [+ DefaultInfo(+ default_output = ctx.actions.symlinked_dir("header_symlink_tree", header_symlink_mapping, has_content_based_path = False),+ )+ ]++ for additional_subtarget, subtarget_providers in impl_params.additional.subtargets.items():+ sub_targets[additional_subtarget] = subtarget_providers++ index_stores = []+ swift_index_stores = []+ if impl_params.index_stores:+ # Index store from swift compile+ index_stores.extend(impl_params.index_stores)+ swift_index_stores.extend(impl_params.index_stores)++ # Index stores from cxx compile. We only generate the index store for pic+ if compiled_srcs.pic:+ index_stores.extend(compiled_srcs.pic.index_stores)++ index_store_subtargets, index_store_info = create_index_store_subtargets_and_provider(ctx, index_stores, swift_index_stores, deps_all_non_exported_first)+ sub_targets.update(index_store_subtargets)+ providers.append(index_store_info)++ mod_dep_graph_subtargets, mod_dep_graph_info = create_modularization_dep_graph_subtargets_and_provider(+ ctx,+ impl_params.modularization_dependency_graph,+ deps_all_non_exported_first,+ )+ sub_targets.update(mod_dep_graph_subtargets)+ providers.append(mod_dep_graph_info)++ linker_flags = cxx_attr_linker_flags_all(ctx, impl_params.cxx_flags)++ # Omnibus root provider.+ linkable_root = None+ if impl_params.generate_providers.omnibus_root:+ if impl_params.use_soname:+ soname = _soname(ctx, impl_params)+ else:+ soname = None+ linker_type = get_cxx_toolchain_info(ctx).linker_info.type+ linkable_root = create_linkable_root(+ label = ctx.label,+ name = soname,+ link_infos = LinkInfos(+ default = LinkInfo(+ pre_flags = linker_flags.flags + linker_flags.exported_flags,+ post_flags = linker_flags.post_flags + linker_flags.exported_post_flags,+ linkables = [+ ObjectsLinkable(+ objects = compiled_srcs.pic.objects,+ linker_type = linker_type,+ link_whole = True,+ )+ ],+ external_debug_info = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ artifacts = (+ compiled_srcs.pic.external_debug_info + (compiled_srcs.pic.objects if compiled_srcs.pic.objects_have_external_debug_info else [])+ ),+ children = impl_params.additional.static_external_debug_info,+ ),+ has_hip_device_debug = compiled_srcs.pic.has_hip_device_debug,+ hip_arch_debug_files = compiled_srcs.pic.hip_arch_debug_files,+ metadata = cxx_attr_dep_metadata(ctx),+ ),+ stripped = LinkInfo(+ pre_flags = linker_flags.flags + linker_flags.exported_flags,+ post_flags = linker_flags.post_flags + linker_flags.exported_post_flags,+ linkables = [+ ObjectsLinkable(+ objects = compiled_srcs.pic.stripped_objects,+ linker_type = linker_type,+ link_whole = True,+ )+ ],+ has_hip_device_debug = compiled_srcs.pic.has_hip_device_debug,+ hip_arch_debug_files = compiled_srcs.pic.hip_arch_debug_files,+ metadata = cxx_attr_dep_metadata(ctx),+ ),+ ),+ deps = deps_all_non_exported_first,+ )+ providers.append(linkable_root)++ # Mark libraries that support `dlopen`.+ if getattr(ctx.attrs, "supports_python_dlopen", False):+ providers.append(DLOPENABLE_LIBRARY_INFO_MARKER)++ # Augment and provide the linkable graph.+ if impl_params.generate_providers.linkable_graph:+ merged_linkable_graph = create_linkable_graph(+ ctx,+ node = create_linkable_graph_node(+ ctx,+ linkable_node = create_linkable_node(+ ctx = ctx,+ default_soname = _soname(ctx, impl_params),+ preferred_linkage = preferred_linkage,+ default_link_strategy = _link_strategy_for_some_shared_links(ctx.attrs),+ deps = non_exported_deps,+ exported_deps = exported_deps,+ # If we don't have link input for this link style, we pass in `None` so+ # that omnibus knows to avoid it.+ include_in_android_mergemap = getattr(ctx.attrs, "include_in_android_merge_map_output", True) and default_output != None,+ # Attach this library's per-source compile commands so app rules can aggregate a+ # native compile-command database. Gated (default off) to keep this off the graph+ # for normal builds; see _emit_native_build_commands.+ compile_cmds = compiled_srcs.compile_cmds.src_compile_cmds if getattr(ctx.attrs, "_emit_native_build_commands", False) else [],+ link_infos = library_outputs.link_infos,+ shared_libs = shared_libs,+ linker_flags = linker_flags,+ can_be_asset = getattr(ctx.attrs, "can_be_asset", False) or False,+ stub = getattr(ctx.attrs, "stub", False),+ ),+ excluded = {ctx.label: None} if not value_or(ctx.attrs.supports_merged_linking, True) else {},+ ),+ deps = linkable_graph_deps,+ )+ providers.append(merged_linkable_graph)++ # C++ resource.+ if impl_params.generate_providers.resources:+ resources = cxx_attr_resources(ctx)+ providers.append(+ make_resource_info(+ gather_resources(+ label = ctx.label,+ resources = resources,+ deps = deps_all_non_exported_first,+ ),+ ),+ )+ if impl_params.generate_providers.cxx_resources_as_apple_resources:+ apple_resource_graph = create_resource_graph(+ ctx = ctx,+ labels = ctx.attrs.labels,+ deps = non_exported_deps,+ exported_deps = exported_deps,+ cxx_resource_spec = CxxResourceSpec(resources = resources) if resources else None,+ )+ providers.append(apple_resource_graph)++ if impl_params.generate_providers.template_placeholders:+ templ_vars = {}++ # Some rules, e.g. fbcode//thrift/lib/cpp:thrift-core-module+ # define preprocessor flags as things like: -DTHRIFT_PLATFORM_CONFIG=<thrift/facebook/PlatformConfig.h>+ # and unless they get quoted, they break shell syntax.+ cxx_compiler_info = get_cxx_toolchain_info(ctx).cxx_compiler_info+ cxx_preprocessor_flags = cmd_args(+ cmd_args(cxx_compiler_info.preprocessor_flags or [], quote = "shell"),+ cmd_args(propagated_preprocessor.set.project_as_args("args"), quote = "shell"),+ propagated_preprocessor.set.project_as_args("include_dirs"),+ )+ templ_vars["cxxppflags"] = cxx_preprocessor_flags++ c_compiler_info = get_cxx_toolchain_info(ctx).c_compiler_info+ c_preprocessor_flags = cmd_args(+ cmd_args(c_compiler_info.preprocessor_flags or [], quote = "shell"),+ cmd_args(propagated_preprocessor.set.project_as_args("args"), quote = "shell"),+ propagated_preprocessor.set.project_as_args("include_dirs"),+ )+ templ_vars["cppflags"] = c_preprocessor_flags++ # Add in ldflag macros.+ for link_strategy in (LinkStrategy("static"), LinkStrategy("static_pic")):+ name = "ldflags-" + link_strategy.value.replace("_", "-")+ args = []+ linker_info = get_cxx_toolchain_info(ctx).linker_info+ args.append(linker_info.linker_flags or [])++ # Normally, we call get_link_args_for_strategy for getting the args for our own link from our+ # deps. This case is a bit different as we are effectively trying to get the args for how this library+ # would be represented on a dependent's link line and so it is appropriate to use our own merged_native_link_info.+ link_args = get_link_args_for_strategy(+ ctx.actions,+ ctx.label,+ get_cxx_toolchain_info(ctx).linker_info,+ [merged_native_link_info],+ link_strategy,+ prefer_stripped = False,+ transformation_spec_context = None,+ )+ args.append(unpack_link_args(link_args))+ templ_vars[name] = cmd_args(args)++ # TODO(T110378127): To implement `$(ldflags-shared ...)` properly, we'd need+ # to setup a symink tree rule for all transitive shared libs. Since this+ # currently would be pretty costly (O(N^2)?), and since it's not that+ # commonly used anyway, just use `static-pic` instead. Longer-term, once+ # v1 is gone, macros that use `$(ldflags-shared ...)` (e.g. Haskell's+ # hsc2hs) can move to a v2 rules-based API to avoid needing this macro.+ templ_vars["ldflags-shared"] = templ_vars["ldflags-static-pic"]++ providers.append(TemplatePlaceholderInfo(keyed_variables = templ_vars))++ # It is possible (e.g. in a java binary or an Android APK) to have C++ libraries that depend+ # upon Java libraries (through JNI). In some cases those Java libraries are not depended upon+ # anywhere else, so we need to expose them here to ensure that they are packaged into the+ # final binary.+ if impl_params.generate_providers.java_packaging_info:+ providers.append(get_java_packaging_info(ctx, deps_all_non_exported_first))++ if impl_params.generate_providers.java_global_code_info:+ providers.append(propagate_global_code_info(ctx, ctx.attrs.deps + getattr(ctx.attrs, "exported_deps", [])))++ # TODO(T107163344) this shouldn't be in cxx_library itself, use overlays to remove it.+ if impl_params.generate_providers.android_packageable_info:+ providers.append(merge_android_packageable_info(ctx.label, ctx.actions, deps_all_non_exported_first))++ bitcode_bundle = default_output.bitcode_bundle if default_output != None else None+ if bitcode_bundle:+ bc_provider = BitcodeBundleInfo(bitcode = bitcode_bundle, bitcode_bundle = ctx.actions.tset(BitcodeTSet, value = bitcode_bundle))+ additional_providers.append(bc_provider)++ # Add prefer-static and prefer-shared sub-targets for dependent-specific linkage control.+ # These expose the library with different preferred linkages, allowing dependents to+ # explicitly choose static or shared linking regardless of the library's default.+ if impl_params.generate_providers.merged_native_link_info:+ for linkage in (Linkage("static"), Linkage("shared")):+ # Get the appropriate output for this linkage+ linkage_output_style = get_lib_output_style(to_link_strategy(cxx_attr_link_style(ctx)), linkage, pic_behavior)+ linkage_output = library_outputs.outputs.get(linkage_output_style, {}).get(LinkableFlavor("default"), None)++ # Create MergedLinkInfo with this linkage (reuses inherited_*_link from above)+ linkage_merged_link_info = create_merged_link_info(+ ctx,+ pic_behavior,+ library_outputs.link_infos,+ preferred_linkage = linkage,+ deps = inherited_non_exported_link,+ exported_deps = inherited_exported_link,+ frameworks_linkable = frameworks_linkable,+ swiftmodule_linkable = swiftmodule_linkable,+ )++ # Check if we have the required output styles for this linkage+ required_output_styles = get_output_styles_for_linkage(linkage)+ has_required_outputs = True+ for style in required_output_styles:+ if style not in library_outputs.link_infos:+ has_required_outputs = False+ break++ # Include all providers needed for this sub-target to be usable as a dependency+ linkage_providers = [+ linkage_merged_link_info,+ propagated_preprocessor,+ EMPTY_LINK_GROUP_LIB_INFO,+ EMPTY_SHARED_LIBRARY_INFO,+ ]++ # Only create LinkableGraph if we have all required output styles for this linkage+ if has_required_outputs and impl_params.generate_providers.linkable_graph:+ linkage_linkable_graph = create_linkable_graph(+ ctx,+ node = create_linkable_graph_node(+ ctx,+ linkable_node = create_linkable_node(+ ctx = ctx,+ default_soname = _soname(ctx, impl_params),+ preferred_linkage = linkage,+ default_link_strategy = _link_strategy_for_some_shared_links(ctx.attrs),+ deps = non_exported_deps,+ exported_deps = exported_deps,+ include_in_android_mergemap = getattr(ctx.attrs, "include_in_android_merge_map_output", True) and default_output != None,+ compile_cmds = compiled_srcs.compile_cmds.src_compile_cmds if getattr(ctx.attrs, "_emit_native_build_commands", False) else [],+ link_infos = library_outputs.link_infos,+ shared_libs = shared_libs,+ linker_flags = linker_flags,+ can_be_asset = getattr(ctx.attrs, "can_be_asset", False) or False,+ stub = getattr(ctx.attrs, "stub", False),+ ),+ excluded = {ctx.label: None} if not value_or(ctx.attrs.supports_merged_linking, True) else {},+ ),+ deps = linkable_graph_deps,+ )+ linkage_providers.append(linkage_linkable_graph)+ if linkage_output:+ linkage_providers.append(+ DefaultInfo(+ default_output = linkage_output.default,+ )+ )+ sub_targets["prefer-{}".format(linkage.value)] = linkage_providers++ xplugins_usage_info = get_xplugins_usage_info(ctx.actions, deps_all_non_exported_first)+ if xplugins_usage_info:+ providers.append(xplugins_usage_info)++ xplugins_debug_info = xplugins_get_debug_artifacts_info(+ ctx,+ deps_all_non_exported_first,+ )+ if xplugins_debug_info:+ providers.append(xplugins_debug_info)++ if TARGET_STATS_ENABLED:+ target_stats_tools = get_cxx_toolchain_info(ctx).target_stats_tools+ if target_stats_tools != None:+ # Keyed by each file's path within the target, which is what a+ # consumer can line up against the target's own source list.+ target_stats_srcs = {src.file.short_path: src.file for src in impl_params.srcs + impl_params.additional.srcs}+ target_stats_srcs.update(impl_params.target_stats_extra_srcs)+ target_stats_providers, target_stats_subtargets = target_stats_providers_and_subtargets(+ ctx,+ tools = target_stats_tools,+ srcs = target_stats_srcs,+ deps = non_exported_deps + exported_deps,+ cycle_mode = CycleMode(impl_params.target_stats_cycle_mode),+ module_name = impl_params.target_stats_module_name or ctx.label.name,+ swift_dot = impl_params.target_stats_swift_dot,+ )+ providers.extend(target_stats_providers)+ sub_targets.update(target_stats_subtargets)++ if impl_params.generate_providers.default:+ if False:+ # TODO(nga): `default_output.unstripped` is never `None`.+ def unknown():+ pass++ default_output = unknown()++ default_info = DefaultInfo(+ default_output = default_output.default if default_output != None else None,+ other_outputs = default_output.other if default_output != None else [],+ sub_targets = sub_targets,+ )+ providers.append(default_info)++ # Propagate all transitive link group lib roots up the tree, so that the+ # final executable can use them.+ if impl_params.generate_providers.merged_native_link_info:+ providers.append(+ merge_link_group_lib_info(+ label = ctx.label,+ name = link_group,+ shared_libs = shared_libs,+ shared_link_infos = library_outputs.link_infos.get(LibOutputStyle("shared_lib")),+ deps = deps_all_exported_first,+ ),+ )++ if impl_params.generate_providers.transitive_diagnostics:+ providers.append(+ cxx_transitive_diagnostics_combine(+ ctx = ctx,+ diagnostics = filter(None, [all_diagnostics]) + impl_params.extra_transitive_diagnostics,+ deps = deps_all_exported_first,+ )+ )++ if getattr(ctx.attrs, "_meta_apple_library_validation_enabled", False):+ providers.append(+ CxxLibraryInfo(+ target = ctx.label,+ labels = ctx.attrs.labels,+ ),+ )++ providers.extend(additional_providers)++ return _CxxLibraryParameterizedOutput(+ default_output = default_output,+ all_outputs = library_outputs,+ sub_targets = sub_targets,+ bitcode_bundle = bitcode_bundle,+ providers = providers,+ index_store_info = index_store_info,+ modularization_dep_graph_info = mod_dep_graph_info,+ xcode_data_info = xcode_data_info,+ cxx_compilationdb_info = comp_db_info,+ linkable_root = linkable_root,+ sanitizer_runtime_files = library_outputs.sanitizer_runtime_files,+ )++def get_default_cxx_library_product_name(ctx, impl_params) -> str:+ preferred_linkage = cxx_attr_preferred_linkage(ctx)+ output_style = get_lib_output_style(+ to_link_strategy(cxx_attr_link_style(ctx)),+ preferred_linkage,+ get_cxx_toolchain_info(ctx).pic_behavior,+ )+ if output_style == LibOutputStyle("shared_lib"):+ return _soname(ctx, impl_params)+ else:+ return _base_static_library_name(ctx, optimized = False, debuggable = False, stripped = False)++def _collect_hip_arch_debug_files(outs: list[CxxCompileOutput]) -> dict[str, list[Artifact]]:+ result = {}+ for out in outs:+ for arch, f in out.hip_arch_debug_files.items():+ result.setdefault(arch, [])+ result[arch].append(f)+ return result++def _get_library_compile_output(+ actions: AnalysisActions,+ cxx_toolchain_info: CxxToolchainInfo,+ src_compile_cmds: list[CxxSrcCompileCommand],+ outs: list[CxxCompileOutput],+ extra_link_input: list[Artifact],+ supports_stripping: bool,+ has_content_based_path: bool,+) -> _CxxLibraryCompileOutput:+ objects = [out.object for out in outs]+ stripped_objects = _strip_objects(actions, cxx_toolchain_info, outs, supports_stripping, has_content_based_path)++ pch_object_output = [out.pch_object for out in outs if out.pch_object]++ bitcode_objects = [out.object for out in outs if is_bitcode_format(out.object_format)]+ if len(bitcode_objects) == 0:+ bitcode_objects = None++ objects_sub_targets = cxx_objects_sub_targets(outs)++ # add this after setting up sub_targets+ objects += extra_link_input+ stripped_objects += extra_link_input++ index_stores = [out.index_store for out in outs if out.index_store]++ diagnostics = {compile_cmd.src.short_path: out.diagnostics for compile_cmd, out in zip(src_compile_cmds, outs) if out.diagnostics != None}+ clang_tidy_diagnostics = {+ compile_cmd.src.short_path + ".clang-tidy": out.clang_tidy_diagnostics+ for compile_cmd, out in zip(src_compile_cmds, outs)+ if out.clang_tidy_diagnostics != None+ }++ return _CxxLibraryCompileOutput(+ objects = objects,+ pch_object_output = pch_object_output,+ stripped_objects = stripped_objects,+ bitcode_objects = bitcode_objects,+ clang_traces = [out.clang_trace for out in outs if out.clang_trace != None],+ clang_remarks = [out.clang_remarks for out in outs if out.clang_remarks != None],+ clang_llvm_statistics = [out.clang_llvm_statistics for out in outs if out.clang_llvm_statistics != None],+ gcno_files = [out.gcno_file for out in outs if out.gcno_file != None],+ external_debug_info = [out.external_debug_info for out in outs if out.external_debug_info != None],+ objects_have_external_debug_info = lazy.is_any(lambda out: out.object_has_external_debug_info, outs),+ has_hip_device_debug = lazy.is_any(lambda out: out.hip_device_debug, outs),+ hip_arch_debug_files = _collect_hip_arch_debug_files(outs),+ objects_sub_targets = objects_sub_targets,+ index_stores = index_stores,+ diagnostics = diagnostics,+ clang_tidy_diagnostics = clang_tidy_diagnostics,+ )++_CxxSharedLibraryResult = record(+ # Result from link, includes the shared lib, linker map data etc+ link_result = CxxLinkResult,+ # Shared library name (e.g. SONAME)+ soname = str,+ # `LinkInfo` used to link against the shared library.+ info = LinkInfo,+)++def cxx_compile_srcs(+ actions: AnalysisActions,+ target_label: Label,+ cxx_toolchain_info: CxxToolchainInfo,+ impl_params: CxxRuleConstructorParams,+ own_preprocessors: list[CPreprocessor],+ inherited_non_exported_preprocessor_infos: list[CPreprocessorInfo],+ inherited_exported_preprocessor_infos: list[CPreprocessorInfo],+ preferred_linkage: Linkage,+ add_coverage_instrumentation_compiler_flags: bool,+ compile_pch: CxxPrecompiledHeader | None = None,+ own_exported_preprocessors: list[CPreprocessor] = [],+ filename_prefix: str = "",+) -> _CxxCompiledSourcesOutput:+ """+ Compile objects we'll need for archives and shared libraries.+ """++ # Create the commands and argsfiles to use for compiling each source file+ compile_cmd_output = create_compile_cmds(+ actions = actions,+ target_label = target_label,+ toolchain = cxx_toolchain_info,+ impl_params = impl_params,+ own_preprocessors = own_preprocessors,+ inherited_preprocessor_infos = inherited_non_exported_preprocessor_infos + inherited_exported_preprocessor_infos,+ add_coverage_instrumentation_compiler_flags = add_coverage_instrumentation_compiler_flags,+ compile_pch = compile_pch,+ filename_prefix = filename_prefix,+ )++ # Define header unit.+ header_unit_preprocessors = []+ if own_exported_preprocessors:+ header_preprocessor_info = cxx_merge_cpreprocessors(+ actions,+ own_exported_preprocessors,+ inherited_exported_preprocessor_infos,+ )+ header_unit_preprocessors.extend(+ precompile_cxx(+ actions = actions,+ target_label = target_label,+ toolchain = cxx_toolchain_info,+ impl_params = impl_params,+ preprocessors = own_exported_preprocessors,+ header_preprocessor_info = header_preprocessor_info,+ )+ )++ # Define object files.+ pic_cxx_outs = compile_cxx(+ actions = actions,+ target_label = target_label,+ toolchain = cxx_toolchain_info,+ src_compile_cmds = compile_cmd_output.src_compile_cmds,+ flavors = set([CxxCompileFlavor("pic")]),+ provide_syntax_only = True,+ separate_debug_info = impl_params.separate_debug_info,+ use_header_units = impl_params.use_header_units,+ precompiled_header = impl_params.precompiled_header,+ compile_pch = compile_pch,+ cuda_compile_style = impl_params.cuda_compile_style,+ )+ pic = _get_library_compile_output(+ actions = actions,+ cxx_toolchain_info = cxx_toolchain_info,+ src_compile_cmds = compile_cmd_output.src_compile_cmds,+ outs = pic_cxx_outs,+ extra_link_input = impl_params.extra_link_input,+ supports_stripping = impl_params.supports_stripping,+ has_content_based_path = impl_params.use_content_based_paths,+ )++ non_pic = None+ pic_optimized = None+ if preferred_linkage != Linkage("shared"):+ non_pic_cxx_outs = compile_cxx(+ actions = actions,+ target_label = target_label,+ toolchain = cxx_toolchain_info,+ src_compile_cmds = compile_cmd_output.src_compile_cmds,+ flavors = set(),+ # Diagnostics from the pic and non-pic compilation would be+ # identical. We can avoid instantiating a second set of actions.+ provide_syntax_only = False,+ separate_debug_info = impl_params.separate_debug_info,+ compile_pch = compile_pch,+ precompiled_header = impl_params.precompiled_header,+ use_header_units = impl_params.use_header_units,+ cuda_compile_style = impl_params.cuda_compile_style,+ )+ non_pic = _get_library_compile_output(+ actions = actions,+ cxx_toolchain_info = cxx_toolchain_info,+ src_compile_cmds = compile_cmd_output.src_compile_cmds,+ outs = non_pic_cxx_outs,+ extra_link_input = impl_params.extra_link_input,+ supports_stripping = impl_params.supports_stripping,+ has_content_based_path = impl_params.use_content_based_paths,+ )++ if toolchain_supports_flavor(cxx_toolchain_info, CxxCompileFlavor("optimized")):+ optimized_cxx_outs = compile_cxx(+ actions = actions,+ target_label = target_label,+ toolchain = cxx_toolchain_info,+ src_compile_cmds = compile_cmd_output.src_compile_cmds,+ flavors = set([CxxCompileFlavor("pic"), CxxCompileFlavor("optimized")]),+ # Diagnostics from the pic and non-pic compilation would be+ # identical. We can avoid instantiating a second set of actions.+ provide_syntax_only = False,+ separate_debug_info = impl_params.separate_debug_info,+ use_header_units = impl_params.use_header_units,+ cuda_compile_style = impl_params.cuda_compile_style,+ )+ pic_optimized = _get_library_compile_output(+ actions = actions,+ cxx_toolchain_info = cxx_toolchain_info,+ src_compile_cmds = compile_cmd_output.src_compile_cmds,+ outs = optimized_cxx_outs,+ extra_link_input = impl_params.extra_link_input,+ supports_stripping = impl_params.supports_stripping,+ has_content_based_path = impl_params.use_content_based_paths,+ )++ pic_debuggable = None+ if toolchain_supports_flavor(cxx_toolchain_info, CxxCompileFlavor("debug")):+ debuggable_cxx_outs = compile_cxx(+ actions = actions,+ target_label = target_label,+ toolchain = cxx_toolchain_info,+ src_compile_cmds = compile_cmd_output.src_compile_cmds,+ flavors = set([CxxCompileFlavor("pic"), CxxCompileFlavor("debug")]),+ # Diagnostics from the pic and non-pic compilation would be+ # identical. We can avoid instantiating a second set of actions.+ provide_syntax_only = False,+ separate_debug_info = impl_params.separate_debug_info,+ use_header_units = impl_params.use_header_units,+ cuda_compile_style = impl_params.cuda_compile_style,+ )+ pic_debuggable = _get_library_compile_output(+ actions = actions,+ cxx_toolchain_info = cxx_toolchain_info,+ src_compile_cmds = compile_cmd_output.src_compile_cmds,+ outs = debuggable_cxx_outs,+ extra_link_input = impl_params.extra_link_input,+ supports_stripping = impl_params.supports_stripping,+ has_content_based_path = impl_params.use_content_based_paths,+ )+ return _CxxCompiledSourcesOutput(+ compile_cmds = compile_cmd_output,+ pic = pic,+ pic_optimized = pic_optimized,+ pic_debuggable = pic_debuggable,+ non_pic = non_pic,+ header_unit_preprocessors = header_unit_preprocessors,+ )++def _form_library_outputs(+ ctx: AnalysisContext,+ impl_params: CxxRuleConstructorParams,+ compiled_srcs: _CxxCompiledSourcesOutput,+ preferred_linkage: Linkage,+ dep_infos: LinkArgs,+ extra_static_linkables: list[[FrameworksLinkable, SwiftmoduleLinkable]],+ gnu_use_link_groups: bool,+ link_execution_preference: LinkExecutionPreference,+ compile_pch: CxxPrecompiledHeader | None,+) -> _CxxAllLibraryOutputs:+ # Build static/shared libs and the link info we use to export them to dependents.+ outputs = {}+ solibs = {}+ link_infos = {}+ providers = []+ sanitizer_runtime_files = []+ gcno_files = []++ linker_info = get_cxx_toolchain_info(ctx).linker_info+ linker_flags = cxx_attr_linker_flags_all(ctx, impl_params.cxx_flags)++ # Add in exported linker flags.+ def ldflags(inner: LinkInfo) -> LinkInfo:+ exported_flags, exported_post_flags = sandbox_exported_linker_flags(+ linker_info,+ linker_flags.exported_flags,+ linker_flags.exported_post_flags,+ )+ return wrap_link_info(+ inner = inner,+ pre_flags = exported_flags,+ post_flags = exported_post_flags,+ )++ def build_static_library(+ compile_output: _CxxLibraryCompileOutput | None, pic: bool, optimized: bool, debuggable: bool, pch: bool, stripped: bool+ ) -> (CxxLibraryOutput | None, LinkInfo | None):+ if not compile_output:+ return (None, None)++ objects = compile_output.pch_object_output if pch else compile_output.stripped_objects if stripped else compile_output.objects++ if not objects:+ return (None, None)++ return _static_library(+ ctx,+ impl_params,+ objects,+ objects_have_external_debug_info = compile_output.objects_have_external_debug_info,+ external_debug_info = make_artifact_tset(+ ctx.actions,+ label = ctx.label,+ artifacts = compile_output.external_debug_info,+ children = impl_params.additional.static_external_debug_info,+ ),+ pic = pic,+ optimized = optimized,+ debuggable = debuggable,+ stripped = stripped,+ extra_linkables = extra_static_linkables,+ bitcode_objects = compile_output.bitcode_objects,+ has_hip_device_debug = compile_output.has_hip_device_debug,+ hip_arch_debug_files = compile_output.hip_arch_debug_files,+ )++ def build_shared_library(+ compile_output: _CxxLibraryCompileOutput, flavor: LinkableFlavor+ ) -> (CxxLibraryOutput, _CxxSharedLibraryResult, NamedLinkedObject):+ external_debug_artifacts = compile_output.external_debug_info+ if compile_output.objects_have_external_debug_info:+ external_debug_artifacts.extend(compile_output.objects)+ if impl_params.extra_link_input_has_external_debug_info:+ external_debug_artifacts.extend(impl_params.extra_link_input)+ external_debug_info = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ artifacts = external_debug_artifacts,+ children = impl_params.additional.shared_external_debug_info,+ tags = impl_params.additional.external_debug_info_tags,+ )++ result = _shared_library(+ ctx = ctx,+ impl_params = impl_params,+ objects = compile_output.objects,+ external_debug_info = external_debug_info,+ dep_infos = dep_infos,+ gnu_use_link_groups = gnu_use_link_groups,+ link_ordering = map_val(LinkOrdering, ctx.attrs.link_ordering),+ link_execution_preference = link_execution_preference,+ flavor = flavor,+ has_hip_device_debug = compile_output.has_hip_device_debug,+ )+ shlib = result.link_result.linked_object++ hip_debug = compile_output.hip_arch_debug_files+ if hip_debug:+ shlib = LinkedObject(+ output = shlib.output,+ bitcode_bundle = shlib.bitcode_bundle,+ unstripped_output = shlib.unstripped_output,+ prebolt_output = shlib.prebolt_output,+ link_args = shlib.link_args,+ dwp = shlib.dwp,+ hip_arch_debug_files = hip_debug,+ external_debug_info = shlib.external_debug_info,+ linker_argsfile = shlib.linker_argsfile,+ linker_command = shlib.linker_command,+ index_argsfile = shlib.index_argsfile,+ import_library = shlib.import_library,+ pdb = shlib.pdb,+ split_debug_output = shlib.split_debug_output,+ )++ extra_outputs = result.link_result.extra_outputs++ link_cmd_debug_output_file = None+ link_cmd_debug_output = make_link_command_debug_output(shlib)+ if link_cmd_debug_output != None and flavor == LinkableFlavor("default"):+ link_cmd_debug_output_file = make_link_command_debug_output_json_info(ctx.actions, [link_cmd_debug_output])+ providers.append(LinkCommandDebugOutputInfo(debug_outputs = [link_cmd_debug_output]))++ unstripped = shlib.unstripped_output+ output = CxxLibraryOutput(+ output_style = LibOutputStyle("shared_lib"),+ default = shlib.output,+ unstripped = unstripped,+ object_files = compile_output.objects,+ external_debug_info = shlib.external_debug_info,+ dwp = shlib.dwp,+ hip_arch_debug_files = hip_debug,+ linker_map = result.link_result.linker_map_data,+ sub_targets = extra_outputs+ | {+ "linker.argsfile": [+ DefaultInfo(+ default_output = shlib.linker_argsfile,+ )+ ],+ "linker.command": [+ DefaultInfo(+ default_outputs = filter(None, [link_cmd_debug_output_file]),+ )+ ],+ "unstripped": [+ DefaultInfo(+ default_output = unstripped,+ )+ ],+ },+ pdb = shlib.pdb,+ implib = shlib.import_library,+ )++ solib = NamedLinkedObject(+ soname = result.soname,+ linked_object = shlib,+ extra_outputs = extra_outputs,+ )++ return (output, result, solib)++ # We don't know which outputs consumers may want, so we define all the possibilities given our preferred linkage.+ for output_style in get_output_styles_for_linkage(preferred_linkage):+ outputs_for_style = {}+ optimized_info = None+ debuggable_info = None+ stripped = None+ info = None++ # Generate the necessary libraries and+ # add them to the exported link info.+ if output_style != LibOutputStyle("shared_lib"):+ pic = _use_pic(output_style)+ lib_compile_output = compiled_srcs.pic+ if not pic:+ lib_compile_output = compiled_srcs.non_pic+ if not lib_compile_output:+ fail("output_style {} requires non_pic compiled srcs, but didn't have any in {}".format(output_style, compiled_srcs))++ gcno_files += lib_compile_output.gcno_files++ # FYI(patskovn): Note that we are using `pic` in optimized and debuggable transformations here.+ # Ideal way to set it up would be to expose whole matrix of debuggable/optimized/pic instead.+ # But it increases retained memory (not much really, but still) so in the mean time I decied+ # to not do it. As a downside, if transformation spec is used to build a binary statically+ # without -fPIE, we are still using pic objects for it. I haven't found any real world impact+ # of that though. Another point is: transformation specs are not used for building for production+ # and only affect local development so we can do this experiment first. I may revisit that decision.+ optimized_output, optimized_info = build_static_library(+ compile_output = compiled_srcs.pic_optimized,+ pic = pic,+ optimized = True,+ debuggable = False,+ pch = False,+ stripped = False,+ )+ if optimized_output:+ outputs_for_style[LinkableFlavor("optimized")] = optimized_output++ debuggable_output, debuggable_info = build_static_library(+ compile_output = compiled_srcs.pic_debuggable,+ pic = pic,+ optimized = False,+ debuggable = True,+ pch = False,+ stripped = False,+ )+ if debuggable_output:+ outputs_for_style[LinkableFlavor("debug")] = debuggable_output++ # Only generate an archive if we have objects to include+ if lib_compile_output.objects or (compile_pch and lib_compile_output.pch_object_output):+ default_output, info = build_static_library(+ compile_output = lib_compile_output,+ pic = pic,+ optimized = False,+ debuggable = False,+ pch = bool(compile_pch),+ stripped = False,+ )+ stripped_output, stripped = _static_library(+ ctx,+ impl_params,+ lib_compile_output.stripped_objects,+ pic = pic,+ stripped = True,+ optimized = False,+ debuggable = False,+ extra_linkables = extra_static_linkables,+ bitcode_objects = lib_compile_output.bitcode_objects,+ has_hip_device_debug = lib_compile_output.has_hip_device_debug,+ hip_arch_debug_files = lib_compile_output.hip_arch_debug_files,+ )+ if default_output:+ outputs_for_style[LinkableFlavor("default")] = default_output+ if stripped_output:+ outputs_for_style[LinkableFlavor("stripped")] = stripped_output+ else:+ # Header only libraries can have `extra_static_linkables`+ info = LinkInfo(+ name = ctx.label.name,+ linkables = extra_static_linkables,+ metadata = cxx_attr_dep_metadata(ctx),+ )+ else: # shared+ # Bare-metal toolchains don't support shared libraries (ld lacks -shared).+ # Provide the pic_archive as fallback to satisfy the linkable graph.+ if not get_cxx_toolchain_info(ctx).linker_info.supports_shared_libraries:+ if preferred_linkage == Linkage("shared"):+ fail("{}: cannot build shared library for a toolchain that does not support shared libraries".format(ctx.label))+ link_infos[output_style] = link_infos[LibOutputStyle("pic_archive")]+ continue++ # If requested (by build_empty_so), we still generate a shared library even if there's no source objects.+ # This could be useful because it can still point to dependencies.+ # i.e. a rust_python_extension is an empty .so depending on a rust shared object+ compile_output = compiled_srcs.pic+ if compile_output.objects or impl_params.build_empty_so:+ gcno_files += compile_output.gcno_files++ default_output, result, solib = build_shared_library(+ compile_output = compiled_srcs.pic,+ flavor = LinkableFlavor("default"),+ )+ info = result.info+ outputs_for_style[LinkableFlavor("default")] = default_output+ solibs[LinkableFlavor("default")] = solib++ providers.append(result.link_result.link_execution_preference_info)++ link_sanitizer_runtime_files = result.link_result.sanitizer_runtime_files+ if link_sanitizer_runtime_files:+ if sanitizer_runtime_files:+ fail("Cannot specify sanitizer runtime files multiple times")+ sanitizer_runtime_files = link_sanitizer_runtime_files++ if compiled_srcs.pic_optimized and (compiled_srcs.pic_optimized.objects or impl_params.build_empty_so):+ optimized_output, optimized_result, optimized_solib = build_shared_library(+ compile_output = compiled_srcs.pic_optimized,+ flavor = LinkableFlavor("optimized"),+ )+ optimized_info = optimized_result.info+ outputs_for_style[LinkableFlavor("optimized")] = optimized_output+ solibs[LinkableFlavor("optimized")] = optimized_solib++ if compiled_srcs.pic_debuggable and (compiled_srcs.pic_debuggable.objects or impl_params.build_empty_so):+ debug_output, debug_result, debug_solib = build_shared_library(+ compile_output = compiled_srcs.pic_debuggable,+ flavor = LinkableFlavor("debug"),+ )+ debuggable_info = debug_result.info+ outputs_for_style[LinkableFlavor("debug")] = debug_output+ solibs[LinkableFlavor("debug")] = debug_solib++ if outputs_for_style:+ outputs[output_style] = outputs_for_style++ # you cannot link against header only libraries so create an empty link info+ info = info if info != None else LinkInfo()+ link_infos[output_style] = LinkInfos(+ label = ctx.label,+ default = ldflags(info),+ optimized = ldflags(optimized_info) if optimized_info != None else None,+ debuggable = ldflags(debuggable_info) if debuggable_info != None else None,+ stripped = ldflags(stripped) if stripped != None else None,+ )++ if get_cxx_toolchain_info(ctx).gcno_files:+ deps_gcno_files = [x[GcnoFilesInfo].gcno_files for x in ctx.attrs.deps + ctx.attrs.exported_deps if GcnoFilesInfo in x]+ providers.append(+ GcnoFilesInfo(+ gcno_files = dedupe(flatten(deps_gcno_files) + gcno_files),+ )+ )++ return _CxxAllLibraryOutputs(+ outputs = outputs,+ link_infos = link_infos,+ providers = providers,+ solibs = solibs,+ sanitizer_runtime_files = sanitizer_runtime_files,+ )++def _strip_objects(+ actions: AnalysisActions, cxx_toolchain_info: CxxToolchainInfo, outs: list[CxxCompileOutput], supports_stripping: bool, has_content_based_path: bool+) -> list[Artifact]:+ """+ Return new objects with debug info stripped.+ """++ # Stripping is not supported on Windows+ linker_type = cxx_toolchain_info.linker_info.type+ if linker_type == LinkerType("windows"):+ return [out.object for out in outs]++ # Disable stripping if no `strip` binary was provided by the toolchain.+ if cxx_toolchain_info.binary_utilities_info == None or cxx_toolchain_info.binary_utilities_info.strip == None:+ return [out.object for out in outs]++ # Disable stripping if library opted out from it+ if not supports_stripping:+ return [out.object for out in outs]++ stripped_objects = []++ for out in outs:+ obj = out.object+ if out.hip_device_debug:+ # hip_debug_extract already rewrote the embedded GPU code objects;+ # a second strip invalidates ELF extended section indexes.+ stripped_objects.append(obj)+ continue+ base, ext = paths.split_extension(obj.short_path)+ expect(ext == ".o")+ stripped_objects.append(strip_debug_info(actions, base + ".stripped.o", obj, cxx_toolchain_info, has_content_based_path = has_content_based_path))++ return stripped_objects++def _get_shared_library_links(+ ctx: AnalysisContext,+ reduce_linkable_graph_func: typing.Callable[[], ReducedLinkableGraph],+ link_group: [str, None],+ link_group_mappings: [dict[Label, str], None],+ link_group_preferred_linkage: dict[Label, Linkage],+ link_group_libs: dict[str, LinkGroupLib],+ exported_deps: list[Dependency],+ non_exported_deps: list[Dependency],+ force_link_group_linking,+ frameworks_linkable: [FrameworksLinkable, None],+ swiftmodule_linkable: [SwiftmoduleLinkable, None],+ force_static_follows_dependents: bool = True,+) -> (LinkArgs, [DefaultInfo, None], LinkExecutionPreference):+ """+ Returns LinkArgs with the content to link, and a link group map json output if applicable.++ TODO(T110378116): Omnibus linking always creates shared libraries by linking+ against shared dependencies. This is not true for link groups and possibly+ other forms of shared libraries. Ideally we consolidate this logic and+ propagate up only the expected links. Until we determine the comprehensive+ logic here, simply diverge behavior on whether link groups are defined.+ """++ pic_behavior = get_cxx_toolchain_info(ctx).pic_behavior++ # If we're not filtering for link groups, link against the shared dependencies+ if not link_group_mappings and not force_link_group_linking:+ deps = dedupe(flatten([non_exported_deps, exported_deps]))+ deps_merged_link_infos = cxx_inherited_link_info(deps)++ link_strategy = _link_strategy_for_some_shared_links(ctx.attrs)++ # We cannot support deriving link execution preference off the included links, as we've already+ # lost the information on what is in the link.+ # TODO(T152860998): Derive link_execution_preference based upon the included links+ # Not all rules calling `cxx_library_parameterized` have `link_execution_preference`. Notably `cxx_python_extension`.+ link_execution_preference = (+ get_link_execution_preference(ctx, []) if hasattr(ctx.attrs, "link_execution_preference") else LinkExecutionPreference("any")+ )++ return (+ apple_build_link_args_with_deduped_flags(+ ctx,+ deps_merged_link_infos,+ frameworks_linkable,+ # fPIC behaves differently on various combinations of toolchains + platforms.+ # To get the link_strategy, we have to check the link_strategy against the toolchain's pic_behavior.+ #+ # For more info, check the PicBehavior docs.+ process_link_strategy_for_pic_behavior(link_strategy, pic_behavior),+ None,+ swiftmodule_linkable,+ ),+ None,+ link_execution_preference,+ )++ # Else get filtered link group links+ prefer_stripped = cxx_is_gnu(ctx) and ctx.attrs.prefer_stripped_objects++ # TODO(cjhopman): Why is this different than where we compute just above for the non link-group case?+ link_strategy = to_link_strategy(cxx_attr_link_style(ctx))+ if link_strategy == LinkStrategy("static"):+ link_strategy = LinkStrategy("static_pic")+ link_strategy = process_link_strategy_for_pic_behavior(link_strategy, pic_behavior)+ reduced_linkable_graph = reduce_linkable_graph_func()++ roots = set(linkable_deps(non_exported_deps + exported_deps))+ is_executable_link = False+ lib_linkables = collect_linkables(+ reduced_linkable_graph,+ is_executable_link,+ link_strategy,+ link_group_preferred_linkage,+ pic_behavior,+ roots,+ )++ build_context = BuildLinkGroupsContext(+ public_nodes = set(),+ linkable_graph = reduced_linkable_graph,+ link_groups = {},+ link_group_mappings = link_group_mappings,+ link_group_preferred_linkage = link_group_preferred_linkage,+ link_strategy = link_strategy,+ pic_behavior = pic_behavior,+ link_group_libs = {name: (lib.label, lib.shared_link_infos) for name, lib in link_group_libs.items()},+ prefer_stripped = prefer_stripped,+ prefer_optimized = False,+ )++ filtered_labels_to_links = get_filtered_labels_to_links_map(+ link_group = link_group,+ linkables = lib_linkables,+ is_executable_link = False,+ build_context = build_context,+ force_static_follows_dependents = force_static_follows_dependents,+ )+ filtered_links = get_filtered_links(filtered_labels_to_links.map)+ filtered_targets = get_filtered_targets(filtered_labels_to_links.map)++ link_execution_preference = get_link_execution_preference(ctx, filtered_labels_to_links.map.keys())++ # Unfortunately, link_groups does not use MergedLinkInfo to represent the args+ # for the resolved nodes in the graph.+ additional_links = apple_get_link_info_by_deduping_link_infos(ctx, filtered_links, frameworks_linkable, swiftmodule_linkable)+ if additional_links:+ filtered_links.append(additional_links)++ return LinkArgs(infos = filtered_links), get_link_group_map_json(ctx, filtered_targets), link_execution_preference++def _use_pic(output_style: LibOutputStyle) -> bool:+ """+ Whether this output style requires PIC objects.+ """+ return output_style != LibOutputStyle("archive")++# Create the objects/archive to use for static linking this rule.+# Returns a tuple of objects/archive to use as the default output for the link+# style(s) it's used in and the `LinkInfo` to export to dependents.+def _static_library(+ ctx: AnalysisContext,+ impl_params: CxxRuleConstructorParams,+ objects: list[Artifact],+ pic: bool,+ optimized: bool,+ debuggable: bool,+ stripped: bool,+ extra_linkables: list[[FrameworksLinkable, SwiftmoduleLinkable]],+ objects_have_external_debug_info: bool = False,+ external_debug_info: ArtifactTSet = ArtifactTSet(),+ bitcode_objects: [list[Artifact], None] = None,+ has_hip_device_debug: bool = False,+ hip_arch_debug_files: dict[str, list[Artifact]] = {},+) -> (CxxLibraryOutput, LinkInfo):+ if optimized and debuggable:+ fail("Pls pick optimized OR debuggable")+ if len(objects) == 0:+ fail("empty objects")++ # No reason to create a static library with just a single object file. We+ # still want to create a static lib to expose as the default output because+ # it's the contract/expectation of external clients of the cmd line+ # interface. Any tools consuming `buck build` outputs should get a+ # consistent output type when building a library, not static lib or object+ # file depending on number of source files.+ linker_info = get_cxx_toolchain_info(ctx).linker_info+ linker_type = linker_info.type++ base_name = _base_static_library_name(ctx, optimized, debuggable, stripped)+ name = _archive_name(base_name, pic = pic, extension = linker_info.static_library_extension)++ # If we have extra hidden deps of this target add them to the archive action+ # so they are forced to build for static library output.+ archive = make_archive(ctx, name, objects, impl_params.extra_hidden)++ bitcode_bundle = _bitcode_bundle(ctx, bitcode_objects, optimized, debuggable, pic, stripped)+ if False:+ # TODO(nga): bitcode_bundle.artifact+ def unknown():+ pass++ bitcode_bundle = unknown()+ if bitcode_bundle != None and bitcode_bundle.artifact != None:+ bitcode_artifact = bitcode_bundle.artifact+ else:+ bitcode_artifact = None++ if use_archives(ctx):+ linkable = ArchiveLinkable(+ archive = archive,+ bitcode_bundle = bitcode_artifact,+ linker_type = linker_type,+ link_whole = _attr_link_whole(ctx),+ )+ else:+ linkable = ObjectsLinkable(+ objects = objects,+ bitcode_bundle = bitcode_artifact,+ linker_type = linker_type,+ link_whole = _attr_link_whole(ctx),+ )++ post_flags = []++ if pic:+ post_flags.extend(linker_info.static_pic_dep_runtime_ld_flags or [])+ else:+ post_flags.extend(linker_info.static_dep_runtime_ld_flags or [])++ # On darwin, the linked output references the archive that contains the+ # object files instead of the originating objects.+ object_external_debug_info = []+ if linker_type == LinkerType("darwin"):+ if archive.archive_contents_type == ArchiveContentsType("virtual"):+ # If using thin archives or passing archives --start-lib --end-lib style (virtual), we only need to provide the underlying objects+ object_external_debug_info.extend(archive.external_objects)+ elif archive.archive_contents_type == ArchiveContentsType("thin"):+ # If passing the archive to the linker conventionally, we need to provide both the thin archive+ # and the underlying object files if using thin archives+ object_external_debug_info.append(archive.artifact)+ object_external_debug_info.extend(archive.external_objects)+ else:+ # And only the archive if using regular archives+ object_external_debug_info.append(archive.artifact)+ elif archive.archive_contents_type == ArchiveContentsType("thin") and objects_have_external_debug_info:+ object_external_debug_info.extend(objects)++ all_external_debug_info = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ artifacts = object_external_debug_info,+ children = [external_debug_info],+ tags = impl_params.additional.external_debug_info_tags,+ )++ return (+ CxxLibraryOutput(+ output_style = LibOutputStyle("pic_archive") if pic else LibOutputStyle("archive"),+ default = archive.artifact,+ unstripped = archive.artifact,+ object_files = objects,+ bitcode_bundle = bitcode_bundle,+ other = (archive.external_objects if archive.archive_contents_type == ArchiveContentsType("thin") else []),+ sub_targets = {},+ ),+ LinkInfo(+ name = name,+ # We're propagating object code for linking up the dep tree,+ # so we need to also propagate any necessary link flags required for+ # the object code.+ pre_flags = impl_params.extra_exported_link_flags,+ post_flags = post_flags,+ # Extra linkables are propagated here so they are available to link_groups+ # when they are deducing linker args.+ linkables = [linkable] + extra_linkables,+ external_debug_info = all_external_debug_info,+ has_hip_device_debug = has_hip_device_debug,+ hip_arch_debug_files = hip_arch_debug_files,+ metadata = cxx_attr_dep_metadata(ctx),+ ),+ )++# A bitcode bundle is very much like a static library and is generated from object file+# inputs, except the output is a combined bitcode file, which is not machine code.+def _bitcode_bundle(+ ctx: AnalysisContext, objects: [list[Artifact], None], optimized: bool, debuggable: bool, pic: bool, stripped: bool, name_extra = ""+) -> [BitcodeBundle, None]:+ if objects == None or len(objects) == 0:+ return None++ base_name = _base_static_library_name(ctx, optimized, debuggable, stripped = False)+ name = name_extra + _bitcode_bundle_name(base_name, pic, stripped)+ return make_bitcode_bundle(ctx, name, objects)++def _shared_library(+ ctx: AnalysisContext,+ impl_params: CxxRuleConstructorParams,+ objects: list[Artifact],+ external_debug_info: ArtifactTSet,+ dep_infos: LinkArgs,+ gnu_use_link_groups: bool,+ link_execution_preference: LinkExecutionPreference,+ link_ordering: [LinkOrdering, None],+ flavor: LinkableFlavor,+ has_hip_device_debug: bool = False,+) -> _CxxSharedLibraryResult:+ """+ Generate a shared library and the associated native link info used by+ dependents to link against it.+ """++ def flavored_output(output: str, separator: str = "/") -> str:+ if flavor != LinkableFlavor("default"):+ return flavor.value + separator + output+ return output++ soname = _soname(ctx, impl_params)+ cxx_toolchain = get_cxx_toolchain_info(ctx)+ linker_info = cxx_toolchain.linker_info++ local_bitcode_bundle = _bitcode_bundle(+ ctx,+ objects,+ optimized = flavor == LinkableFlavor("optimized"),+ debuggable = flavor == LinkableFlavor("debug"),+ pic = False,+ stripped = flavor == LinkableFlavor("stripped"),+ name_extra = "objects-",+ )++ # NOTE(agallagher): We add exported link flags here because it's what v1+ # does, but the intent of exported link flags are to wrap the link output+ # that we propagate up the tree, rather than being used locally when+ # generating a link product.+ linker_flags = cxx_attr_linker_flags_all(ctx, impl_params.cxx_flags)+ link_info = LinkInfo(+ dist_thin_lto_codegen_flags = getattr(ctx.attrs, "dist_thin_lto_codegen_flags", []),+ pre_flags = (linker_flags.flags + linker_flags.exported_flags + getattr(ctx.attrs, "local_linker_flags", [])),+ linkables = [+ ObjectsLinkable(+ objects = objects,+ bitcode_bundle = local_bitcode_bundle.artifact if local_bitcode_bundle else None,+ linker_type = linker_info.type,+ link_whole = True,+ )+ ],+ post_flags = (+ impl_params.extra_exported_link_flags + impl_params.extra_link_flags + linker_flags.post_flags + (linker_info.shared_dep_runtime_ld_flags or [])+ # TODO(cjhopman): Why doesn't this add exported_linker_flags.post_flags?+ ),+ external_debug_info = external_debug_info,+ metadata = cxx_attr_dep_metadata(ctx),+ )++ # If we have extra hidden deps here, add them as hidden inputs+ # to the link action so that they are forced to build before linking.+ links = [LinkArgs(infos = [link_info]), dep_infos]+ if impl_params.extra_hidden:+ links.append(+ LinkArgs(flags = cmd_args(hidden = impl_params.extra_hidden)),+ )++ # shared library interface generation can be disabled at the target level+ effective_shlib_interfaces_mode = ShlibInterfacesMode("disabled")+ if cxx_use_shlib_intfs(ctx):+ effective_shlib_interfaces_mode = get_cxx_toolchain_info(ctx).linker_info.shlib_interfaces+ if effective_shlib_interfaces_mode == ShlibInterfacesMode("defined_only") and gnu_use_link_groups:+ # TODO(agallagher): There's a bug in shlib intfs interacting with link+ # groups, where we don't include the symbols we're meant to export from+ # deps that get statically linked in.+ effective_shlib_interfaces_mode = ShlibInterfacesMode("disabled")++ needs_extract = hip_debug_extract_available(cxx_toolchain) and (has_hip_device_debug or link_args_have_hip_device_debug(links))+ link_output = flavored_output(soname) + PRE_EXTRACT_SUFFIX if needs_extract else flavored_output(soname)++ link_result = cxx_link_shared_library(+ ctx = ctx,+ output = link_output,+ opts = link_options(+ enable_distributed_thinlto = getattr(ctx.attrs, "enable_distributed_thinlto", False),+ links = links,+ identifier = flavored_output(soname, separator = "_"),+ # As for a cxx_binary's link (exe_allow_cache_upload).+ allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs),+ link_ordering = link_ordering,+ strip = impl_params.strip_executable,+ strip_args_factory = impl_params.strip_args_factory,+ link_execution_preference = link_execution_preference,+ error_handler = impl_params.error_handler,+ extra_linker_outputs_factory = impl_params.extra_linker_outputs_factory,+ extra_linker_outputs_flags_factory = impl_params.extra_linker_outputs_flags_factory,+ extra_distributed_thin_lto_opt_outputs_merger = impl_params.extra_distributed_thin_lto_opt_outputs_merger,+ produce_shared_library_interface = effective_shlib_interfaces_mode == ShlibInterfacesMode("stub_from_linker_invocation"),+ has_hip_device_debug = has_hip_device_debug,+ ),+ name = soname if impl_params.use_soname else None,+ shared_library_flags = impl_params.shared_library_flags,+ )+ exported_shlib = link_result.linked_object.output++ if effective_shlib_interfaces_mode == ShlibInterfacesMode("stub_from_linker_invocation"):+ exported_shlib = link_result.shared_library_interface+ elif effective_shlib_interfaces_mode == ShlibInterfacesMode("stub_from_library"):+ # Generate a library interface from the linked library output.+ # This will prevent relinking rdeps when changes do not affect+ # the library symbols.+ exported_shlib = shared_library_interface(+ ctx = ctx,+ shared_lib = exported_shlib,+ )+ elif effective_shlib_interfaces_mode == ShlibInterfacesMode("defined_only"):+ link_info = LinkInfo(+ pre_flags = link_info.pre_flags,+ linkables = link_info.linkables,+ post_flags = (+ (link_info.post_flags or [])+ + get_ignore_undefined_symbols_flags(linker_info.type)+ + (linker_info.independent_shlib_interface_linker_flags or [])+ ),+ external_debug_info = link_info.external_debug_info,+ metadata = cxx_attr_dep_metadata(ctx),+ )+ intf_link_result = cxx_link_shared_library(+ ctx = ctx,+ output = flavored_output(+ get_shared_library_name(+ linker_info,+ ctx.label.name + "-for-interface",+ apply_default_prefix = True,+ )+ ),+ opts = link_options(+ category_suffix = "interface",+ link_ordering = link_ordering,+ links = [LinkArgs(infos = [link_info])],+ identifier = flavored_output(soname + "-interface", separator = "_"),+ link_execution_preference = link_execution_preference,+ strip = impl_params.strip_executable,+ error_handler = impl_params.error_handler,+ ),+ name = soname,+ )+ exported_shlib = shared_library_interface(+ ctx = ctx,+ shared_lib = intf_link_result.linked_object.output,+ )++ # Link against import library on Windows.+ if link_result.linked_object.import_library:+ exported_shlib = link_result.linked_object.import_library++ return _CxxSharedLibraryResult(+ link_result = link_result,+ soname = soname,+ info = LinkInfo(+ name = soname,+ linkables = [+ SharedLibLinkable(+ lib = exported_shlib,+ )+ ],+ has_hip_device_debug = has_hip_device_debug,+ metadata = cxx_attr_dep_metadata(ctx),+ ),+ )++def _attr_reexport_all_header_dependencies(ctx: AnalysisContext) -> bool:+ return value_or(ctx.attrs.reexport_all_header_dependencies, False)++def _soname(ctx: AnalysisContext, impl_params) -> str:+ """+ Get the shared library name to set for the given C++ library.+ """+ linker_info = get_cxx_toolchain_info(ctx).linker_info+ explicit_soname = value_or(ctx.attrs.soname, impl_params.soname)+ if explicit_soname != None:+ return get_shared_library_name_for_param(linker_info, explicit_soname)+ return get_default_shared_library_name(linker_info, ctx.label)++def _base_static_library_name(ctx: AnalysisContext, optimized: bool, debuggable: bool, stripped: bool) -> str:+ return "{}{}{}{}".format(ctx.label.name, ".optimized" if optimized else "", ".debuggable" if debuggable else "", ".stripped" if stripped else "")++def _archive_name(name: str, pic: bool, extension: str) -> str:+ return "lib{}{}.{}".format(name, ".pic" if pic else "", extension)++def _bitcode_bundle_name(name: str, pic: bool, stripped: bool = False) -> str:+ return "{}{}{}.bc".format(name, ".pic" if pic else "", ".stripped" if stripped else "")++def _attr_link_whole(ctx: AnalysisContext) -> bool:+ return value_or(ctx.attrs.link_whole, False)++def use_archives(ctx: AnalysisContext) -> bool:+ """+ Whether this rule should use archives to package objects when producing+ link input for dependents.+ """+ linker_info = get_cxx_toolchain_info(ctx).linker_info+ requires_archives = linker_info.requires_archives+ requires_objects = linker_info.requires_objects++ if requires_archives and requires_objects:+ fail("In cxx linker_info, only one of `requires_archives` and `requires_objects` can be enabled")++ # If the toolchain requires them, then always use them.+ if requires_archives:+ return True++ if requires_objects:+ return False++ # Otherwise, fallback to the rule-specific setting.+ return value_or(getattr(ctx.attrs, "use_archive", True), True)
@@ -0,0 +1,207 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifacts.bzl",+ "ArtifactOutputs", # @unused Used as a type+ "single_artifact",+)+load("@prelude//:paths.bzl", "paths")+load(+ "@prelude//linking:link_info.bzl",+ "DepMetadata",+ "LinkStyle",+ "LinkerFlags",+ "MergedLinkInfo",+)+load("@prelude//linking:types.bzl", "Linkage")+load(+ "@prelude//utils:utils.bzl",+ "filter_and_map_idx",+ "from_named_set",+)+load(":cxx_context.bzl", "get_cxx_platform_info", "get_cxx_toolchain_info")+load(":cxx_flags.bzl", "cxx_flags_linker_flags")+load(+ ":cxx_toolchain_types.bzl",+ "LinkerType",+ "ShlibInterfacesMode",+)++OBJECTS_SUBTARGET = "objects"++EMPTY_DEFAULT_INFO = DefaultInfo()++# The dependencies, and the default deps (if selected)+def cxx_attr_deps(ctx: AnalysisContext) -> list[Dependency]:+ deps = ctx.attrs.deps++ if getattr(ctx.attrs, "default_deps", "") == "deps":+ toolchain_info = get_cxx_toolchain_info(ctx)+ if toolchain_info.default_deps:+ deps.extend(toolchain_info.default_deps)++ deps_query_attr = getattr(ctx.attrs, "deps_query", None)+ if deps_query_attr:+ return deps + deps_query_attr++ # Avoid making a copy of deps if deps_query is not set.+ return deps++# The exported dependencies, and the default deps (if selected)+def cxx_attr_exported_deps(ctx: AnalysisContext) -> list[Dependency]:+ exported_deps = []++ exported_deps_attr = getattr(ctx.attrs, "exported_deps", None)+ if exported_deps_attr:+ exported_deps.extend(exported_deps_attr)++ if getattr(ctx.attrs, "default_deps", "") == "exported_deps":+ toolchain_info = get_cxx_toolchain_info(ctx)+ if toolchain_info.default_deps:+ exported_deps.extend(toolchain_info.default_deps)++ return exported_deps++def cxx_attr_linker_flags_all(ctx: AnalysisContext, cxx_flags: list[Dependency] = []) -> LinkerFlags:+ flags = cxx_attr_linker_flags(ctx, cxx_flags)++ local_linker_script_flags_attr = getattr(ctx.attrs, "local_linker_script_flags", None)+ if local_linker_script_flags_attr:+ flags.extend(local_linker_script_flags_attr)++ post_flags = getattr(ctx.attrs, "post_linker_flags", [])++ return LinkerFlags(+ flags = flags,+ post_flags = post_flags,+ exported_flags = ctx.attrs.exported_linker_flags,+ exported_post_flags = ctx.attrs.exported_post_linker_flags,+ )++def cxx_inherited_link_info(first_order_deps: list[Dependency]) -> list[MergedLinkInfo]:+ """+ Returns the list of MergedLinkInfo from the dependencies, filtering out those without a MergedLinkInfo+ """++ # We filter out nones because some non-cxx rule without such providers could be a dependency, for example+ # cxx_binary "fbcode//one_world/cli/util/process_wrapper:process_wrapper" depends on+ # python_library "fbcode//third-party-buck/$platform/build/glibc:__project__"+ return filter_and_map_idx(MergedLinkInfo, first_order_deps)++# Linker flags+def cxx_attr_linker_flags(ctx: AnalysisContext, cxx_flags: list[Dependency] = []) -> list[typing.Any]:+ linker_flags = cxx_flags_linker_flags(ctx.actions, cxx_flags) + ctx.attrs.linker_flags+ return linker_flags++def cxx_attr_link_style(ctx: AnalysisContext) -> LinkStyle:+ if ctx.attrs.link_style != None:+ return LinkStyle(ctx.attrs.link_style)+ if ctx.attrs.defaults != None:+ # v1 equivalent code is in CxxConstructorArg::getDefaultFlavors and ParserWithConfigurableAttributes::applyDefaultFlavors+ # Only values in the map are used by v1 as flavors, copy this behavior and return the first value which is compatible with link style.+ v1_flavors = ctx.attrs.defaults.values()+ for s in [LinkStyle("static"), LinkStyle("static_pic"), LinkStyle("shared")]:+ if s.value in v1_flavors:+ return s+ return get_cxx_toolchain_info(ctx).linker_info.link_style++def cxx_attr_preferred_linkage(ctx: AnalysisContext) -> Linkage:+ preferred_linkage = ctx.attrs.preferred_linkage++ # force_static is deprecated, but it has precedence over preferred_linkage+ if getattr(ctx.attrs, "force_static", False):+ preferred_linkage = "static"++ return Linkage(preferred_linkage)++def cxx_attr_resources(ctx: AnalysisContext) -> dict[str, ArtifactOutputs]:+ """+ Return the resources provided by this rule, as a map of resource name to+ a tuple of the resource artifact and any "other" outputs exposed by it.+ """++ resources = {}++ resources_attr = getattr(ctx.attrs, "resources", None)+ if resources_attr:+ # Resource keys prefix with `header_namespace`. Unset (None) falls+ # back to package; explicit "" means "no prefix" UNLESS `raw_headers`+ # is also set, which signals the xplat macros (`_unified_cxx_library`+ # / `_fbcode_cpp_common_wrapper`) clobbered `header_namespace=""` to+ # suppress #include namespace mangling — fall back to package in that+ # case so consumers (e.g. `kBuckPrefix + "manifest.json"`) keep+ # working. Idempotent: keys already prefixed (by ACME, snapshots) are+ # left alone.+ namespace = ctx.attrs.header_namespace+ if namespace == None:+ namespace = ctx.label.package+ elif namespace == "" and getattr(ctx.attrs, "raw_headers", None):+ namespace = ctx.label.package+ prefix = namespace + "/" if namespace else None++ # Use getattr, as apple rules don't have a `resources` parameter.+ for name, resource in from_named_set(resources_attr).items():+ if not namespace:+ key = name+ elif name == namespace or name.startswith(prefix):+ key = name+ else:+ key = paths.join(namespace, name)+ resources[key] = single_artifact(resource)++ return resources++def cxx_is_gnu(ctx: AnalysisContext) -> bool:+ return get_cxx_toolchain_info(ctx).linker_info.type == LinkerType("gnu")++def cxx_use_shlib_intfs(ctx: AnalysisContext) -> bool:+ """+ Return whether we should use shared library interfaces for linking.+ """++ # Per-rule opt-out.+ if not getattr(ctx.attrs, "supports_shlib_interfaces", True):+ return False++ linker_info = get_cxx_toolchain_info(ctx).linker_info+ return linker_info.shlib_interfaces != ShlibInterfacesMode("disabled")++def cxx_use_shlib_intfs_mode(ctx: AnalysisContext, mode: ShlibInterfacesMode) -> bool:+ """+ Verify we are using a specific shared library interface mode.+ """+ return cxx_use_shlib_intfs(ctx) and get_cxx_toolchain_info(ctx).linker_info.shlib_interfaces == mode++def cxx_platform_supported(ctx: AnalysisContext) -> bool:+ """+ Return whether this rule's `supported_platforms_regex` matches the current+ platform name.+ """++ if ctx.attrs.supported_platforms_regex == None:+ return True++ return regex_match(+ ctx.attrs.supported_platforms_regex,+ get_cxx_platform_info(ctx).name,+ )++def cxx_attr_dep_metadata(ctx: AnalysisContext) -> list[DepMetadata]:+ """+ Return a `DepMetadata` structure with a meaningful version identifier.+ """+ if not getattr(ctx.attrs, "version", None):+ return []+ return [DepMetadata(version = ctx.attrs.version)]++def cxx_attr_use_content_based_paths(ctx: AnalysisContext) -> bool:+ """+ Return whether this rule should use content-based paths.+ """+ return getattr(ctx.attrs, "use_content_based_paths", False)
@@ -0,0 +1,363 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:artifact_tset.bzl", "project_artifacts")+load("@prelude//:paths.bzl", "paths")+load("@prelude//cxx:cxx_apple_linker_flags.bzl", "apple_extra_darwin_linker_flags")+load(+ "@prelude//cxx:cxx_toolchain_types.bzl",+ "CxxToolchainInfo",+ "LinkerType",+)+load("@prelude//cxx:debug.bzl", "SplitDebugMode")+load("@prelude//cxx:linker.bzl", "get_rpath_origin")+load("@prelude//cxx:target_sdk_version.bzl", "get_target_triple")+load(+ "@prelude//linking:link_info.bzl",+ "LinkArgs",+ "LinkOrdering", # @unused Used as a type+ "link_info_to_args",+ "unpack_link_args",+ "unpack_link_args_excluding_object_files_and_lazy_archives",+ "unpack_link_args_object_files_and_lazy_archives_only",+)+load("@prelude//linking:lto.bzl", "LtoMode")+load(+ "@prelude//linking:shared_libraries.bzl",+ "SharedLibrary", # @unused Used as a type+ "create_shlib_dwp_tree",+ "create_shlib_symlink_tree",+)+load("@prelude//utils:arglike.bzl", "ArgLike") # @unused Used as a type+load(+ "@prelude//utils:utils.bzl",+ "map_val",+)++def generates_split_debug(toolchain: CxxToolchainInfo):+ """+ Whether linking generates split debug outputs.+ """++ if toolchain.split_debug_mode == SplitDebugMode("none"):+ return False++ if toolchain.linker_info.lto_mode == LtoMode("none"):+ return False++ return True++def linker_supports_linker_maps(linker_type: LinkerType) -> bool:+ """+ Returns whether the given linker type supports generating linker maps.+ """+ return linker_type in [LinkerType("darwin"), LinkerType("gnu")]++def linker_map_args(toolchain: CxxToolchainInfo, linker_map) -> LinkArgs:+ linker_type = toolchain.linker_info.type+ if linker_type == LinkerType("darwin"):+ flags = [+ "-Xlinker",+ "-map",+ "-Xlinker",+ linker_map,+ ]+ elif linker_type == LinkerType("gnu"):+ flags = [+ "-Xlinker",+ "-Map",+ "-Xlinker",+ linker_map,+ ]+ else:+ fail("Linker type {} not supported for linker maps".format(linker_type))+ return LinkArgs(flags = flags)++def gc_sections_args(toolchain: CxxToolchainInfo, gc_sections_output) -> LinkArgs:+ """Generate linker args for gc-sections output file."""+ linker_type = toolchain.linker_info.type+ if linker_type == LinkerType("gnu"):+ # The linker wrapper (ld.py) handles --write-gc-sections-output flag+ flags = [+ "--write-gc-sections-output",+ gc_sections_output,+ ]+ else:+ fail("gc-sections output is only supported for GNU linker, got: {}".format(linker_type))+ return LinkArgs(flags = flags)++LinkArgsOutput = record(+ link_args = ArgLike,+ hidden = list[typing.Any],+ pdb_artifact = Artifact | None,+)++def get_extra_darwin_linker_flags(ctx: AnalysisContext) -> cmd_args:+ target_triple = get_target_triple(ctx)+ return cmd_args(apple_extra_darwin_linker_flags(target_triple))++def make_link_args(+ ctx: AnalysisContext,+ actions: AnalysisActions,+ cxx_toolchain_info: CxxToolchainInfo,+ links: list[LinkArgs],+ output_short_path: [str, None] = None,+ link_ordering: [LinkOrdering, None] = None,+ has_content_based_path: bool = False,+) -> LinkArgsOutput:+ """+ Merges LinkArgs. Returns the args, files that must be present for those+ args to work when passed to a linker, and optionally an artifact where DWO+ outputs will be written to.+ """+ args = cmd_args()+ hidden = []++ linker_info = cxx_toolchain_info.linker_info+ linker_type = linker_info.type++ link_ordering = link_ordering or map_val(LinkOrdering, linker_info.link_ordering)++ if linker_type == LinkerType("darwin"):+ args.add(get_extra_darwin_linker_flags(ctx))++ pdb_artifact = None+ if linker_info.is_pdb_generated and output_short_path != None:+ pdb_filename = paths.replace_extension(output_short_path, ".pdb")+ pdb_artifact = actions.declare_output(pdb_filename, has_content_based_path = has_content_based_path)+ hidden.append(pdb_artifact.as_output())++ if linker_type == LinkerType("darwin"):+ # We order inputs partially for binary size, and partially for historical+ # reasons. It is important that lazy object file (non link-whole archives)+ # be listed last on the command line so they are not unnecessarily loaded.+ # Some applications implicitly rely upon this ordering, so it is difficult+ # to change. Note link_ordering configuration is not respected. The+ # link_metadata_flag is also ignored as that is a flag to the GNU linker wrapper,+ # which does not apply to Darwin.+ args.add(filter(None, [unpack_link_args_excluding_object_files_and_lazy_archives(link) for link in links]))+ args.add(filter(None, [unpack_link_args_object_files_and_lazy_archives_only(link) for link in links]))+ else:+ args.add(filter(None, [unpack_link_args(link, link_ordering = link_ordering, link_metadata_flag = linker_info.link_metadata_flag) for link in links]))++ return LinkArgsOutput(+ link_args = args,+ hidden = [args] + hidden,+ pdb_artifact = pdb_artifact,+ )++def shared_libs_symlink_tree_name(output: Artifact | str) -> str:+ if isinstance(output, Artifact):+ output = output.short_path+ return "__{}__shared_libs_symlink_tree".format(output)++def _dwp_symlink_tree_name(output: Artifact) -> str:+ return "__{}__dwp_symlink_tree".format(output.short_path)++ExecutableSharedLibArguments = record(+ extra_link_args = field(list[ArgLike], []),+ # Files that must be present for the executable to run successfully. These+ # are always materialized, whether the executable is the output of a build+ # or executed as a host tool.+ runtime_files = field(list[ArgLike], []),+ # Files needed to debug the executable. These need to be materialized when+ # this executable is the output of a build, but not when it is used by other+ # rules.+ external_debug_info = field(list[TransitiveSetArgsProjection], []),+ # Optional shared libs symlink tree symlinked_dir action.+ shared_libs_symlink_tree = field(list[Artifact] | Artifact | None, None),+ dwp_symlink_tree = field(list[Artifact] | Artifact | None, None),+)++CxxSanitizerRuntimeArguments = record(+ extra_link_args = field(list[ArgLike], []),+ sanitizer_runtime_files = field(list[Artifact], []),+)++# @executable_path/Frameworks++def cxx_sanitizer_runtime_arguments(ctx: AnalysisContext, cxx_toolchain: CxxToolchainInfo, output: Artifact) -> CxxSanitizerRuntimeArguments:+ linker_info = cxx_toolchain.linker_info+ target_sanitizer_runtime_enabled = ctx.attrs.sanitizer_runtime_enabled if hasattr(ctx.attrs, "sanitizer_runtime_enabled") else None+ sanitizer_runtime_enabled = target_sanitizer_runtime_enabled if target_sanitizer_runtime_enabled != None else linker_info.sanitizer_runtime_enabled+ if not sanitizer_runtime_enabled:+ return CxxSanitizerRuntimeArguments()++ if not linker_info.sanitizer_runtime_files:+ fail("C++ sanitizer runtime enabled but there are no runtime files")++ if linker_info.type == LinkerType("darwin"):+ # ignore_artifacts as the runtime directory is not required at _link_ time+ runtime_rpath = cmd_args(ignore_artifacts = True)+ runtime_files = linker_info.sanitizer_runtime_files+ for runtime_shared_lib in runtime_files:+ # Rpath-relative dylibs have an install name of `@rpath/libName.dylib`,+ # which means we need to add the parent dir of the dylib as an rpath.+ runtime_shared_lib_dir = cmd_args(runtime_shared_lib, parent = 1)++ # The parent dir of the runtime shared lib must appear as a path+ # relative to the parent dir of the binary. `@executable_path`+ # represents the parent dir of the binary, not the binary itself.+ runtime_shared_lib_rpath = cmd_args(runtime_shared_lib_dir, format = "-Wl,-rpath,@executable_path/{}", relative_to = (output, 1))+ runtime_rpath.add(runtime_shared_lib_rpath)++ return CxxSanitizerRuntimeArguments(+ extra_link_args = [runtime_rpath],+ sanitizer_runtime_files = runtime_files,+ )++ return CxxSanitizerRuntimeArguments()++def cxx_runtime_library_arguments(cxx_toolchain: CxxToolchainInfo) -> list[ArgLike]:+ # Runtime-library files (e.g. compiler-rt builtins) the toolchain provides are+ # linked here, toward the end of the link line, to match the Clang driver's+ # placement of compiler-rt. The consumer is responsible for stopping the driver+ # from also injecting these (e.g. `-nodefaultlibs`).+ linker_info = cxx_toolchain.linker_info+ link_infos = linker_info.runtime_library_files+ if not link_infos:+ return []+ if linker_info.type != LinkerType("gnu"):+ fail("runtime_library_files is only supported for the gnu linker, got {}".format(linker_info.type))+ return [link_info_to_args(link_info) for link_info in link_infos]++def executable_shared_lib_arguments(+ ctx: AnalysisContext, cxx_toolchain: CxxToolchainInfo, output: Artifact, shared_libs: list[SharedLibrary]+) -> ExecutableSharedLibArguments:+ def create_external_debug_info() -> list[TransitiveSetArgsProjection]:+ return project_artifacts(+ actions = ctx.actions,+ tsets = [shlib.lib.external_debug_info for shlib in shared_libs],+ )++ def create_shared_libs_symlink_tree_windows() -> list[Artifact]:+ return [+ ctx.actions.symlink_file(+ shlib.lib.output.basename,+ shlib.lib.output,+ has_content_based_path = False,+ )+ for shlib in shared_libs+ ]++ def create_shared_libs_symlink_trees(shared_libs_symlink_tree_name_arg: str, dwp_symlink_tree_name_arg: str) -> (Artifact, Artifact) | None:+ if not shared_libs:+ return None++ shared_libs_symlink_tree = create_shlib_symlink_tree(+ actions = ctx.actions,+ out = shared_libs_symlink_tree_name_arg,+ shared_libs = shared_libs,+ )+ dwp_symlink_tree = create_shlib_dwp_tree(ctx.actions, dwp_symlink_tree_name_arg, shared_libs)+ return (shared_libs_symlink_tree, dwp_symlink_tree)++ return executable_shared_lib_arguments_template(+ cxx_toolchain,+ output,+ create_external_debug_info,+ create_shared_libs_symlink_trees,+ create_shared_libs_symlink_tree_windows,+ )++def executable_shared_lib_arguments_template(+ cxx_toolchain: CxxToolchainInfo,+ output: Artifact,+ create_external_debug_info: typing.Callable[[], list[TransitiveSetArgsProjection]],+ create_shared_libs_symlink_trees: typing.Callable[[str, str], (Artifact, Artifact) | None],+ create_shared_libs_symlink_tree_windows: typing.Callable[[], list[Artifact]],+) -> ExecutableSharedLibArguments:+ """A generic/templated version of `executable_shared_lib_arguments` that takes in `Callable`s for constructing+ the shared libs symlink tree and external debug info.++ The shared libs symlink tree is constructed differently depending on if the SharedLibraries are stored in a `record`+ or in a `TransitiveSet`.+ """++ extra_link_args = []+ runtime_files = []+ shared_libs_symlink_tree = None++ # External debug info is materialized only when the executable is the output+ # of a build. Do not add to runtime_files.+ external_debug_info = create_external_debug_info()++ linker_type = cxx_toolchain.linker_info.type++ dwp_symlink_tree = None+ if linker_type == LinkerType("windows"):+ shared_libs_symlink_tree = create_shared_libs_symlink_tree_windows()+ runtime_files.extend(shared_libs_symlink_tree)+ # Windows doesn't support rpath.++ else:+ symlink_trees = create_shared_libs_symlink_trees(+ shared_libs_symlink_tree_name(output),+ _dwp_symlink_tree_name(output),+ )++ if symlink_trees:+ shared_libs_symlink_tree, dwp_symlink_tree = symlink_trees+ runtime_files.append(shared_libs_symlink_tree)+ rpath_reference = get_rpath_origin(linker_type)++ # We ignore_artifacts here since we don't want the symlink tree to actually be there for the link.+ rpath_arg = cmd_args(+ shared_libs_symlink_tree,+ format = "-Wl,-rpath,{}/{{}}".format(rpath_reference),+ ignore_artifacts = True,+ relative_to = (output, 1),+ )+ extra_link_args.append(rpath_arg)++ return ExecutableSharedLibArguments(+ extra_link_args = extra_link_args,+ runtime_files = runtime_files,+ external_debug_info = external_debug_info,+ shared_libs_symlink_tree = shared_libs_symlink_tree,+ dwp_symlink_tree = dwp_symlink_tree,+ )++LinkCmdParts = record(+ linker = [RunInfo, cmd_args],+ linker_flags = cmd_args,+ post_linker_flags = cmd_args,+ # linker + linker_flags, for convenience+ link_cmd = cmd_args,+)++def cxx_link_cmd_parts(toolchain: CxxToolchainInfo, executable: bool) -> LinkCmdParts:+ # `toolchain_linker_flags` can either be a list of strings, `cmd_args` or `None`,+ # so we need to do a bit more work to satisfy the type checker+ toolchain_linker_flags = toolchain.linker_info.linker_flags+ toolchain_post_linker_flags = toolchain.linker_info.post_linker_flags+ if toolchain_linker_flags == None:+ toolchain_linker_flags = cmd_args()+ elif not type(toolchain_linker_flags) == "cmd_args":+ toolchain_linker_flags = cmd_args(toolchain_linker_flags)++ if executable:+ toolchain_linker_flags = cmd_args(+ toolchain_linker_flags,+ toolchain.linker_info.executable_linker_flags,+ )++ if toolchain_post_linker_flags == None:+ toolchain_post_linker_flags = cmd_args()+ elif not type(toolchain_post_linker_flags) == "cmd_args":+ toolchain_post_linker_flags = cmd_args(toolchain_post_linker_flags)++ link_cmd = cmd_args(toolchain.linker_info.linker)+ link_cmd.add(toolchain_linker_flags)++ return LinkCmdParts(+ linker = toolchain.linker_info.linker,+ linker_flags = toolchain_linker_flags,+ post_linker_flags = toolchain_post_linker_flags,+ link_cmd = link_cmd,+ )
@@ -0,0 +1,46 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# An input to cxx compilation, consisting of a file to compile and optional+# file specific flags to compile with.+CxxSrcWithFlags = record(+ file = field(Artifact),+ flags = field(list[[ResolvedStringWithMacros, str]], []),+ # If we have multiple source entries with same files but different flags,+ # specify an index so we can differentiate them. Otherwise, use None.+ index = field([int, None], None),+ is_header = field(bool, False),+)++# The source files+def get_srcs_with_flags(ctx: AnalysisContext, additional_srcs: list = []) -> list[CxxSrcWithFlags]:+ all_srcs = ctx.attrs.srcs + additional_srcs++ # src -> flags_hash -> flags+ flags_sets_by_src = {}+ for x in all_srcs:+ if type(x) == type(()):+ artifact = x[0]+ flags = x[1]+ else:+ artifact = x+ flags = []++ flags_hash = hash(str(flags))+ flag_sets = flags_sets_by_src.setdefault(artifact, {})+ flag_sets[flags_hash] = flags++ # Go through collected (source, flags) pair and set the index field if there are duplicate source files+ cxx_src_with_flags_records = []+ for artifact, flag_sets in flags_sets_by_src.items():+ needs_indices = len(flag_sets) > 1+ for i, flags in enumerate(flag_sets.values()):+ index = i if needs_indices else None+ cxx_src_with_flags_records.append(CxxSrcWithFlags(file = artifact, flags = flags, index = index))++ return cxx_src_with_flags_records
@@ -0,0 +1,482 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:is_full_meta_repo.bzl", "is_full_meta_repo")+load("@prelude//cxx:compile.bzl", "compiler_info_with_toolchain_argsfiles")+load(+ "@prelude//cxx:cxx_toolchain_types.bzl",+ "AsCompilerInfo",+ "AsmCompilerInfo",+ "BinaryUtilitiesInfo",+ "CCompilerInfo",+ "CudaCompilerInfo",+ "CvtresCompilerInfo",+ "CxxCompilerInfo",+ "CxxInternalTools",+ "CxxObjectFormat",+ "DepTrackingMode",+ "HipCompilerInfo",+ "IncrementalLinkingMode",+ "LinkerInfo",+ "LinkerType",+ "ObjcCompilerInfo",+ "ObjcxxCompilerInfo",+ "PicBehavior",+ "RcCompilerInfo",+ "ShlibInterfacesMode",+ "StripFlagsInfo",+ "cxx_toolchain_infos",+)+load("@prelude//cxx:cxx_utility.bzl", "cxx_toolchain_allow_cache_upload_args")+load("@prelude//cxx:debug.bzl", "SplitDebugMode")+load("@prelude//cxx:headers.bzl", "HeaderMode", "HeadersAsRawHeadersMode", "RawHeadersAsHeadersMode")+load("@prelude//cxx:linker.bzl", "LINKERS", "is_pdb_generated")+load("@prelude//decls:cxx_rules.bzl", "cxx_rules")+load(+ "@prelude//linking:link_info.bzl",+ "LibOutputStyle",+ "LinkOrdering",+ "LinkStyle",+)+load("@prelude//linking:linkable_graph.bzl", "LinkableGraph")+load("@prelude//linking:lto.bzl", "LtoMode", "lto_compiler_flags")+load(+ "@prelude//linking:shared_libraries.bzl",+ "SharedLibraryInfo",+)+load("@prelude//target_stats:target_stats_tools.bzl", "TargetStatsToolsInfo")+load("@prelude//utils:utils.bzl", "flatten", "value_or")++def cxx_toolchain_impl(ctx):+ c_compiler = _get_maybe_wrapped_msvc(+ ctx.attrs.c_compiler[RunInfo], ctx.attrs.c_compiler_type or ctx.attrs.compiler_type, ctx.attrs._msvc_hermetic_exec[RunInfo]+ )++ lto_mode = LtoMode(ctx.attrs.lto_mode)+ if lto_mode != LtoMode("none"):+ object_format = "bitcode"+ else:+ object_format = ctx.attrs.object_format if ctx.attrs.object_format else "native"++ c_lto_flags = lto_compiler_flags(lto_mode)++ c_info = CCompilerInfo(+ compiler = c_compiler,+ compiler_type = ctx.attrs.c_compiler_type or ctx.attrs.compiler_type,+ compiler_flags = cmd_args(ctx.attrs.c_compiler_flags, c_lto_flags),+ preprocessor = c_compiler,+ preprocessor_flags = cmd_args(ctx.attrs.c_preprocessor_flags),+ allow_cache_upload = ctx.attrs.c_compiler_allow_cache_upload,+ supports_content_based_paths = ctx.attrs.supports_content_based_paths,+ )+ objc_info = ObjcCompilerInfo(+ compiler = c_compiler,+ compiler_type = ctx.attrs.c_compiler_type or ctx.attrs.compiler_type,+ compiler_flags = cmd_args(ctx.attrs.c_compiler_flags, c_lto_flags, ctx.attrs.objc_compiler_flags),+ preprocessor = c_compiler,+ preprocessor_flags = cmd_args(ctx.attrs.c_preprocessor_flags),+ allow_cache_upload = ctx.attrs.c_compiler_allow_cache_upload,+ supports_content_based_paths = ctx.attrs.supports_content_based_paths,+ )+ cxx_compiler = _get_maybe_wrapped_msvc(+ ctx.attrs.cxx_compiler[RunInfo], ctx.attrs.cxx_compiler_type or ctx.attrs.compiler_type, ctx.attrs._msvc_hermetic_exec[RunInfo]+ )+ cxx_info = CxxCompilerInfo(+ compiler = cxx_compiler,+ compiler_type = ctx.attrs.cxx_compiler_type or ctx.attrs.compiler_type,+ compiler_flags = cmd_args(ctx.attrs.cxx_compiler_flags, c_lto_flags),+ preprocessor = cxx_compiler,+ preprocessor_flags = cmd_args(ctx.attrs.cxx_preprocessor_flags),+ allow_cache_upload = ctx.attrs.cxx_compiler_allow_cache_upload,+ supports_two_phase_compilation = ctx.attrs.supports_two_phase_compilation,+ supports_content_based_paths = ctx.attrs.supports_content_based_paths,+ )+ objcxx_info = ObjcxxCompilerInfo(+ compiler = cxx_compiler,+ compiler_type = ctx.attrs.cxx_compiler_type or ctx.attrs.compiler_type,+ compiler_flags = cmd_args(ctx.attrs.cxx_compiler_flags, c_lto_flags, ctx.attrs.objcxx_compiler_flags),+ preprocessor = cxx_compiler,+ preprocessor_flags = cmd_args(ctx.attrs.cxx_preprocessor_flags),+ allow_cache_upload = ctx.attrs.cxx_compiler_allow_cache_upload,+ supports_content_based_paths = ctx.attrs.supports_content_based_paths,+ )+ asm_info = (+ AsmCompilerInfo(+ compiler = ctx.attrs.asm_compiler[RunInfo],+ compiler_type = ctx.attrs.asm_compiler_type or ctx.attrs.compiler_type,+ compiler_flags = cmd_args(ctx.attrs.asm_compiler_flags),+ preprocessor_flags = cmd_args(ctx.attrs.asm_preprocessor_flags),+ supports_content_based_paths = ctx.attrs.supports_content_based_paths,+ )+ if ctx.attrs.asm_compiler+ else None+ )+ as_info = (+ AsCompilerInfo(+ compiler = ctx.attrs.assembler[RunInfo],+ compiler_type = ctx.attrs.assembler_type or ctx.attrs.compiler_type,+ compiler_flags = cmd_args(ctx.attrs.assembler_flags),+ preprocessor_flags = cmd_args(ctx.attrs.assembler_preprocessor_flags),+ supports_content_based_paths = ctx.attrs.supports_content_based_paths,+ )+ if ctx.attrs.assembler+ else None+ )+ cuda_info = (+ CudaCompilerInfo(+ compiler = ctx.attrs.cuda_compiler[RunInfo],+ compiler_for_dryrun = ctx.attrs.cuda_compiler_for_dryrun[RunInfo] if ctx.attrs.cuda_compiler_for_dryrun else None,+ compiler_type = ctx.attrs.cuda_compiler_type or ctx.attrs.compiler_type,+ compiler_flags = cmd_args(ctx.attrs.cuda_compiler_flags),+ preprocessor_flags = cmd_args(ctx.attrs.cuda_preprocessor_flags),+ allow_cache_upload = ctx.attrs.cuda_compiler_allow_cache_upload,+ supports_content_based_paths = ctx.attrs.supports_content_based_paths,+ )+ if ctx.attrs.cuda_compiler+ else None+ )+ hip_info = (+ HipCompilerInfo(+ compiler = ctx.attrs.hip_compiler[RunInfo],+ compiler_type = ctx.attrs.hip_compiler_type or ctx.attrs.compiler_type,+ compiler_flags = cmd_args(ctx.attrs.hip_compiler_flags),+ preprocessor_flags = cmd_args(ctx.attrs.hip_preprocessor_flags),+ )+ if ctx.attrs.hip_compiler+ else None+ )+ cvtres_info = (+ CvtresCompilerInfo(+ compiler = ctx.attrs.cvtres_compiler[RunInfo],+ compiler_type = ctx.attrs.cvtres_compiler_type or ctx.attrs.compiler_type,+ compiler_flags = cmd_args(ctx.attrs.cvtres_compiler_flags),+ preprocessor_flags = cmd_args(ctx.attrs.cvtres_preprocessor_flags),+ )+ if ctx.attrs.cvtres_compiler+ else None+ )+ rc_info = (+ RcCompilerInfo(+ compiler = ctx.attrs.rc_compiler[RunInfo],+ compiler_type = ctx.attrs.rc_compiler_type or ctx.attrs.compiler_type,+ compiler_flags = cmd_args(ctx.attrs.rc_compiler_flags),+ preprocessor_flags = cmd_args(ctx.attrs.rc_preprocessor_flags),+ )+ if ctx.attrs.rc_compiler+ else None+ )++ c_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "c", CCompilerInfo, c_info)+ objc_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "objc", ObjcCompilerInfo, objc_info)+ cxx_info = compiler_info_with_toolchain_argsfiles(+ ctx.actions,+ "cxx",+ CxxCompilerInfo,+ cxx_info,+ # Only the cxx info can be precompiled for C++20 modules.+ precompile_filter = ctx.attrs.internal_tools[CxxInternalTools].filter_argsfile,+ )+ objcxx_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "objcxx", ObjcxxCompilerInfo, objcxx_info)+ asm_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "asm", AsmCompilerInfo, asm_info)+ as_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "as", AsCompilerInfo, as_info)+ cuda_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "cuda", CudaCompilerInfo, cuda_info)+ hip_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "hip", HipCompilerInfo, hip_info)+ cvtres_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "cvtres", CvtresCompilerInfo, cvtres_info)+ rc_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "rc", RcCompilerInfo, rc_info)++ linker_type = LinkerType(ctx.attrs.linker_type)+ linker_info = LinkerInfo(+ archiver = ctx.attrs.archiver[RunInfo],+ archiver_flags = cmd_args(ctx.attrs.archiver_flags),+ archiver_reads_inputs = ctx.attrs.archiver_reads_inputs,+ archiver_supports_argfiles = ctx.attrs.archiver_supports_argfiles,+ archiver_type = ctx.attrs.archiver_type,+ archive_contents = ctx.attrs.archive_contents,+ archive_objects_locally = False,+ archive_symbol_table = ctx.attrs.archive_symbol_table,+ binary_extension = value_or(ctx.attrs.binary_extension, ""),+ extra_outputs = ctx.attrs.extra_linker_outputs,+ generate_linker_maps = ctx.attrs.generate_linker_maps,+ generate_gc_sections = ctx.attrs.generate_gc_sections,+ is_pdb_generated = is_pdb_generated(linker_type, ctx.attrs.linker_flags),+ link_binaries_locally = not value_or(ctx.attrs.cache_links, True),+ link_libraries_locally = False,+ link_style = LinkStyle(ctx.attrs.link_style),+ link_weight = ctx.attrs.link_weight,+ link_ordering = ctx.attrs.link_ordering,+ linker = ctx.attrs.linker[RunInfo],+ linker_flags = cmd_args(ctx.attrs.linker_flags, c_lto_flags),+ executable_linker_flags = ctx.attrs.executable_linker_flags,+ binary_linker_flags = ctx.attrs.binary_linker_flags,+ dist_thin_lto_codegen_flags = cmd_args(ctx.attrs.dist_thin_lto_codegen_flags) if ctx.attrs.dist_thin_lto_codegen_flags else cmd_args(),+ post_linker_flags = cmd_args(ctx.attrs.post_linker_flags),+ link_metadata_flag = ctx.attrs.link_metadata_flag,+ lto_mode = lto_mode,+ mk_shlib_intf = ctx.attrs.shared_library_interface_producer,+ object_file_extension = ctx.attrs.object_file_extension or "o",+ shlib_interfaces = ShlibInterfacesMode(ctx.attrs.shared_library_interface_mode),+ independent_shlib_interface_linker_flags = ctx.attrs.shared_library_interface_flags,+ requires_archives = value_or(ctx.attrs.requires_archives, True),+ requires_objects = value_or(ctx.attrs.requires_objects, False),+ sanitizer_runtime_enabled = ctx.attrs.sanitizer_runtime_enabled,+ sanitizer_runtime_files = flatten([runtime_file[DefaultInfo].default_outputs for runtime_file in ctx.attrs.sanitizer_runtime_files]),+ runtime_library_files = [+ dep[LinkableGraph].nodes.value.linkable.link_infos[LibOutputStyle("pic_archive")].default for dep in ctx.attrs.runtime_library_files+ ],+ supports_distributed_thinlto = ctx.attrs.supports_distributed_thinlto,+ shared_dep_runtime_ld_flags = ctx.attrs.shared_dep_runtime_ld_flags,+ shared_library_name_default_prefix = _get_shared_library_name_default_prefix(ctx),+ shared_library_name_format = _get_shared_library_name_format(ctx),+ shared_library_versioned_name_format = _get_shared_library_versioned_name_format(ctx),+ static_dep_runtime_ld_flags = ctx.attrs.static_dep_runtime_ld_flags,+ static_library_extension = ctx.attrs.static_library_extension or "a",+ static_pic_dep_runtime_ld_flags = ctx.attrs.static_pic_dep_runtime_ld_flags,+ thin_lto_premerger_enabled = ctx.attrs.thin_lto_premerger_enabled,+ thin_lto_double_codegen_enabled = ctx.attrs.thin_lto_double_codegen_enabled,+ type = linker_type,+ use_archiver_flags = ctx.attrs.use_archiver_flags,+ incremental_linking = ctx.attrs.incremental_linking,+ supports_content_based_paths_for_archiving = ctx.attrs.supports_content_based_paths_for_archiving,+ supports_shared_libraries = ctx.attrs.supports_shared_libraries,+ )++ utilities_info = BinaryUtilitiesInfo(+ bolt = ctx.attrs.bolt[RunInfo] if ctx.attrs.bolt else None,+ custom_tools = {name: dep[RunInfo] for name, dep in ctx.attrs.custom_tools.items()},+ elf_stamp = ctx.attrs.elf_stamp[RunInfo] if ctx.attrs.elf_stamp else None,+ nm = ctx.attrs.nm[RunInfo],+ objcopy = ctx.attrs.objcopy_for_shared_library_interface[RunInfo],+ objdump = ctx.attrs.objdump[RunInfo] if ctx.attrs.objdump else None,+ ranlib = ctx.attrs.ranlib[RunInfo] if ctx.attrs.ranlib else None,+ strip = ctx.attrs.strip[RunInfo],+ dwp = ctx.attrs.dwp[RunInfo] if ctx.attrs.dwp else None,+ )++ strip_flags_info = StripFlagsInfo(+ strip_debug_flags = ctx.attrs.strip_debug_flags,+ strip_non_global_flags = ctx.attrs.strip_non_global_flags,+ strip_all_flags = ctx.attrs.strip_all_flags,+ )++ platform_name = ctx.attrs.platform_name or ctx.attrs.name+ return [+ DefaultInfo(),+ ] + cxx_toolchain_infos(+ as_compiler_info = as_info,+ asm_compiler_info = asm_info,+ binary_utilities_info = utilities_info,+ bolt_enabled = value_or(ctx.attrs.bolt_enabled, False),+ cell_to_path_prefix_map = ctx.attrs.cell_to_path_prefix_map,+ c_compiler_info = c_info,+ clang_remarks = ctx.attrs.clang_remarks,+ clang_llvm_statistics = value_or(ctx.attrs.clang_llvm_statistics, False),+ clang_trace = value_or(ctx.attrs.clang_trace, False),+ cpp_dep_tracking_mode = DepTrackingMode(ctx.attrs.cpp_dep_tracking_mode),+ cuda_compiler_info = cuda_info,+ cuda_dep_tracking_mode = DepTrackingMode(ctx.attrs.cuda_dep_tracking_mode),+ cvtres_compiler_info = cvtres_info,+ cxx_compiler_info = cxx_info,+ dumpbin_toolchain_path = ctx.attrs._dumpbin_toolchain_path[DefaultInfo].default_outputs[0] if ctx.attrs._dumpbin_toolchain_path else None,+ gcno_files = value_or(ctx.attrs.gcno_files, False),+ header_mode = _get_header_mode(ctx),+ headers_as_raw_headers_mode = HeadersAsRawHeadersMode(ctx.attrs.headers_as_raw_headers_mode) if ctx.attrs.headers_as_raw_headers_mode != None else None,+ hip_compiler_info = hip_info,+ internal_tools = ctx.attrs.internal_tools[CxxInternalTools],+ libclang = ctx.attrs.libclang,+ linker_info = linker_info,+ lipo = ctx.attrs.lipo[RunInfo] if ctx.attrs.lipo else None,+ llvm_cgdata = ctx.attrs.llvm_cgdata[RunInfo] if ctx.attrs.llvm_cgdata else None,+ llvm_link = ctx.attrs.llvm_link[RunInfo] if ctx.attrs.llvm_link else None,+ objc_compiler_info = objc_info,+ objcxx_compiler_info = objcxx_info,+ object_format = CxxObjectFormat(object_format),+ pass_plugin = ctx.attrs.pass_plugin[DefaultInfo].default_outputs[0] if ctx.attrs.pass_plugin else None,+ compiler_flavor_flags = ctx.attrs.compiler_flavor_flags,+ pic_behavior = PicBehavior(ctx.attrs.pic_behavior),+ platform_deps_aliases = ctx.attrs.platform_deps_aliases,+ platform_name = platform_name,+ raw_headers_as_headers_mode = RawHeadersAsHeadersMode(ctx.attrs.raw_headers_as_headers_mode) if ctx.attrs.raw_headers_as_headers_mode != None else None,+ rc_compiler_info = rc_info,+ remap_cwd = ctx.attrs.remap_cwd,+ materialize_external_debug_info = ctx.attrs.materialize_external_debug_info,+ split_debug_mode = SplitDebugMode(ctx.attrs.split_debug_mode),+ strip_flags_info = strip_flags_info,+ minimum_os_version = ctx.attrs.minimum_os_version,+ # TODO(T138705365): Turn on dep files by default+ use_dep_files = value_or(ctx.attrs.use_dep_files, _get_default_use_dep_files(platform_name)),+ default_deps = ctx.attrs.default_deps,+ target_stats_tools = ctx.attrs.target_stats_tools[TargetStatsToolsInfo] if ctx.attrs.target_stats_tools else None,+ )++def cxx_toolchain_extra_attributes(is_toolchain_rule):+ dep_type = attrs.exec_dep if is_toolchain_rule else attrs.dep+ return {+ "archive_symbol_table": attrs.bool(default = True),+ "archiver": dep_type(providers = [RunInfo]),+ "archiver_reads_inputs": attrs.bool(default = True),+ "archiver_supports_argfiles": attrs.bool(default = False),+ "asm_compiler": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "asm_preprocessor": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "assembler": dep_type(providers = [RunInfo]),+ "assembler_preprocessor": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "bolt": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "bolt_enabled": attrs.bool(default = False),+ "c_compiler": dep_type(providers = [RunInfo]),+ "cell_to_path_prefix_map": attrs.dict(key = attrs.string(), value = attrs.string(), default = {}),+ "clang_llvm_statistics": attrs.option(attrs.bool(), default = None),+ "clang_remarks": attrs.option(attrs.string(), default = None),+ "clang_trace": attrs.option(attrs.bool(), default = None),+ "compiler_flavor_flags": attrs.dict(key = attrs.string(), value = attrs.list(attrs.string()), default = {}),+ "cpp_dep_tracking_mode": attrs.enum(DepTrackingMode.values(), default = "makefile"),+ "cuda_compiler": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "cuda_compiler_for_dryrun": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "cuda_dep_tracking_mode": attrs.enum(DepTrackingMode.values(), default = "makefile"),+ "custom_tools": attrs.dict(key = attrs.string(), value = dep_type(providers = [RunInfo]), default = {}),+ "cvtres_compiler": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "cxx_compiler": dep_type(providers = [RunInfo]),+ "default_deps": attrs.list(dep_type(), default = []),+ "dwp": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "elf_stamp": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "gcno_files": attrs.bool(default = False),+ "generate_gc_sections": attrs.bool(default = False),+ "generate_linker_maps": attrs.bool(default = False),+ "hip_compiler": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "incremental_linking": attrs.enum(IncrementalLinkingMode.values(), default = "disabled"),+ "internal_tools": dep_type(providers = [CxxInternalTools], default = "prelude//cxx/tools:internal_tools"),+ "libclang": attrs.option(dep_type(providers = [SharedLibraryInfo]), default = None),+ "link_ordering": attrs.enum(LinkOrdering.values(), default = "preorder"),+ "link_weight": attrs.int(default = 1),+ "linker": dep_type(providers = [RunInfo]),+ "lipo": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "llvm_cgdata": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "llvm_link": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "lto_mode": attrs.enum(LtoMode.values(), default = "none"),+ "materialize_external_debug_info": attrs.bool(default = True),+ # Darwin only: the deployment target to use for this build+ "minimum_os_version": attrs.option(attrs.string(), default = None),+ "nm": dep_type(providers = [RunInfo]),+ "objcopy_for_shared_library_interface": dep_type(providers = [RunInfo]),+ "objdump": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "object_format": attrs.enum(CxxObjectFormat.values(), default = "native"),+ "pass_plugin": attrs.option(dep_type(providers = [DefaultInfo]), default = None),+ "pic_behavior": attrs.enum(PicBehavior.values(), default = "supported"),+ # A placeholder tool that can be used to set up toolchain constraints.+ # Useful when fat and thin toolchahins share the same underlying tools via `command_alias()`,+ # which requires setting up separate platform-specific aliases with the correct constraints.+ "placeholder_tool": attrs.option(dep_type(providers = [RunInfo]), default = None),+ # Used for regex matching any 'platform_*' attributes.+ "platform_deps_aliases": attrs.option(attrs.list(attrs.string()), default = None),+ # Used for regex matching any 'platform_*' attributes.+ "platform_name": attrs.option(attrs.string(), default = None),+ "private_headers_symlinks_enabled": attrs.bool(default = True),+ "public_headers_symlinks_enabled": attrs.bool(default = True),+ "ranlib": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "rc_compiler": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "remap_cwd": attrs.bool(default = False),+ "requires_objects": attrs.bool(default = False),+ "runtime_library_files": attrs.set(attrs.dep(), sorted = True, default = []), # Use `attrs.dep()` as it's not a tool, always propagate target platform+ "sanitizer_runtime_enabled": attrs.bool(default = False),+ "sanitizer_runtime_files": attrs.set(attrs.dep(), sorted = True, default = []), # Use `attrs.dep()` as it's not a tool, always propagate target platform+ "shared_library_interface_mode": attrs.enum(ShlibInterfacesMode.values(), default = "disabled"),+ "shared_library_interface_producer": attrs.option(dep_type(providers = [RunInfo]), default = None),+ "split_debug_mode": attrs.enum(SplitDebugMode.values(), default = "none"),+ "strip": dep_type(providers = [RunInfo]),+ "supports_content_based_paths": attrs.bool(default = False),+ "supports_content_based_paths_for_archiving": attrs.bool(default = False),+ "supports_distributed_thinlto": attrs.bool(default = False),+ "supports_shared_libraries": attrs.bool(default = True),+ "supports_two_phase_compilation": attrs.bool(default = False),+ "target_stats_tools": attrs.option(dep_type(providers = [TargetStatsToolsInfo]), default = None),+ "thin_lto_double_codegen_enabled": attrs.bool(default = False),+ "thin_lto_premerger_enabled": attrs.bool(default = False),+ "use_archiver_flags": attrs.bool(default = True),+ "use_dep_files": attrs.option(attrs.bool(), default = None),+ # TODO(scottcao): Figure out a slightly better way to integrate this. In theory, this is only needed for clang toolchain.+ # If we were using msvc, we should be able to use dumpbin directly.+ "_dumpbin_toolchain_path": attrs.default_only(+ attrs.option(+ dep_type(providers = [DefaultInfo]),+ default = select({+ "DEFAULT": None,+ "ovr_config//os:windows": select({+ # Unfortunately, it seems like an unresolved select when resolve exec platforms causes the whole resolution+ # to fail, so I need a DEFAULT here when some target without cpu constraint tries to configure against the+ # windows exec platform.+ "DEFAULT": None,+ # FIXME: prelude// should be standalone (not refer to fbsource//)+ "ovr_config//cpu:x86_32": "fbsource//third-party/toolchains/visual_studio:cl_x86_and_tools",+ "ovr_config//cpu:x86_64": "fbsource//third-party/toolchains/visual_studio:cl_x64_and_tools",+ }),+ })+ if is_full_meta_repo()+ else None,+ )+ ),+ "_msvc_hermetic_exec": attrs.default_only(dep_type(providers = [RunInfo], default = "prelude//windows/tools:msvc_hermetic_exec")),+ } | cxx_toolchain_allow_cache_upload_args()++def _cxx_toolchain_inheriting_target_platform_attrs():+ attrs = dict(cxx_rules.cxx_toolchain.attrs)+ attrs.update(cxx_toolchain_extra_attributes(is_toolchain_rule = True))+ return attrs++cxx_toolchain_inheriting_target_platform = rule(+ impl = cxx_toolchain_impl,+ attrs = _cxx_toolchain_inheriting_target_platform_attrs(),+ is_toolchain_rule = True,+)++_APPLE_PLATFORM_NAME_PREFIXES = [+ "iphonesimulator",+ "iphoneos",+ "maccatalyst",+ "macosx",+ "watchos",+ "watchsimulator",+ "appletvos",+ "appletvsimulator",+]++def _get_default_use_dep_files(platform_name: str) -> bool:+ # All Apple platforms use Clang which supports the standard dep files format+ for apple_platform_name_prefix in _APPLE_PLATFORM_NAME_PREFIXES:+ if apple_platform_name_prefix in platform_name:+ return True+ return False++def _get_header_mode(ctx: AnalysisContext) -> HeaderMode:+ if ctx.attrs.use_header_map:+ if ctx.attrs.private_headers_symlinks_enabled or ctx.attrs.public_headers_symlinks_enabled:+ return HeaderMode("symlink_tree_with_header_map")+ else:+ return HeaderMode("header_map_only")+ else:+ return HeaderMode("symlink_tree_only")++def _get_shared_library_name_default_prefix(ctx: AnalysisContext) -> str:+ extension = ctx.attrs.shared_library_extension+ return "" if extension == "dll" else "lib"++def _get_shared_library_name_format(ctx: AnalysisContext) -> str:+ linker_type = LinkerType(ctx.attrs.linker_type)+ extension = ctx.attrs.shared_library_extension+ if extension == "":+ extension = LINKERS[linker_type].default_shared_library_extension+ return "{}." + extension++def _get_shared_library_versioned_name_format(ctx: AnalysisContext) -> str:+ linker_type = LinkerType(ctx.attrs.linker_type)+ extension_format = ctx.attrs.shared_library_versioned_extension_format.replace("%s", "{}")+ if extension_format == "":+ extension_format = LINKERS[linker_type].default_shared_library_versioned_extension_format+ return "{}." + extension_format++def _get_maybe_wrapped_msvc(compiler: RunInfo, compiler_type: str, msvc_hermetic_exec: RunInfo) -> RunInfo:+ if compiler_type == "windows":+ return RunInfo(args = cmd_args(msvc_hermetic_exec, compiler))+ return compiler
@@ -0,0 +1,33 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++def cxx_toolchain_macro_impl(cxx_toolchain_rule = None, **kwargs):+ # `generate_linker_maps` set in order of priority:+ # - Explicit attribute on the cxx_toolchain() target+ # - Constraint on the target platform+ # - `cxx.linker_map_enabled` buckconfig+ if "generate_linker_maps" not in kwargs:+ linker_map_enabled = read_root_config("cxx", "linker_map_enabled", "").lower() == "true"+ kwargs["generate_linker_maps"] = select({+ "DEFAULT": linker_map_enabled,+ "config//linker/constraints:generate_linker_maps_disabled": False,+ "config//linker/constraints:generate_linker_maps_enabled": True,+ })++ bitcode = read_root_config("cxx", "bitcode")+ if bitcode != None:+ if bitcode.lower() == "false":+ kwargs["object_format"] = "native"+ elif bitcode.lower() == "true":+ kwargs["object_format"] = "bitcode"+ elif bitcode.lower() == "embed":+ kwargs["object_format"] = "embedded-bitcode"+ else:+ kwargs["object_format"] = "native"++ cxx_toolchain_rule(**kwargs)
@@ -0,0 +1,531 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//cxx:cxx_apple_linker_flags.bzl", "apple_extra_darwin_linker_flags", "apple_format_target_triple", "is_valid_apple_platform_name")+load("@prelude//cxx:debug.bzl", "SplitDebugMode")+load("@prelude//target_stats:target_stats_tools.bzl", "TargetStatsToolsInfo")++CXX_COMPILER_TYPES = ["clang", "clang_cl", "clang_windows", "gcc", "windows", "windows_ml64"]++LinkerType = enum("gnu", "darwin", "windows", "wasm")++IncrementalLinkingMode = enum("disabled", "supported", "enabled")++ShlibInterfacesMode = enum(+ "disabled",+ "defined_only", # Generate a "stub" shared library by only linking object files passed to the link, ignoring static libraries or dynamic libraries linked against.+ # This known to be incorrect in the presence of static libraries, as they won't be represented in the interface.+ "stub_from_library", # Generate an interface from the completed shared library via some external tool.+ "stub_from_linker_invocation", # For linkers that support it, generate an interface from the linker invocation that would ordinarily produce the shared library, adding some extra flags+)++# TODO(T110378149): Consider whether it makes sense to move these things to+# configurations/constraints rather than part of the toolchain.+LinkerInfo = provider(+ # @unsorted-dict-items+ fields = {+ "archiver": provider_field(typing.Any, default = None),+ "archiver_flags": provider_field(typing.Any, default = None),+ "archiver_reads_inputs": provider_field(bool, default = True),+ "archiver_supports_argfiles": provider_field(typing.Any, default = None),+ "archiver_type": provider_field(typing.Any, default = None),+ "archive_contents": provider_field(typing.Any, default = "normal"),+ "archive_objects_locally": provider_field(typing.Any, default = None),+ "archive_symbol_table": provider_field(bool, default = True),+ # "archiver_platform",+ # "" on Unix, "exe" on Windows+ "binary_extension": provider_field(typing.Any, default = None), # str+ "dist_thin_lto_codegen_flags": provider_field([cmd_args, None], default = None),+ "extra_outputs": provider_field(list[str], default = []),+ "generate_linker_maps": provider_field(typing.Any, default = None), # bool+ "generate_gc_sections": provider_field(typing.Any, default = None), # bool+ # Whether to run native links locally. We support this for fbcode platforms+ # to avoid issues with C++ static links (see comment in+ # `platform/cxx_toolchains.bzl` for details).+ "link_binaries_locally": provider_field(typing.Any, default = None),+ # Whether to run native shared library links locally. For certain use cases+ # (e.g., large Apple frameworks), it's more efficient to link locally due+ # GiBs of object files (which can also lead to RE errors/timesouts etc).+ "link_libraries_locally": provider_field(typing.Any, default = None),+ "link_style": provider_field(typing.Any, default = None), # LinkStyle+ "link_weight": provider_field(int, default = 1), # int+ "link_ordering": provider_field(typing.Any, default = None), # LinkOrdering+ "linker": provider_field(typing.Any, default = None),+ "linker_flags": provider_field(typing.Any, default = None),+ "executable_linker_flags": provider_field(typing.Any, default = []),+ "binary_linker_flags": provider_field(typing.Any, default = []),+ "link_metadata_flag": provider_field(str | None, default = None),+ "lto_mode": provider_field(typing.Any, default = None),+ "mk_shlib_intf": provider_field(typing.Any, default = None),+ # "o" on Unix, "obj" on Windows+ "object_file_extension": provider_field(typing.Any, default = None), # str+ "post_linker_flags": provider_field(typing.Any, default = None),+ # `LinkInfo`s (list[LinkInfo]) of the runtime libraries the toolchain provides.+ "runtime_library_files": provider_field(list[typing.Any], default = []),+ "sanitizer_runtime_enabled": provider_field(bool, default = False),+ "sanitizer_runtime_files": provider_field(list[Artifact], default = []),+ "shlib_interfaces": provider_field(ShlibInterfacesMode),+ "shared_dep_runtime_ld_flags": provider_field(typing.Any, default = None),+ # "lib" on Linux/Mac/Android, "" on Windows.+ "shared_library_name_default_prefix": provider_field(typing.Any, default = None), # str+ # "{}.so" on Linux, "{}.dylib" on Mac, "{}.dll" on Windows+ "shared_library_name_format": provider_field(typing.Any, default = None), # str+ "shared_library_versioned_name_format": provider_field(typing.Any, default = None), # str+ "static_dep_runtime_ld_flags": provider_field(typing.Any, default = None),+ # "a" on Unix, "lib" on Windows+ "static_library_extension": provider_field(typing.Any, default = None), # str+ "static_pic_dep_runtime_ld_flags": provider_field(typing.Any, default = None),+ "requires_archives": provider_field(typing.Any, default = None),+ "requires_objects": provider_field(typing.Any, default = None),+ "supports_distributed_thinlto": provider_field(typing.Any, default = None),+ "independent_shlib_interface_linker_flags": provider_field(typing.Any, default = None),+ "thin_lto_premerger_enabled": provider_field(bool, default = False),+ "thin_lto_double_codegen_enabled": provider_field(bool, default = False),+ "type": LinkerType,+ "use_archiver_flags": provider_field(typing.Any, default = None),+ "force_full_hybrid_if_capable": provider_field(typing.Any, default = None),+ "is_pdb_generated": provider_field(typing.Any, default = None), # bool+ # Flags to use to "sandbox" exported library linker flags.+ "push_pop_state_flags": provider_field(typing.Any, default = None),+ "supports_content_based_paths_for_archiving": provider_field(bool, default = False),+ "incremental_linking": provider_field(str, default = "disabled"),+ "supports_shared_libraries": provider_field(bool, default = True),+ },+)++BinaryUtilitiesInfo = provider(+ fields = {+ "bolt": provider_field(typing.Any, default = None),+ "custom_tools": provider_field(dict[str, RunInfo], default = {}),+ "dwp": provider_field(typing.Any, default = None),+ "elf_stamp": provider_field([RunInfo, None], default = None),+ "nm": provider_field(typing.Any, default = None),+ "objcopy": provider_field(typing.Any, default = None),+ "objdump": provider_field(typing.Any, default = None),+ "ranlib": provider_field(typing.Any, default = None),+ "strip": provider_field(typing.Any, default = None),+ }+)++StripFlagsInfo = provider(+ # @unsorted-dict-items+ fields = {+ "strip_debug_flags": provider_field(typing.Any, default = None), # [["str"], None]+ "strip_non_global_flags": provider_field(typing.Any, default = None), # [["str"], None]+ "strip_all_flags": provider_field(typing.Any, default = None), # [["str"], None]+ },+)++DepTrackingMode = enum(+ # MAKEFILE corresponds to `gcc -MD -MF depfile ...` on *nix+ "makefile",+ # SHOW_INCLUDES corresponds to `cl.exe /showIncludes ...` on windows+ "show_includes",+ # SHOW_HEADERS corresponds to `clang/gcc -H ...` on *nix+ "show_headers",+ # Some compilers - like ml64 - do not produce information about included files+ "none",+)++# TODO(T110378147): There's a bunch of info encoded in random places in buck+# derived from information in these toolchains but hardcoded (for example,+# which file extensions are preprocessable/compilable). We should figure out+# how to move most of that into these toolchain infos.+# TODO(T110378146): The inclusion of compiler and preprocessor in here is really+# just a legacy thing that was never cleaned up. Historically, buck supported a+# mode where compilation was done in two, explicitly separate phases+# (preprocess and then compile). We don't support that today, and including+# both of these mostly just ends up with added complexity and with us+# duplicating flags in command lines.++# In cxx_library, we support a bunch of different types of files (ex. cuda),+# the toolchain for these follow this common pattern.+_compiler_fields = [+ "compiler",+ "compiler_type",+ "compiler_flags",+ # An optional argsfile that contains the preprocessor flags and the compiler flags.+ "argsfile", # `cmd_args | None`+ # An optional argsfile that contains the preprocessor flags and the compiler flags,+ # formatted for xcode.+ "argsfile_xcode", # `cmd_args | None`+ # An optional copy of `argsfile` filtered for C++20 module precompilation,+ # as an `argsfile_with_artifacts()` value.+ "argsfile_precompile", # `cmd_args | None`+ "preprocessor",+ "preprocessor_type",+ "preprocessor_flags",+ # Controls cache upload for object files+ "allow_cache_upload",+ "supports_two_phase_compilation",+ "compiler_with_wrapper",+ "supports_content_based_paths",+]++AsCompilerInfo = provider(fields = _compiler_fields)+AsmCompilerInfo = provider(fields = _compiler_fields)+CCompilerInfo = provider(fields = _compiler_fields)+CudaCompilerInfo = provider(fields = _compiler_fields + ["compiler_for_dryrun"])+CvtresCompilerInfo = provider(fields = _compiler_fields)+CxxCompilerInfo = provider(fields = _compiler_fields)+HipCompilerInfo = provider(fields = _compiler_fields)+ObjcCompilerInfo = provider(fields = _compiler_fields)+ObjcxxCompilerInfo = provider(fields = _compiler_fields)+RcCompilerInfo = provider(fields = _compiler_fields)++def compiler_info_with_argsfiles(+ compiler_info: typing.Any, ctor: typing.Callable, argsfile: cmd_args, argsfile_xcode: cmd_args, argsfile_precompile: cmd_args | None = None+) -> typing.Any:+ fields = {k: getattr(compiler_info, k) for k in _compiler_fields}+ fields["argsfile"] = argsfile+ fields["argsfile_xcode"] = argsfile_xcode+ fields["argsfile_precompile"] = argsfile_precompile++ # CudaCompilerInfo carries fields beyond the shared set.+ compiler_for_dryrun = getattr(compiler_info, "compiler_for_dryrun", None)+ if compiler_for_dryrun != None:+ fields["compiler_for_dryrun"] = compiler_for_dryrun+ return ctor(**fields)++DistLtoToolsInfo = provider(+ fields = dict(+ planner = dict[LinkerType, RunInfo],+ opt = dict[LinkerType, RunInfo],+ prepare = dict[LinkerType, RunInfo],+ copy = RunInfo,+ archive_mapper = RunInfo,+ compiler_stats_merger = RunInfo,+ )+)++CxxInternalTools = provider(+ fields = dict(+ check_nonempty_output = RunInfo,+ clang_tidy_wrapper = RunInfo,+ concatenate_diagnostics = RunInfo,+ dep_file_processor = RunInfo,+ dist_lto = DistLtoToolsInfo,+ filter_argsfile = RunInfo,+ hmap_wrapper = RunInfo,+ make_comp_db = RunInfo,+ remap_cwd = RunInfo,+ serialized_diagnostics_to_json_wrapper = RunInfo,+ stderr_to_file = RunInfo,+ stub_header_unit = RunInfo,+ )+)++CxxObjectFormat = enum(+ "native",+ "bitcode",+ "embedded-bitcode",+ "swift",+)++# - For targets being built for x86_64, arm64, the fPIC flag isn't respected. Everything is fPIC.+# - For targets being built for Windows, nothing is fPIC. The flag is ignored.+# - There are many platforms (linux, etc.) where the fPIC flag is supported.+#+# As a result, we can end-up in a place where you pic + non-pic artifacts are requested+# but the platform will produce the exact same output (despite the different files).+#+# The PicBehavior is applied to avoid using link or output styles that are unsupported by a toolchain.+PicBehavior = enum(+ # Regardless of whether -fPIC is specified explicitly+ # every compiled artifact will have a position-independent representation.+ # This should be the default when targeting x86_64 + arm64.+ "always_enabled",+ # The -fPIC flag is known and changes the compiled artifact.+ "supported",+ # The -fPIC flag is unknown to this platform.+ "not_supported",+)++# Additional behavior for how to handle runtime dependencies+RuntimeDependencyHandling = enum(+ # Do no additional handling+ "no_symlink",+ # Always include runtime dependencies in a symlink tree, regardless+ # of whether shared linkage is used or not. Only include first level deps.+ "symlink_single_level_only",+ # Always include runtime dependencies in a symlink tree, regardless+ # of whether shared linkage is used or not. Include transitive deps.+ "symlink",+)++# TODO(T110378094): We should consider if we can change this from a hardcoded+# list of compiler_info to something more general. We could maybe do a list of+# compiler_info where each one also declares what extensions it supports.+# TODO(T110378145): Could we split up this Info so that each of the compilers+# could be provided by different dependencies? That would allow a target to+# only depend on the compilers it actually needs.+CxxToolchainInfo = provider(+ fields = {+ "as_compiler_info": provider_field(typing.Any, default = None),+ "asm_compiler_info": provider_field(typing.Any, default = None),+ "binary_utilities_info": provider_field(typing.Any, default = None),+ "bolt_enabled": provider_field(typing.Any, default = None),+ "c_compiler_info": provider_field(typing.Any, default = None),+ # Maps cell names to their repo-relative path prefix. Used by coverage+ # prefix maps to translate cell-relative paths to repo-relative paths.+ # e.g. {"fbcode": "fbcode"} means cell "fbcode" maps to the "fbcode/"+ # subdirectory. Cells not in the map are assumed to be the repo root.+ "cell_to_path_prefix_map": provider_field(dict[str, str], default = {}),+ "clang_llvm_statistics": provider_field(typing.Any, default = None),+ "clang_remarks": provider_field(typing.Any, default = None),+ # Produce a time profiler JSON report by calling clang with `-ftime-trace`.+ "clang_trace": provider_field(bool, default = False),+ "compiler_flavor_flags": provider_field(typing.Any, default = {}),+ "cpp_dep_tracking_mode": provider_field(typing.Any, default = None),+ "cuda_compiler_info": provider_field(typing.Any, default = None),+ "cuda_dep_tracking_mode": provider_field(typing.Any, default = None),+ "cvtres_compiler_info": provider_field(typing.Any, default = None),+ "cxx_compiler_info": provider_field(typing.Any, default = None),+ "cxx_error_handler": provider_field(typing.Any, default = None),+ "default_deps": provider_field(list[Dependency], default = []),+ "dumpbin_toolchain_path": provider_field(typing.Any, default = None),+ "gcno_files": provider_field(typing.Any, default = None),+ "header_mode": provider_field(typing.Any, default = None),+ "headers_as_raw_headers_mode": provider_field(typing.Any, default = None),+ "hip_compiler_info": provider_field(typing.Any, default = None),+ # See prelude/cxx/hip_debug_extract.bzl. `hip_debug_extract` is the+ # wrapper RunInfo (None on unsupported ROCm).+ "hip_debug_extract": provider_field([RunInfo, None], default = None),+ "hip_device_debug_extract": provider_field(bool, default = False),+ "hip_gpu_archs": provider_field(list[str], default = []),+ "internal_tools": provider_field(CxxInternalTools),+ "libclang": provider_field(typing.Any, default = None),+ "linker_info": provider_field(typing.Any, default = None),+ "lipo": provider_field([RunInfo, None], default = None),+ "llvm_cgdata": provider_field([RunInfo, None], default = None),+ "llvm_link": provider_field(typing.Any, default = None),+ # Whether a top-level binary's unpacked external debug info (e.g.+ # split-dwarf .dwo files) is materialized as part of building it, via+ # DefaultInfo.other_outputs. When False, it can still be materialized+ # explicitly via the `[debuginfo]` sub-target.+ "materialize_external_debug_info": provider_field(bool, default = True),+ "minimum_os_version": provider_field([str, None], default = None),+ "objc_compiler_info": provider_field([ObjcCompilerInfo, None], default = None),+ "objcxx_compiler_info": provider_field([ObjcxxCompilerInfo, None], default = None),+ "object_format": provider_field(typing.Any, default = None),+ "pass_plugin": provider_field([Artifact, None], default = None),+ "pic_behavior": provider_field(typing.Any, default = None),+ "raw_headers_as_headers_mode": provider_field(typing.Any, default = None),+ "rc_compiler_info": provider_field(typing.Any, default = None),+ "remap_cwd": provider_field(bool, default = False),+ "runtime_dependency_handling": provider_field(RuntimeDependencyHandling),+ "split_debug_mode": provider_field(typing.Any, default = None),+ "strip_flags_info": provider_field(typing.Any, default = None),+ "supported_compile_flavors": provider_field(typing.Any, default = []),+ "target_stats_tools": provider_field([TargetStatsToolsInfo, None], default = None),+ "use_dep_files": provider_field(typing.Any, default = None),+ "use_distributed_thinlto": provider_field(typing.Any, default = None),+ },+)++# Stores "platform"/flavor name used to resolve *platform_* arguments+CxxPlatformInfo = provider(+ # @unsorted-dict-items+ fields = {+ "name": provider_field(typing.Any, default = None),+ # List of aliases used to resolve platform_deps+ "deps_aliases": provider_field(typing.Any, default = None),+ },+)++def _validate_linker_info(info: LinkerInfo):+ if info.requires_archives and info.requires_objects:+ fail("only one of `requires_archives` and `requires_objects` can be enabled")++def is_bitcode_format(format: CxxObjectFormat) -> bool:+ return format in [CxxObjectFormat("bitcode"), CxxObjectFormat("embedded-bitcode")]++def cxx_toolchain_infos(+ platform_name,+ c_compiler_info,+ cxx_compiler_info,+ linker_info,+ binary_utilities_info,+ header_mode,+ internal_tools: CxxInternalTools,+ headers_as_raw_headers_mode = None,+ raw_headers_as_headers_mode = None,+ asm_compiler_info = None,+ as_compiler_info = None,+ hip_compiler_info = None,+ hip_debug_extract = None,+ hip_device_debug_extract = False,+ hip_gpu_archs = [],+ cuda_compiler_info = None,+ cvtres_compiler_info = None,+ rc_compiler_info = None,+ object_format = CxxObjectFormat("native"),+ use_distributed_thinlto = False,+ use_dep_files = False,+ clang_remarks = None,+ clang_llvm_statistics = False,+ gcno_files = None,+ clang_trace = False,+ cpp_dep_tracking_mode = DepTrackingMode("none"),+ cuda_dep_tracking_mode = DepTrackingMode("none"),+ strip_flags_info = None,+ split_debug_mode = SplitDebugMode("none"),+ materialize_external_debug_info = True,+ bolt_enabled = False,+ cell_to_path_prefix_map = {},+ llvm_cgdata = None,+ llvm_link = None,+ platform_deps_aliases = [],+ pic_behavior = PicBehavior("supported"),+ dumpbin_toolchain_path = None,+ minimum_os_version = None,+ libclang = None,+ lipo = None,+ remap_cwd = False,+ compiler_flavor_flags = {},+ supported_compile_flavors = ["pic"],+ objc_compiler_info = None,+ objcxx_compiler_info = None,+ cxx_error_handler = None,+ pass_plugin = None,+ default_deps = [],+ runtime_dependency_handling = RuntimeDependencyHandling("no_symlink"),+ target_stats_tools = None,+):+ """+ Creates the collection of cxx-toolchain Infos for a cxx toolchain.++ c and c++ compiler infos are required, as is a linker info. The rest are+ optional, and it will be an error if any cxx_library or other rules have srcs+ of those other types.+ """++ # TODO(T110378099): verify types of the inner info objects.+ _validate_linker_info(linker_info)++ # Maintain backwards compatibility with ObjC compilation using the C compiler.+ if objc_compiler_info == None:+ objc_compiler_info = ObjcCompilerInfo(**{k: getattr(c_compiler_info, k, None) for k in _compiler_fields})+ if objcxx_compiler_info == None:+ objcxx_compiler_info = ObjcxxCompilerInfo(**{k: getattr(cxx_compiler_info, k, None) for k in _compiler_fields})++ toolchain_info = CxxToolchainInfo(+ as_compiler_info = as_compiler_info,+ asm_compiler_info = asm_compiler_info,+ binary_utilities_info = binary_utilities_info,+ bolt_enabled = bolt_enabled,+ cell_to_path_prefix_map = cell_to_path_prefix_map,+ c_compiler_info = c_compiler_info,+ clang_remarks = clang_remarks,+ clang_llvm_statistics = clang_llvm_statistics,+ clang_trace = clang_trace,+ cpp_dep_tracking_mode = cpp_dep_tracking_mode,+ cuda_compiler_info = cuda_compiler_info,+ cuda_dep_tracking_mode = cuda_dep_tracking_mode,+ cvtres_compiler_info = cvtres_compiler_info,+ cxx_compiler_info = cxx_compiler_info,+ dumpbin_toolchain_path = dumpbin_toolchain_path,+ gcno_files = gcno_files,+ header_mode = header_mode,+ headers_as_raw_headers_mode = headers_as_raw_headers_mode,+ hip_compiler_info = hip_compiler_info,+ hip_debug_extract = hip_debug_extract,+ hip_device_debug_extract = hip_device_debug_extract,+ hip_gpu_archs = hip_gpu_archs,+ internal_tools = internal_tools,+ libclang = libclang,+ linker_info = linker_info,+ lipo = lipo,+ llvm_cgdata = llvm_cgdata,+ llvm_link = llvm_link,+ materialize_external_debug_info = materialize_external_debug_info,+ objc_compiler_info = objc_compiler_info,+ objcxx_compiler_info = objcxx_compiler_info,+ object_format = object_format,+ pass_plugin = pass_plugin,+ compiler_flavor_flags = compiler_flavor_flags,+ pic_behavior = pic_behavior,+ raw_headers_as_headers_mode = raw_headers_as_headers_mode,+ rc_compiler_info = rc_compiler_info,+ remap_cwd = remap_cwd,+ runtime_dependency_handling = runtime_dependency_handling,+ split_debug_mode = split_debug_mode,+ strip_flags_info = strip_flags_info,+ minimum_os_version = minimum_os_version,+ use_dep_files = use_dep_files,+ use_distributed_thinlto = use_distributed_thinlto,+ cxx_error_handler = cxx_error_handler,+ supported_compile_flavors = supported_compile_flavors,+ default_deps = default_deps,+ target_stats_tools = target_stats_tools,+ )++ ldflags_shared_extra = None+ if linker_info.type == LinkerType("darwin") and is_valid_apple_platform_name(platform_name):+ # These flags are used in `cxx_genrule()`, using the toolchain's target sdk version is+ # the best we can do, as there's no target sdk on the rule itself.+ #+ # Without target triple, the linker will use the host OS as the target+ # which is almost always incorrect.+ apple_target_triple = apple_format_target_triple(platform_name, minimum_os_version or "")+ ldflags_shared_extra = apple_extra_darwin_linker_flags(apple_target_triple)++ # Provide placeholder mappings, used primarily by cxx_genrule.+ # We don't support these buck1 placeholders since we can't take an argument.+ # $(ldflags-pic-filter <pattern>)+ # $(ldflags-shared-filter <pattern>)+ # $(ldflags-static-filter <pattern>)+ unkeyed_variables = {+ "ar": linker_info.archiver,+ "cc": c_compiler_info.compiler,+ "cflags": _shell_quote(c_compiler_info.compiler_flags),+ "cppflags": _shell_quote(c_compiler_info.preprocessor_flags),+ "cxx": cxx_compiler_info.compiler,+ "cxxflags": _shell_quote(cxx_compiler_info.compiler_flags),+ "cxxppflags": _shell_quote(cxx_compiler_info.preprocessor_flags),+ "ld": linker_info.linker,+ # NOTE(agallagher): The arg-less variants of the ldflags macro are+ # identical, and are just separate to match v1's behavior (ideally,+ # we just have a single `ldflags` macro for this case).+ "ldflags-shared": _shell_quote(linker_info.linker_flags or [], ldflags_shared_extra),+ "ldflags-static": _shell_quote(linker_info.linker_flags or []),+ "ldflags-static-pic": _shell_quote(linker_info.linker_flags or []),+ "objcopy": binary_utilities_info.objcopy,+ }++ if as_compiler_info != None:+ unkeyed_variables["as"] = as_compiler_info.compiler+ unkeyed_variables["asflags"] = _shell_quote(as_compiler_info.compiler_flags)+ unkeyed_variables["asppflags"] = _shell_quote(as_compiler_info.preprocessor_flags)++ if cuda_compiler_info != None:+ unkeyed_variables["cuda"] = cuda_compiler_info.compiler+ unkeyed_variables["cudaflags"] = _shell_quote(cuda_compiler_info.compiler_flags)+ placeholders_info = TemplatePlaceholderInfo(unkeyed_variables = unkeyed_variables)+ return [toolchain_info, placeholders_info, CxxPlatformInfo(name = platform_name, deps_aliases = platform_deps_aliases)]++def _shell_quote(xs, extra = None):+ return cmd_args(xs, extra or [], quote = "shell")++# export these things under a single "cxx" struct+cxx = struct(+ LinkerType = LinkerType,+ LinkerInfo = LinkerInfo,+ BinaryUtilitiesInfo = BinaryUtilitiesInfo,+ HipCompilerInfo = HipCompilerInfo,+ CudaCompilerInfo = CudaCompilerInfo,+ CCompilerInfo = CCompilerInfo,+ CxxCompilerInfo = CxxCompilerInfo,+ AsmCompilerInfo = AsmCompilerInfo,+ AsCompilerInfo = AsCompilerInfo,+ CxxToolchainInfo = CxxToolchainInfo,+ CxxPlatformInfo = CxxPlatformInfo,+ StripFlagsInfo = StripFlagsInfo,+ DistLtoToolsInfo = DistLtoToolsInfo,+ cxx_toolchain_infos = cxx_toolchain_infos,+)
@@ -0,0 +1,37 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "ArtifactTSet", # @unused Used as a type+ "make_artifact_tset",+)++CxxTransitiveDiagnosticsInfo = provider(+ fields = {+ "transitive_diagnostics": provider_field(ArtifactTSet),+ },+)++def cxx_transitive_diagnostics_combine(ctx: AnalysisContext, diagnostics: list[Artifact], deps: list[Dependency]) -> CxxTransitiveDiagnosticsInfo:+ children = []+ for dep in deps:+ dep_diagnostics_info = dep.get(CxxTransitiveDiagnosticsInfo)+ if dep_diagnostics_info:+ children.append(dep_diagnostics_info.transitive_diagnostics)++ transitive_diagnostics = make_artifact_tset(+ actions = ctx.actions,+ label = ctx.label,+ artifacts = diagnostics,+ children = children,+ )++ return CxxTransitiveDiagnosticsInfo(+ transitive_diagnostics = transitive_diagnostics,+ )
@@ -0,0 +1,315 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//:artifact_tset.bzl", "ArtifactInfoTag", "ArtifactTSet")+load(+ "@prelude//cxx:cuda.bzl",+ "CudaCompileStyle",+)+load(+ "@prelude//cxx:cxx_toolchain_types.bzl",+ "RuntimeDependencyHandling", # @unused Used as a type+)+load(+ "@prelude//cxx:link_groups_types.bzl",+ "LinkGroupInfo", # @unused Used as a type+)+load(+ "@prelude//linking:link_info.bzl",+ "LinkArgs",+ "SwiftmoduleLinkable",+)+load(+ "@prelude//linking:linkables.bzl",+ "LinkableProviders",+)+load(+ "@prelude//linking:shared_libraries.bzl",+ "SharedLibrary", # @unused Used as a type+)+load(":argsfiles.bzl", "CompileArgsfiles")+load(+ ":compile_types.bzl",+ "IndexStoreFactory",+ "UseHeaderUnitsMode",+)+load(+ ":cxx_sources.bzl",+ "CxxSrcWithFlags", # @unused Used as a type+)+load(+ ":headers.bzl",+ "CxxHeadersLayout",+)+load(+ ":link_groups.bzl",+ "LinkGroupLibSpec", # @unused Used as a type+)+load(+ ":linker.bzl",+ "SharedLibraryFlagOverrides",+)+load(+ ":preprocessor.bzl",+ "CPreprocessor",+ "CPreprocessorInfo",+)+load(+ ":xcode.bzl",+ "cxx_populate_xcode_attributes",+)++LinkPreference = enum("default", "full", "incremental")++CxxLibraryInfo = provider(+ fields = dict(+ target = provider_field(Label),+ labels = provider_field(list[str]),+ ),+)++# Parameters to control which sub targets to define when processing Cxx rules.+# By default, generates all subtargets.+CxxRuleSubTargetParams = record(+ argsfiles = field(bool, True),+ compilation_database = field(bool, True),+ clang_remarks = field(bool, True),+ clang_llvm_statistics = field(bool, True),+ clang_traces = field(bool, True),+ headers = field(bool, True),+ link_group_map = field(bool, True),+ link_style_outputs = field(bool, True),+ xcode_data = field(bool, False),+ objects = field(bool, True),+ bitcode_bundle = field(bool, True),+ header_unit = field(bool, True),+)++def xcode_data_enabled() -> bool:+ # Project generators must manually enable xcode data because it measurably increases memory usage.+ return read_root_config("cxx", "enable_xcode_data", "false").lower() == "true"++# Parameters to control which providers to define when processing Cxx rules.+# By default, generates all providers.+CxxRuleProviderParams = record(+ compilation_database = field(bool, True),+ default = field(bool, True),+ java_packaging_info = field(bool, True),+ android_packageable_info = field(bool, True),+ java_global_code_info = field(bool, True),+ linkable_graph = field(bool, True),+ link_style_outputs = field(bool, True),+ merged_native_link_info = field(bool, True),+ omnibus_root = field(bool, True),+ preprocessors = field(bool, True),+ # Whether or not to generate a resource groups provider for raw cxx resources.+ cxx_resources_as_apple_resources = field(bool, True),+ resources = field(bool, True),+ shared_libraries = field(bool, True),+ template_placeholders = field(bool, True),+ preprocessor_for_tests = field(bool, True),+ third_party_build = field(bool, False),+ transitive_diagnostics = field(bool, False),+)++# Parameters to handle non-Clang sources, e.g Swift on Apple's platforms.+CxxRuleAdditionalParams = record(+ srcs = field(list[CxxSrcWithFlags], []),+ # Additional argsfiles to include for this rule.+ argsfiles = field(CompileArgsfiles, CompileArgsfiles()),+ # External debug info to be used when generated static output+ static_external_debug_info = field(list[ArtifactTSet], []),+ # External debug info to be used when generating shared objects+ shared_external_debug_info = field(list[ArtifactTSet], []),+ subtargets = field(dict, {}), # [str: ["provider"]]+ # Might be used to expose additional providers to cxx layer (e.g to support #headers subtarget for Swift)+ additional_providers_factory = field([typing.Callable, None], None), # ([CPreprocessorInfo, None]) -> ["provider"]:+ # The list of tags that should be applied to generated ArtifactTSet of debug information.+ external_debug_info_tags = field(list[ArtifactInfoTag], []),+)++# Parameters that allows to configure/extend generic implementation of C++ rules.+# Apple-specific rules (such as `apple_binary` and `apple_library`) and regular C+++# rules (such as `cxx_binary` and `cxx_library`) have too much in common, though+# some aspects of behavior (like layout of headers affecting inclusion of those+# or additional linking flags to support usage of platform frameworks) of are+# different and need to be specified. The following record holds the data which+# is needed to specialize user-facing rule from generic implementation.+CxxRuleConstructorParams = record(+ # Required+ # Name of the top level rule utilizing the cxx rule.+ rule_type = str,+ # Header layout to use importing headers.+ headers_layout = CxxHeadersLayout,+ # Optional+ # Whether to build an empty shared library. This is utilized for rust_python_extensions+ # so that they can link against the rust shared object.+ build_empty_so = field(bool, False),+ # If the rule is a test.+ is_test = field(bool, False),+ # Additional information used to preprocess every unit of translation in the rule.+ extra_preprocessors = field(list[CPreprocessor], []),+ extra_preprocessors_info = field(list[CPreprocessorInfo], []),+ # Additional preprocessor info to export to other rules.+ extra_exported_preprocessors = field(list[CPreprocessor], []),+ # Additional information used to link every object produced by the rule,+ # flags are _both_ exported and used to link the target itself.+ extra_exported_link_flags = field(list[typing.Any], []),+ # Additional hidden inputs for link or archive actions.+ extra_hidden = field(list[Artifact], []),+ extra_dwp_flags = field(list[typing.Any], []),+ # Additional flags used _only_ when linking the target itself.+ # These flags are _not_ propagated up the dep tree.+ extra_link_flags = field(list[typing.Any], []),+ extra_binary_link_flags = field(list[typing.Any], []),+ # Inputs that invalidate generated build info without becoming inputs to the executable link.+ generated_build_info_invalidation_inputs = field(list[typing.Any], []),+ # Additional artifacts to be linked together with the cxx compilation output.+ extra_link_input = field(list[Artifact], []),+ # If True the extra_link_input should be considered as external debug info.+ extra_link_input_has_external_debug_info = field(bool, False),+ # Additional args to be used to link the target.+ extra_link_args = field(list[LinkArgs], []),+ # The swift module linkable that should be included for linking,+ # used for link_groups and regular linking.+ swiftmodule_linkable = field([SwiftmoduleLinkable, None], None),+ # The source files to compile as part of this rule. This list can be generated+ # from ctx.attrs with the `get_srcs_with_flags` function.+ srcs = field(list[CxxSrcWithFlags]),+ additional = field(CxxRuleAdditionalParams, CxxRuleAdditionalParams()),+ # A function which enables the caller to inject subtargets into the link_style provider+ # as well as create custom providers based on the link styles.+ output_style_sub_targets_and_providers_factory = field(typing.Callable, lambda _link_style, _context, _output: ({}, [])),+ # Linker flags that tell the linker to create shared libraries, overriding the default shared library flags.+ # e.g. when building Apple tests, we want to link with `-bundle` instead of `-shared` to allow+ # linking against the bundle loader.+ shared_library_flags = field([SharedLibraryFlagOverrides, None], None),+ # Optional argument to override the default name of the shared object being produced.+ soname = field([str, None], None),+ # Optional argument to override the default name of the executable being produced.+ executable_name = field([str, None], None),+ # Optional argument to set the deffile for the windows linker on a dll+ deffile = field([Artifact, None], None),+ # If passed to cxx_executable, this field will be used to determine+ # a shared subtarget's default output should be stripped.+ strip_executable = field(bool, False),+ strip_args_factory = field(typing.Callable, lambda _: cmd_args()),+ # Whether to embed the library name as the SONAME.+ use_soname = field(bool, True),+ # Use link group's linking logic regardless whether a link group map's present.+ force_link_group_linking = field(bool, False),+ # Function to use for setting Xcode attributes for the Xcode data sub target.+ cxx_populate_xcode_attributes_func = field(typing.Callable, cxx_populate_xcode_attributes),+ # Define which sub targets to generate.+ generate_sub_targets = field(CxxRuleSubTargetParams, CxxRuleSubTargetParams()),+ # Define which providers to generate.+ generate_providers = field(CxxRuleProviderParams, CxxRuleProviderParams()),+ force_full_hybrid_if_capable = field(bool, False),+ # Whether shared libs for executables should generate a shared lib link tree.+ exe_shared_libs_link_tree = field(bool, True),+ extra_link_deps = field(list[LinkableProviders], []),+ # Additional link roots (e.g. dlopen-able libs in a native python link),+ # other than the main executable, which can influence the C++ executable+ # result (e.g. added to link group linking or needs to be searched for+ # shared libs to include in the symlink tree).+ extra_link_roots = field(list[LinkableProviders], []),+ # Additional shared libs to "package".+ extra_shared_libs = field(list[SharedLibrary], []),+ auto_link_group_specs = field([list[LinkGroupLibSpec], None], None),+ link_group_info = field([LinkGroupInfo, None], None),+ # Whether to use pre-stripped objects when linking.+ prefer_stripped_objects = field(bool, False),+ # The category suffix to use for executables actions (e.g. linking).+ exe_category_suffix = field(str, "executable"),+ # Whether link groups liking should make `preferred_linkage = "static"` libs+ # "follow" their dependents across link group boundaries.+ link_groups_force_static_follows_dependents = field(bool, True),+ # A factory function to produce extra artifacts and output providers for a rule+ # with signature: f(ctx, ExtraLinkerOutputsCategory) -> ExtraLinkerOutputs+ extra_linker_outputs_factory = field(typing.Callable | None, None),+ # A factory function to produce linker flags for the extra linker outputs+ # returned from the extra_linker_outputs_factory. It should have the signature+ # f(ctx, ExtraLinkerOutputCategory, dict[str, Artifact]) -> list[ArgLike]+ extra_linker_outputs_flags_factory = field(typing.Callable | None, None),+ # A function to consume extra outputs produced by distributed thin-lto opt actions+ # and merge them together, as if they were produced by a local thin-lto link.+ # The signature should be:+ # f(ctx, dict[str, Artifact], list[dict[str, Artifact]])+ # The second parameter should be the artifacts field of a call to+ # extra_linker_outputs_factory(ctx, ExtraLinkerOutputsCategory("produced-during-distributed-thin-lto-opt")),+ # and the last parameter a list of matching dictionaries representing all the opt outputs+ # to be merged to bind the final outputs.+ extra_distributed_thin_lto_opt_outputs_merger = field(typing.Callable | None, None),+ # Whether to allow cache uploads for locally-executed actions (except for linking, see "exe_allow_cache_upload").+ allow_cache_upload = field(bool, False),+ # Whether to allow cache uploads for locally-linked executables.+ exe_allow_cache_upload = field(bool, False),+ # Extra shared library interfaces to propagate, eg from mixed Swift libraries.+ extra_shared_library_interfaces = field([list[Artifact], None], None),+ # Compiler flags+ compiler_flags = field(list[typing.Any], []),+ cxx_flags = field(list[Dependency], []),+ lang_compiler_flags = field(dict[typing.Any, typing.Any], {}),+ # Preprocessor flags+ preprocessor_flags = field(list[typing.Any], []),+ lang_preprocessor_flags = field(dict[typing.Any, typing.Any], {}),+ # modulename-Swift.h header for building objc targets that rely on this swift dep+ swift_objc_header = field([Artifact, None], None),+ error_handler = field([typing.Callable, None], None),+ index_store_factory = field(IndexStoreFactory | None, None),+ # Swift index stores to propagate+ index_stores = field(list[Artifact] | None, None),+ # Modularization dependency graph artifact (from Swift compilation)+ modularization_dependency_graph = field(Artifact | None, None),+ # Whether to add header units from dependencies to the command line.+ use_header_units = field(UseHeaderUnitsMode, UseHeaderUnitsMode("none")),+ # Whether to export a header unit to all dependents.+ export_header_unit = field([str, None], None),+ # Filter what headers to include in header units.+ export_header_unit_filter = field(list[str], []),+ # Additional behavior for how to handle runtime dependencies+ runtime_dependency_handling = field([RuntimeDependencyHandling, None], None),+ # Should this library only be used for build time linkage+ stub = field(bool, False),+ # The calling context is allowed to use `AnalysisActions#anon_target` API.+ # This is not allowed in the context of the `dynamic_outputs` callback.+ anon_targets_allowed = field(bool, True),+ # Any extra diagnostics to include in transitive diagnostics provider+ extra_transitive_diagnostics = field(list[Artifact], []),+ # Any extra diagnostics to include in [check] subtarget, maps from+ # identifier (usually filename) to diagnostic output.+ extra_diagnostics = field(dict[str, Artifact] | None, None),+ # Whether to use fbcc Rust wrapper+ use_fbcc_rust_wrapper = field(bool, False),+ # Precompiled header+ precompiled_header = field(Dependency | None, None),+ # Prefix header+ prefix_header = field(Artifact | None, None),+ # Store "_cxx_toolchain" as "Dependency" for use in "anon_target"+ _cxx_toolchain = field(Dependency | None, None),+ # Use content-based filepaths for artifacts+ use_content_based_paths = field(bool, False),+ # Coverage instrumentation compiler flags+ coverage_instrumentation_compiler_flags = field(list[str], []),+ # Optional profile list artifact for selective coverage via -fprofile-list+ coverage_profile_list = field(Artifact | None, None),+ # Separate debug info+ separate_debug_info = field(bool, False),+ # Cuda compile stype+ cuda_compile_style = field(CudaCompileStyle | None, None),+ link_preference = field(LinkPreference, LinkPreference("default")),+ supports_stripping = field(bool, True),+ # Whether to set expect_eligible_for_dedupe on compile actions.+ expect_eligible_for_dedupe = field(bool, False),+ target_stats_cycle_mode = field(str, "none"),+ target_stats_extra_srcs = field(dict[str, Artifact], {}),+ target_stats_swift_dot = field(Artifact | None, None),+ # The module the cycle tools resolve imports against. Not how the target is+ # reported -- that stays the target's label.+ target_stats_module_name = field(str | None, None),+)
@@ -0,0 +1,41 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++def cxx_attrs_use_fbcc_rust_wrapper(attrs: struct) -> bool:+ return attrs.use_fbcc_rust_wrapper if hasattr(attrs, "use_fbcc_rust_wrapper") else False++def cxx_attrs_get_allow_cache_upload(attrs: struct, default: [None, bool] = None) -> bool:+ default_value = default if default != None else False+ if not hasattr(attrs, "allow_cache_upload"):+ return default_value+ value = attrs.allow_cache_upload+ return value if value != None else default_value++def cxx_toolchain_allow_cache_upload_args():+ doc = """+ Whether to allow uploading of object files to cache when the compile+ action is executed locally and the configuration allows uploads (i.e.,+ there is a cache configured and the client has permission to write to it).+ """+ return {+ "c_compiler_allow_cache_upload": attrs.option(+ attrs.bool(),+ default = None,+ doc = doc,+ ),+ "cuda_compiler_allow_cache_upload": attrs.option(+ attrs.bool(),+ default = None,+ doc = doc,+ ),+ "cxx_compiler_allow_cache_upload": attrs.option(+ attrs.bool(),+ default = None,+ doc = doc,+ ),+ }
@@ -0,0 +1,24 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# Model the various "split" debug scenarios (e.g. `-gsplit-dwarf`).+SplitDebugMode = enum(+ # Debug info, if present, is inline in the object file, and will be linked+ # into executables and shared libraries (e.g. traditional behavior when+ # using `-g`).+ "none",+ # Debug info. if present is included in the object file, but will *not* be+ # linked into executables and shared libraries. This style usually requires+ # an additional step, separate from the link, to combine and package debug+ # info (e.g. `dSYM`, `dwp`).+ "single",+ # Debug info, is present, is separated to .dwo file. This style requires+ # additional step, separate from the link, to combine and package debug+ # info (e.g. `dSYM`, `dwp`).+ "split",+)
@@ -0,0 +1,47 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//utils:expect.bzl", "expect")+load(":cxx_context.bzl", "get_cxx_toolchain_info")++def check_sub_target(+ ctx: AnalysisContext,+ diagnostics: dict[str, Artifact],+ error_handler: [typing.Callable, None] = None,+ output_name: str = "diagnostics.txt",+ extra_sub_targets: dict[str, Artifact] = {},+) -> (list[Provider], Artifact):+ expect(len(diagnostics) > 0)++ if len(diagnostics) == 1:+ all_diagnostics = diagnostics.values()[0]+ else:+ toolchain = get_cxx_toolchain_info(ctx)+ concatenate_diagnostics_tool = toolchain.internal_tools.concatenate_diagnostics+ all_diagnostics = ctx.actions.declare_output(output_name, has_content_based_path = False)+ ctx.actions.run(+ [+ concatenate_diagnostics_tool,+ cmd_args(all_diagnostics.as_output(), format = "--out={}"),+ diagnostics.values(),+ ],+ category = "diagnostics",+ identifier = output_name,+ error_handler = error_handler,+ )++ all_sub_targets = {short_path: [DefaultInfo(default_output = diag)] for short_path, diag in diagnostics.items()}+ for short_path, diag in extra_sub_targets.items():+ all_sub_targets[short_path] = [DefaultInfo(default_output = diag)]++ return [+ DefaultInfo(+ default_output = all_diagnostics,+ sub_targets = all_sub_targets,+ )+ ], all_diagnostics
@@ -0,0 +1,323 @@+# Distributed ThinLTO in Buck2++Sean Gillespie, April 2022++This document is a technical overview into Buck2's implementation of a+distributed ThinLTO. Like all rules in Buck2, this implementation is written+entirely in Starlark, contained in `dist_lto.bzl` (in this same directory).++## Motivation++First, I highly recommend watching+[Teresa Johnson's CppCon2017 talk about ThinLTO](https://www.youtube.com/watch?v=p9nH2vZ2mNo),+which covers the topics in this section in much greater detail than I can.++C and C++ have long enjoyed significant optimizations at the hands of compilers.+However, they have also long suffered a fundamental limitation; a C or C+++compiler can only optimize code that it sees in a single translation unit. For a+language like C or C++, this means in practice that only code that is included+via the preprocessor or specified in the translation unit can be optimized as a+single unit. C and C++ compilers are unable to inline functions that are defined+in different translation units. However, a crucial advantage of this compilation+model is that all C and C++ compiler invocations are _completely+parallelizable_; despite sacrificing some code quality, C and C++ compilation+turns into a massively parallel problem with a serial link step at the very end.++```+flowchart LR;+ header.h;++ header.h --> a.cpp;+ header.h -->|#include| b.cpp;+ header.h --> c.cpp;++ a.cpp --> a.o;+ b.cpp -->|clang++ -O2| b.o;+ c.cpp --> c.o;++ a.o --> main;+ b.o -->|ld| main;+ c.o --> main;+```++([Rendered](https://fburl.com/mermaid/rzup8o32). Compilation and optimization of+a, b, and c can proceed in parallel.)++In cases where absolute performance is required, though, the inability to+perform cross-translation-unit (or "cross-module", in LLVM parlance)+optimizations becomes more of a problem. To solve this, a new compilation+paradigm was designed, dubbed "Link-Time Optimization" (LTO). In this scheme, a+compiler will not produce machine code when processing a translation unit;+rather, it will output the compiler's intermediate representation (e.g. LLVM+bitcode). Later on, when it is time for the linker to run, it will load all of+the compiler IR into one giant module, run optimization passes on the+mega-module, and produce a final binary from that.++This works quite well, if all that you're looking for is run-time performance. A+major drawback of the LTO approach is that all of the parallelism gained from+optimizing translation units individually is now completely lost; instead, the+linker (using a plugin) will do a single-threaded pass of _all code_ produced by+compilation steps. This is extremely slow, memory-intensive, and unable to be+run incrementally. There are targets at Meta that simply can't be LTO-compiled+because of their size.++```+flowchart LR;+ header.h;++ header.h --> a.cpp;+ header.h -->|#include| b.cpp;+ header.h --> c.cpp;++ a.cpp --> a.bc;+ b.cpp -->|clang++ -O2 -flto -x ir| b.bc;+ c.cpp --> c.bc;++ a.bc --> a_b_c.bc;+ b.bc -->|linker driver| a_b_c.bc;+ c.bc --> a_b_c.bc;++ a_b_c.bc -->|opt| a_b_c_optimized.bc++ a_b_c_optimized.bc -->|codegen| main.o++ main.o --> |ld| main+```++([Rendered](https://fburl.com/mermaid/kid35io9). `a.bc`, `b.bc`, and `c.bc` are+LLVM bitcode; they are all merged together into a single module,+`a_b_c_optimized.bc`, which is then optimized and codegen'd into a final+binary.)++The idea of ThinLTO comes from a desire to maintain the ability to optimize+modules in parallel while still allowing for profitable cross-module+optimizations. The idea is this:++1. Just like regular LTO, the compiler emits bitcode instead of machine code.+ However, it also contains some light metadata such as a call graph of symbols+ within the module.+2. The monolithic LTO link is split into three steps: `index`, `opt`, and+ `link`.++```+flowchart LR;+ header.h;++ header.h --> a.cpp;+ header.h -->|#include| b.cpp;+ header.h --> c.cpp;++ a.cpp --> a.bc;+ b.cpp -->|clang++ -O2 -flto -x ir| b.bc;+ c.cpp --> c.bc;++ a.bc --> index;+ b.bc --> index;+ c.bc --> index;++ index --> a.thinlto.bc;+ index --> b.thinlto.bc;+ index --> c.thinlto.bc;++ a.thinlto.bc --> a.o;+ b.thinlto.bc --> b.o;+ b.bc --> a.o;+ b.bc --> c.o;+ c.thinlto.bc --> c.o;++ a.o --> main;+ b.o -->|ld| main;+ c.o --> main;+```++([Rendered](https://fburl.com/mermaid/56oc99t5))++The `index` step looks like a link step. However, it does not produce a final+binary; instead, it looks at every compiler IR input file that it receives and+heuristically determines which other IR modules it should be optimized with in+order to achieve profitable optimizations. These modules might include functions+that the index step thinks probably will get inlined, or globals that are read+in the target IR input file. The output of the index step is a series of files+on disk that indicate which sibling object files should be present when+optimizing a particular object file, for each object file in the linker+command-line.++The `opt` step runs in parallel for every object file. Each object file will be+optimized using the compiler's optimizer (e.g. `opt`, for LLVM). The optimizer+will combine the objects that were referenced as part of the index step as+potentially profitable to include and optimize them all together.++The `link` step takes the outputs of `opt` and links them together, like a+normal linker.++In practice, ThinLTO manages to recapture the inherent parallelism of C/C+++compilation by pushing the majority of work to the parallel `opt` phase of+execution. When LLVM performs ThinLTO by default, it will launch a thread pool+and process independent modules in parallel. ThinLTO does not produce as+performant a binary as a monolithic LTO; however, in practice, ThinLTO binaries+[paired with AutoFDO](https://fburl.com/wiki/q480euco) perform comparably to+monolithic LTO. Furthermore, ThinLTO's greater efficiency allows for more+expensive optimization passes to be run, which can further improve code quality+near that of a monolithic LTO.++This is all great, and ThinLTO has been in use at Meta for some time. However,+Buck2 has the ability to take a step further than Buck1 could ever have - Buck2+can distribute parallel `opt` actions across many machines via Remote Execution+to achieve drastic speedups in ThinLTO wall clock time, memory usage, and+incrementality.++## Buck2's Implementation++Buck2's role in a distributed ThinLTO compilation is to construct a graph of+actions that directly mirrors the graph that the `index` step outputs. The graph+that the `index` step outputs is entirely dynamic and, as such, the build system+is only aware of what the graph could be after the `index` step is complete.+Unlike Buck1 (or even Blaze/Bazel), Buck2 has explicit support for this paradigm+[("dynamic dependencies")](https://fburl.com/gdoc/zklwhkll). Therefore, for+Buck2, the basic strategy looks like:++1. Invoke `clang` to act as `index`. `index` will output a file for every object+ file that indicates what other modules need to be present when running `opt`+ on the object file (an "imports file").+2. Read imports files and construct a graph of dynamic `opt` actions whose+ dependencies mirror the contents of the imports files.+3. Collect the outputs from the `opt` actions and invoke the linker to produce a+ final binary.++Action `2` is inherently dynamic, since it must read the contents of files+produced as part of action `1`. Furthermore, Buck2's support of `1` is+complicated by the fact that certain Buck2 rules can produce an archive of+object files as an output (namely, the Rust compiler). As a result, Buck2's+implementation of Distributed ThinLTO is highly dynamic.++Buck2's implementation contains four phases of actions:++1. `thin_lto_prepare`, which specifically handles archives containing LLVM IR+ and prepares them to be inputs to `thin_lto_index`,+2. `thin_lto_index`, which invokes LLVM's ThinLTO indexer to produce a imports+ list for every object file to be optimized,+3. `thin_lto_opt`, which optimizes each object file in parallel with its imports+ present,+4. `thin_lto_link`, which links together the optimized code into a final binary.++### thin_lto_prepare++It is a reality of Buck2 today that some rules don't produce a statically-known+list of object files. The list of object files is known _a priori_ during C/C+++compilation, since they have a one-to-one correspondence to source files;+however, the Rust compiler emits an archive of object files; without inspecting+the archive, Buck2 has no way of knowing what the contents of the archive are,+or even if they contain bitcode at all.++Future steps (particularly `thin_lto_index`) are defined to only operate on a+list of object files - a limitation+[inherited from LLVM](https://lists.llvm.org/pipermail/llvm-dev/2019-June/133145.html).+Therefore, it is the job of `thin_lto_prepare` to turn an archive into a list of+objects - namely, by extracting the archive into a directory.++Buck2 dispatches a `thin_lto_prepare` action for every archive. Each prepare+action has two outputs:++1. An **output directory** (called `objects` in the code), a directory that+ contains the unextracted contents of the archive.+2. A **archive manifest**, a JSON document containing a list of object files+ that are contained in the output directory.++The core logic of this action is implemented in the Python script+`dist_lto_prepare.py`, contained in the `tools` directory. In addition to+unpacking each archive, Buck2 keeps track of the list of archives as a Starlark+array that will be referenced by index in later steps.++### thin_lto_index++With all archives prepared, the next step is to invoke LLVM's ThinLTO indexer.+For the purposes of Buck2, the indexer looks like a linker; because of this,+Buck2 must construct a reasonable link line. Buck2 does this by iterating over+the list of linkables that it has been given and constructing a link line from+them. Uniquely for distributed ThinLTO, Buck2 must wrap all objects that were+derived from `thin_lto_prepare` (i.e. were extracted from archives) with+`-Wl,--start-lib` and `-Wl,--end-lib` to ensure that they are still treated as+if they were archives by the indexer.++Invoking the indexer is relatively straightforward in that Buck2 invokes it like+it would any other linker. However, once the indexer returns, Buck2 must+post-process its output into a format that Buck2's Starlark can understand and+translate into a graph of dynamic `opt` actions. The first thing that Buck2 is+write a "meta file" to disk, which communicates inputs and outputs of+`thin_lto_index` to a Python script, `dist_lto_planner.py`. The meta file+contains a list of 7-tuples, whose members are:++1. The path to the source bitcode file. This is used as an index into a+ dictionary that records much of the metadata coming from these lines.+2. The path to an output file. `dist_lto_planner.py` is expected to place a+ ThinLTO index file at this location (suffixed `.thinlto.bc`).+3. The path to an output plan. This script is expected to place a link plan here+ (a JSON document indicating which other object files this) object file+ depends on, among other things.+4. If this object file came from an archive, the index of the archive in the+ Starlark archives array.+5. If this object file came from an archive, the name of the archive.+6. If this object file came from an archive, the path to an output plan. This+ script is expected to produce an archive link plan here (a JSON) document+ similar to the object link plan, except containing link information for every+ file in the archive from which this object came.+7. If this object file came from an archive, the indexes directory of that+ archive. This script is expected to place all ThinLTO indexes derived from+ object files originating from this archive in that directory.++There are two indices that are derived from this meta file: the object index+(`mapping["index"]`) and the archive index (`mapping["archive_index"]`). These+indices are indices into Starlark arrays for all objects and archive linkables,+respectively. `dist_lto_planner.py` script does not inspect them; rather, it is+expected to communicate these indices back to Starlark by writing them to the+link plan.++`dist_lto_planner.py` reads the index and imports file produced by LLVM and+derives a number of artifacts:++1. For each object file, a `thinlto.bc` file (`bitcode_file`). This file is the+ same as the input bitcode file, except that LLVM has inserted a number of+ module imports to refer to the other modules that will be present when the+ object file is optimized.+2. For each object file, an optimization plan (`plan`). The optimization plan is+ a JSON document indicating how to construct an `opt` action for this object+ file. This plan includes this object file's module imports, whether or not+ this file contains bitcode at all, a location to place the optimized object+ file, and a list of archives that this object file imported.+3. For each archive, an optimization plan (`archive_plan`), which contains+ optimization plans for all of the object files contained within the archive.++This action is a dynamic action because, in the case that there are archives+that needed to be preprocessed by `thin_lto_prepare`, this action must read the+archive manifest.++### thin_lto_opt++After `thin_lto_index` completes, Buck2 launches `thin_lto_opt` actions for+every object file and for every archive. For each object file, Buck2 reads that+object file's optimization plan. At this phase, it is Buck2's responsibility to+declare dependencies on every object file referenced by that object's+compilation plan; it does so here by adding `hidden` dependencies on every+object file and archive that the archive plan says that this object depends on.++`thin_lto_opt` uses a Python wrapper around LLVM because of a bug (T116695431)+where LTO fatal errors don't prevent `clang` from returning an exit code of+zero. The Python script wraps `clang` and exits with a non-zero exit code if+`clang` produced an empty object file.++For each archive, Buck2 reads the archive's optimization plan and constructs+additional `thin_lto_opt` actions for each object file contained in the archive.+Buck2 creates a directory of symlinks (`opt_objects`) that either contains+symlinks to optimized object files (if the object file contained bitcode) or the+original object file (if it didn't). The purpose of this symlink directory is to+allow the final link to consume object files directly from this directory+without having to know whether they were optimized or not. Paths to these files+are passed to the link step via the optimization manifest (`opt_manifest`).++### thin_lto_link++The final link step. Similar to `thin_lto_index`, this involves creating a link+line to feed to the linker that uses the optimized artifacts that we just+calculated. In cases where Buck2 would put an archive on the link line, it+instead inserts `-Wl,--start-lib`, `-Wl,--end-lib`, and references to the+objects in `opt_objects`.
@@ -0,0 +1,53 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//linking:link_info.bzl",+ "SharedLibLinkable", # @unused Used as a type+)++EagerBitcodeLinkData = record(+ name = str,+ input_object_file = Artifact, # This may be a native object file or a bitcode file, we can't tell at this point+ output_index_shard_file = Artifact,+ plan = Artifact,+ output_first_codegen_round_native_object_file = field([Artifact, None]),+ output_precodegen_ir = field([Artifact, None]),+ output_final_native_object_file = Artifact,+ merged_bc = field([Artifact, None]),+ extra_outputs = field(dict[str, Artifact]),+)++LazyBitcodeLinkData = record(+ name = str,+ input_object_file = Artifact, # This may be a native object file or a bitcode file, we can't tell at this point+ output_index_shard_file = Artifact,+ plan = Artifact,+ output_final_native_object_file = Artifact,+ output_first_codegen_round_native_object_file = field([Artifact, None]),+ output_precodegen_ir = field([Artifact, None]),+ merged_bc = field([Artifact, None]),+ archive_start = bool,+ archive_end = bool,+ extra_outputs = field(dict[str, Artifact]),+)++DynamicLibraryLinkData = record(+ linkable = SharedLibLinkable,+)++LinkDataType = enum(+ "eager_bitcode",+ "lazy_bitcode",+ "dynamic_library",+)++DThinLTOLinkData = record(+ data_type = LinkDataType,+ link_data = field([LazyBitcodeLinkData, EagerBitcodeLinkData, DynamicLibraryLinkData]),+)
@@ -0,0 +1,926 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "make_artifact_tset",+)+load("@prelude//apple:apple_utility.bzl", "get_apple_architecture")+# @oss-disable[end= ]: load("@prelude//apple/meta_only:shared_library_interfaces.bzl", "get_shared_library_interface_generation_linker_flags")+load(+ "@prelude//apple/swift:swift_incremental_support.bzl",+ "get_uses_content_based_paths",+)+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")+load(+ "@prelude//cxx:cxx_link_utility.bzl",+ "CxxSanitizerRuntimeArguments",+ "cxx_link_cmd_parts",+ "get_extra_darwin_linker_flags",+ "linker_map_args",+)+load("@prelude//cxx:cxx_toolchain_types.bzl", "LinkerType")+load("@prelude//cxx:link_types.bzl", "ExtraLinkerOutputCategory", "LinkOptions")+load("@prelude//cxx:target_sdk_version.bzl", "get_target_sdk_version_flags")+load(+ "@prelude//linking:link_info.bzl",+ "ArchiveLinkable",+ "ExtraLinkerOutputs",+ "FrameworksLinkable", # @unused Used as a type+ "LinkInfo",+ "LinkedObject",+ "ObjectsLinkable",+ "SharedLibLinkable", # @unused Used as a type+ "SwiftmoduleLinkable", # @unused Used as a type+ "append_linkable_args",+ "map_to_link_infos",+ "unpack_external_debug_info",+)+load("@prelude//linking:strip.bzl", "strip_object")+load("@prelude//utils:argfile.bzl", "at_argfile")+load("@prelude//utils:arglike.bzl", "ArgLike")+load(":common_types.bzl", "DThinLTOLinkData", "DynamicLibraryLinkData", "EagerBitcodeLinkData", "LazyBitcodeLinkData", "LinkDataType")+load(":thin_link.bzl", "thin_link")+load(":thin_link_record_defs.bzl", "BitcodeMergeState", "ObjectFileOptimizationPlan")++def identity_projection(value: cmd_args):+ return value++# This tset exists for the sole purpose of saving memory. When action inputs+# are hashed, the memory cost for hashing tset projection generated input+# tree nodes is paid once per unique node. Without a tset projection every+# input is hashed once per action it is included in. The opt actions created+# here share a tremendous number of inputs, so we might end up hashing a+# given input 1000s of times, and paying dearly for it in memory consumption.+# This is not ideal either, the memory allocated to hash these tset projection+# generated inputs will not be freed for the duration of the build, but in+# testing that is a worth while tradeoff.+IdentityTSet = transitive_set(args_projections = {"identity": identity_projection})++def _sort_index_link_data(input_list: list[DThinLTOLinkData]) -> list[DThinLTOLinkData]:+ # Sort link datas to reduce binary size. The idea is to encourage the linker to load the minimal number of object files possible. We load force loaded archives first (since they will be loaded no matter what), then non lazy object files (which will also be loaded no matter what), then shared libraries (to share as many symbols as possible), then finally regular archives+ force_loaded_archives = []+ regular_archives = []+ object_files = []+ dynamic_libraries = []+ for link_data in input_list:+ if link_data.data_type == LinkDataType("eager_bitcode"):+ object_files.append(link_data)+ elif link_data.data_type == LinkDataType("lazy_bitcode"):+ regular_archives.append(link_data)+ elif link_data.data_type == LinkDataType("dynamic_library"):+ dynamic_libraries.append(link_data)++ return force_loaded_archives + object_files + dynamic_libraries + regular_archives++# Generate linker flags that are common to thin-link, native-link, and the link invocation used+# to generate a shared library interface+def _get_common_linker_flags(ctx: AnalysisContext, link_infos: list[LinkInfo], executable_link: bool, sanitizer_runtime_args: list[ArgLike]):+ cxx_toolchain = get_cxx_toolchain_info(ctx)+ result = cmd_args(cxx_link_cmd_parts(cxx_toolchain, executable_link).linker_flags)+ result.add(get_extra_darwin_linker_flags(ctx))+ result.add(sanitizer_runtime_args)++ for link in link_infos:+ result.add(link.pre_flags)+ result.add(link.post_flags)++ return result++DoubleCodegenState = enum(+ "disabled",+ "first_round",+ "second_round",+)++def create_output_first_codegen_round_native_object_file(ctx, name, double_codegen_enabled, uses_content_based_paths):+ if double_codegen_enabled:+ return ctx.actions.declare_output(name + ".opt.first_codegen_round.o", has_content_based_path = uses_content_based_paths)+ return None++def create_output_precodegen_ir(ctx, name, double_codegen_enabled, uses_content_based_paths):+ if double_codegen_enabled:+ return ctx.actions.declare_output(name + ".opt.precodegen.bc", has_content_based_path = uses_content_based_paths)+ return None++def complete_distributed_link_with_expanded_archive_link_data(+ ctx: AnalysisContext,+ artifacts,+ outputs,+ common_opt_cmd: cmd_args,+ double_codegen_enabled: bool,+ executable_link: bool,+ external_debug_info_container_directory: Artifact,+ extra_lto_outputs: dict[str, Artifact],+ extra_native_link_outputs: dict[str, Artifact],+ final_binary_out: Artifact,+ index_argsfile_out: Artifact,+ link_infos: list[LinkInfo],+ link_options: LinkOptions,+ linker_argsfile_out: Artifact,+ linker_map_out: Artifact | None,+ make_cat,+ premerger_enabled: bool,+ prepared_archive_artifacts,+ sanitizer_runtime_args: CxxSanitizerRuntimeArguments,+ uses_content_based_paths: bool,+):+ cxx_toolchain = get_cxx_toolchain_info(ctx)+ lto_planner = cxx_toolchain.internal_tools.dist_lto.planner[LinkerType("darwin")]+ lto_opt = cxx_toolchain.internal_tools.dist_lto.opt[LinkerType("darwin")]+ lto_archive_mapper = cxx_toolchain.internal_tools.dist_lto.archive_mapper++ normalized_identifier = link_options.identifier.replace("[", "_").replace("]", "_").replace(" ", "_") if link_options.identifier != None else None++ def make_id(i: str) -> str:+ """Used to make sure identifiers for our actions include the provided identifier"""+ if normalized_identifier != None:+ return normalized_identifier + "_" + i+ return i++ recorded_outputs = {}++ def name_for_obj(link_name: str, object_artifact: Artifact) -> str:+ """Creates a unique name/path we can use for a particular object file input"""+ prefix = "{}/{}".format(link_name, object_artifact.short_path)+ case_insensitive_prefix = prefix.lower()+ # it's possible (though unlikely) that we can get duplicate name/short_path, so just uniquify them.+ # Make sure we case normalize before to avoid collisions on case in-sensitive file systems.+ if case_insensitive_prefix in recorded_outputs:+ recorded_outputs[case_insensitive_prefix] += 1+ extra = recorded_outputs[case_insensitive_prefix]+ prefix = "{}-{}".format(prefix, extra)+ else:+ recorded_outputs[case_insensitive_prefix] = 1+ return prefix++ names = {}++ def name_for_link(info: LinkInfo) -> str:+ """Creates a unique name for a LinkInfo that we are consuming"""+ name = info.name or "unknown"+ if name not in names:+ names[name] = 1+ else:+ names[name] += 1+ name += "-{}".format(names[name])+ return make_id(name)++ # The process to optimize and codegen a given bitcode file may depend on other bitcode+ # files (ie. to inline function calls between bitcode files). Which bitcode files depend+ # on one another is not known until thin link (sometimes called the dynamic plan) is run.+ # For each input bitcode file, thin link will produce a plan JSON document that will identify+ # which other bitcode files (or archive of bitcode files) it should be optimized along side.+ # Thin link idenitifies these depended upon bitcode files by their index in the sorted version of this array.+ raw_link_data = []+ debug_info_symlink_map = {}+ deps_linker_flags = cmd_args()++ def declare_extra_opt_outputs(name: str) -> dict[str, Artifact]:+ result = {}+ for output_type_str in extra_lto_outputs.keys():+ result[output_type_str] = ctx.actions.declare_output(name + "." + output_type_str, has_content_based_path = uses_content_based_paths)+ return result++ for link in link_infos:+ link_name = name_for_link(link)++ deps_linker_flags.add(link.pre_flags)+ deps_linker_flags.add(link.post_flags)++ for linkable in link.linkables:+ if isinstance(linkable, ObjectsLinkable):+ for obj in linkable.objects:+ name = name_for_obj(link_name, obj)+ index_shard_output = ctx.actions.declare_output(name + ".thinlto.bc", has_content_based_path = uses_content_based_paths)+ plan_output = ctx.actions.declare_output(name + ".opt.plan", has_content_based_path = uses_content_based_paths)+ final_native_object_file_output = ctx.actions.declare_output(name + ".opt.o", has_content_based_path = uses_content_based_paths)+ merged_bc_output = None+ if premerger_enabled:+ # Bitcode files are referenced by index shards by output path, and these merged bitcode files are produced during the+ # same thin-link action that produces the index shards. For this reason, we cannot enable content based path hashing+ # for these outputs because we need to know the final path before running the action.+ merged_bc_output = ctx.actions.declare_output(name + ".merged.bc", has_content_based_path = False)++ output_first_codegen_round_native_object_file = create_output_first_codegen_round_native_object_file(+ ctx, name, double_codegen_enabled, uses_content_based_paths+ )+ output_precodegen_ir = create_output_precodegen_ir(ctx, name, double_codegen_enabled, uses_content_based_paths)++ data = DThinLTOLinkData(+ data_type = LinkDataType("eager_bitcode"),+ link_data = EagerBitcodeLinkData(+ name = name,+ input_object_file = obj,+ output_index_shard_file = index_shard_output,+ plan = plan_output,+ output_final_native_object_file = final_native_object_file_output,+ output_first_codegen_round_native_object_file = output_first_codegen_round_native_object_file,+ output_precodegen_ir = output_precodegen_ir,+ merged_bc = merged_bc_output,+ extra_outputs = declare_extra_opt_outputs(name),+ ),+ )+ raw_link_data.append(data)+ debug_info_symlink_map["debug_info_file_{}".format(len(debug_info_symlink_map))] = final_native_object_file_output+ elif isinstance(linkable, ArchiveLinkable) and linkable.archive.external_objects:+ for virtual_archive_index, obj in enumerate(linkable.archive.external_objects):+ name = name_for_obj(link_name, obj)+ index_shard_output = ctx.actions.declare_output(name + ".thinlto.bc", has_content_based_path = uses_content_based_paths)+ plan_output = ctx.actions.declare_output(name + ".opt.plan", has_content_based_path = uses_content_based_paths)+ final_native_object_file_output = ctx.actions.declare_output(name + ".opt.o", has_content_based_path = uses_content_based_paths)+ merged_bc_output = None+ if premerger_enabled:+ # Bitcode files are referenced by index shards by output path, and these merged bitcode files are produced during the+ # same thin-link action that produces the index shards. For this reason, we cannot enable content based path hashing+ # for these outputs because we need to know the final path before running the action.+ merged_bc_output = ctx.actions.declare_output(name + ".merged.bc", has_content_based_path = False)++ output_first_codegen_round_native_object_file = create_output_first_codegen_round_native_object_file(+ ctx, name, double_codegen_enabled, uses_content_based_paths+ )+ output_precodegen_ir = create_output_precodegen_ir(ctx, name, double_codegen_enabled, uses_content_based_paths)++ # The first member in a non force loaded virtual archive gets --start-lib prended on the command line+ archive_start = (not linkable.link_whole) and virtual_archive_index == 0+ archive_end = (not linkable.link_whole) and virtual_archive_index == len(linkable.archive.external_objects) - 1+ data = DThinLTOLinkData(+ data_type = LinkDataType("lazy_bitcode"),+ link_data = LazyBitcodeLinkData(+ name = name,+ input_object_file = obj,+ output_index_shard_file = index_shard_output,+ plan = plan_output,+ output_final_native_object_file = final_native_object_file_output,+ output_first_codegen_round_native_object_file = output_first_codegen_round_native_object_file,+ output_precodegen_ir = output_precodegen_ir,+ merged_bc = merged_bc_output,+ archive_start = archive_start,+ archive_end = archive_end,+ extra_outputs = declare_extra_opt_outputs(name),+ ),+ )+ raw_link_data.append(data)+ debug_info_symlink_map["debug_info_file_{}".format(len(debug_info_symlink_map))] = final_native_object_file_output+ elif isinstance(linkable, ArchiveLinkable):+ manifest = artifacts[prepared_archive_artifacts[linkable.archive.artifact].manifest].read_json()+ if not len(manifest["objects"]):+ continue++ archive_name = name_for_obj(link_name, linkable.archive.artifact)+ archive_contents_mapper_cmd = cmd_args(lto_archive_mapper)+ archive_contents_mapper_cmd.add("--objects_dir", prepared_archive_artifacts[linkable.archive.artifact].extracted_object_files_dir)+ for archive_index, object_basename in enumerate(manifest["objects"]):+ archive_start = (not linkable.link_whole) and archive_index == 0+ archive_end = (not linkable.link_whole) and archive_index == len(manifest["objects"]) - 1+ name = "{}/{}".format(archive_name, object_basename)+ input_object_file = ctx.actions.declare_output(name, has_content_based_path = uses_content_based_paths)+ index_shard_output = ctx.actions.declare_output(name + ".thinlto.bc", has_content_based_path = uses_content_based_paths)+ plan_output = ctx.actions.declare_output(name + ".opt.plan", has_content_based_path = uses_content_based_paths)+ final_native_object_file_output = ctx.actions.declare_output(name + ".opt.o", has_content_based_path = uses_content_based_paths)+ merged_bc_output = None+ if premerger_enabled:+ # Bitcode files are referenced by index shards by output path, and these merged bitcode files are produced during the+ # same thin-link action that produces the index shards. For this reason, we cannot enable content based path hashing+ # for these outputs because we need to know the final path before running the action.+ merged_bc_output = ctx.actions.declare_output(name + ".merged.bc", has_content_based_path = False)+ output_first_codegen_round_native_object_file = create_output_first_codegen_round_native_object_file(+ ctx, name, double_codegen_enabled, uses_content_based_paths+ )+ output_precodegen_ir = create_output_precodegen_ir(ctx, name, double_codegen_enabled, uses_content_based_paths)++ raw_link_data.append(+ DThinLTOLinkData(+ data_type = LinkDataType("lazy_bitcode"),+ link_data = LazyBitcodeLinkData(+ name = name,+ input_object_file = input_object_file,+ output_index_shard_file = index_shard_output,+ plan = plan_output,+ output_final_native_object_file = final_native_object_file_output,+ output_first_codegen_round_native_object_file = output_first_codegen_round_native_object_file,+ output_precodegen_ir = output_precodegen_ir,+ merged_bc = merged_bc_output,+ archive_start = archive_start,+ archive_end = archive_end,+ extra_outputs = declare_extra_opt_outputs(name),+ ),+ )+ )+ archive_contents_mapper_cmd.add("--object_to_map", object_basename, input_object_file.as_output())+ debug_info_symlink_map["debug_info_file_{}".format(len(debug_info_symlink_map))] = final_native_object_file_output+ ctx.actions.run(archive_contents_mapper_cmd, category = make_cat("thin_lto_map_archive"), identifier = archive_name)++ elif isinstance(linkable, SharedLibLinkable):+ data = DThinLTOLinkData(+ data_type = LinkDataType("dynamic_library"),+ link_data = DynamicLibraryLinkData(linkable = linkable),+ )+ raw_link_data.append(data)+ elif isinstance(linkable, FrameworksLinkable) or isinstance(linkable, SwiftmoduleLinkable):+ # These linkables are handled separately for flag deduplication purposes, as in append_linkable_args:+ # https://www.internalfb.com/code/fbsource/[c6d2c820b394]/fbcode/buck2/prelude/linking/link_info.bzl?lines=271-278+ pass+ else:+ fail("Unhandled linkable type: {}".format(str(linkable)))++ common_link_flags = _get_common_linker_flags(ctx, link_infos, executable_link, sanitizer_runtime_args.extra_link_args)++ sorted_index_link_data = _sort_index_link_data(raw_link_data)++ link_plan_out = ctx.actions.declare_output(final_binary_out.basename + ".link-plan.json", has_content_based_path = uses_content_based_paths)++ thin_link(+ ctx = ctx,+ final_binary_out = final_binary_out,+ sorted_index_link_data = sorted_index_link_data,+ common_link_flags = common_link_flags,+ linker = cxx_link_cmd_parts(cxx_toolchain, executable_link).linker,+ lto_planner = lto_planner,+ post_linker_flags = cxx_link_cmd_parts(cxx_toolchain, executable_link).post_linker_flags,+ index_argsfile_out = outputs[index_argsfile_out],+ link_plan_out = link_plan_out,+ identifier = link_options.identifier,+ premerger_enabled = premerger_enabled,+ use_content_based_output_paths = uses_content_based_paths,+ make_cat = make_cat,+ make_id = make_id,+ )++ # Create an argsfile and dump all the flags to be processed later by lto_opt.+ # These flags are common to all opt actions, we don't need an argfile for each action, one+ # for the entire link unit will do.+ opt_argsfile = ctx.actions.declare_output(final_binary_out.basename + ".lto_opt_argsfile", has_content_based_path = uses_content_based_paths)+ ctx.actions.write(opt_argsfile.as_output(), common_opt_cmd, allow_args = True)++ def optimize_object(ctx: AnalysisContext, artifacts, outputs, bitcode_link_data, double_codegen_state: DoubleCodegenState, merged_cgdata: Artifact | None):+ output_index_shard_file = bitcode_link_data.output_index_shard_file+ input_object_file = bitcode_link_data.input_object_file+ merged_bc = bitcode_link_data.merged_bc+ name = bitcode_link_data.name+ if double_codegen_state == DoubleCodegenState("first_round"):+ output_native_object_file = bitcode_link_data.output_first_codegen_round_native_object_file+ else:+ output_native_object_file = bitcode_link_data.output_final_native_object_file++ plan = bitcode_link_data.plan++ optimization_plan = ObjectFileOptimizationPlan(**artifacts[plan].read_json())++ # If the object was not compiled with thinlto flags, then there+ # won't be valid outputs for it from the indexing, but we still+ # need to bind the artifact. Similarily, if a bitcode file is not+ # loaded by the indexing phase, or is absorbed by another module,+ # there is no point optimizing it.+ if not optimization_plan.loaded_by_linker or not optimization_plan.is_bitcode or optimization_plan.merge_state == BitcodeMergeState("ABSORBED").value:+ ctx.actions.write(outputs[output_native_object_file].as_output(), "")+ if double_codegen_state == DoubleCodegenState("first_round"):+ ctx.actions.write(outputs[bitcode_link_data.output_precodegen_ir].as_output(), "")+ if double_codegen_state == DoubleCodegenState("disabled") or double_codegen_state == DoubleCodegenState("first_round"):+ mapped_extra_outputs = {output_type: outputs[artifact] for output_type, artifact in bitcode_link_data.extra_outputs.items()}+ for extra_output_artifact in mapped_extra_outputs.values():+ ctx.actions.write(extra_output_artifact.as_output(), "")+ return++ opt_cmd = cmd_args(lto_opt)+ if double_codegen_state == DoubleCodegenState("second_round"):+ # For the second round, resume from the precodegen IR produced in the first round+ opt_cmd.add("--input", bitcode_link_data.output_precodegen_ir)+ opt_cmd.add("--codegen-only")+ else:+ # First round or disabled, there is nothing to resume from+ if premerger_enabled:+ if optimization_plan.merge_state == BitcodeMergeState("STANDALONE").value:+ opt_cmd.add("--input", input_object_file)+ elif optimization_plan.merge_state == BitcodeMergeState("ROOT").value:+ opt_cmd.add("--input", merged_bc)+ else:+ fail("Invalid merge state {} for bitcode file: {}".format(optimization_plan.merge_state, output_index_shard_file))+ else:+ opt_cmd.add("--input", input_object_file)++ # Always provide the index regardless of round because codegen depends on information in the index+ opt_cmd.add("--index", output_index_shard_file)++ opt_cmd.add(cmd_args(hidden = common_opt_cmd))+ opt_cmd.add("--shared-args", opt_argsfile)+ opt_cmd.add("--compiler", cxx_toolchain.cxx_compiler_info.compiler)+ if double_codegen_state == DoubleCodegenState("first_round"):+ opt_cmd.add("--generate-cgdata")+ elif double_codegen_state == DoubleCodegenState("second_round"):+ opt_cmd.add("--read-cgdata", merged_cgdata)++ # Second round has already completed importing, so the only bitcode file necessary is the one being optimized,+ # inlined functions have already been embedded into the saved module in round 1+ if double_codegen_state != DoubleCodegenState("second_round"):+ imported_input_bitcode_files = [sorted_index_link_data[idx].link_data.input_object_file for idx in optimization_plan.imports]++ if premerger_enabled:+ imported_merged_input_bitcode_files = [sorted_index_link_data[idx].link_data.merged_bc for idx in optimization_plan.imports]+ opt_cmd.add(cmd_args(hidden = imported_merged_input_bitcode_files))++ opt_cmd.add(cmd_args(hidden = imported_input_bitcode_files))++ projected_opt_cmd = cmd_args(ctx.actions.tset(IdentityTSet, value = opt_cmd).project_as_args("identity"))++ if double_codegen_state == DoubleCodegenState("first_round"):+ category_string = "thin_lto_opt_object_first_round"+ elif double_codegen_state == DoubleCodegenState("second_round"):+ category_string = "thin_lto_opt_object_second_round"+ else:+ category_string = "thin_lto_opt_object"++ # We have to add outputs after wrapping the cmd_args in a projection+ projected_opt_cmd.add("--out", outputs[output_native_object_file].as_output())++ if double_codegen_state == DoubleCodegenState("first_round"):+ projected_opt_cmd.add("--save-precodegen-ir", outputs[bitcode_link_data.output_precodegen_ir].as_output())++ if link_options.extra_linker_outputs_flags_factory and (+ double_codegen_state == DoubleCodegenState("disabled") or double_codegen_state == DoubleCodegenState("first_round")+ ):+ # Extra linker outputs are all produced during the first round (or only round if double codegen is disabled)+ mapped_extra_outputs = {output_type: outputs[artifact] for output_type, artifact in bitcode_link_data.extra_outputs.items()}+ extra_outputs_args = cmd_args(+ link_options.extra_linker_outputs_flags_factory(+ ctx,+ mapped_extra_outputs,+ ExtraLinkerOutputCategory("produced-during-distributed-thin-lto-opt"),+ ),+ )+ projected_opt_cmd.add("--", extra_outputs_args)++ ctx.actions.run(projected_opt_cmd, category = make_cat(category_string), identifier = name)++ def dynamic_optimize(bitcode_link_data, double_codegen_state: DoubleCodegenState, merged_cgdata: Artifact | None = None):+ if double_codegen_state == DoubleCodegenState("first_round"):+ optimize_object_outputs = [+ bitcode_link_data.output_first_codegen_round_native_object_file.as_output(),+ bitcode_link_data.output_precodegen_ir.as_output(),+ ]++ # Produce extra linker outputs in first round+ optimize_object_outputs += [artifact.as_output() for artifact in bitcode_link_data.extra_outputs.values()]+ elif double_codegen_state == DoubleCodegenState("second_round"):+ # Only produce the final native object file in the second round+ optimize_object_outputs = [bitcode_link_data.output_final_native_object_file.as_output()]+ else:+ # If there is only one around, produce everything in that round+ optimize_object_outputs = [bitcode_link_data.output_final_native_object_file.as_output()]+ optimize_object_outputs += [artifact.as_output() for artifact in bitcode_link_data.extra_outputs.values()]++ ctx.actions.dynamic_output(+ dynamic = [bitcode_link_data.plan],+ inputs = [],+ outputs = optimize_object_outputs,+ f = lambda ctx, artifacts, outputs: optimize_object(+ ctx,+ artifacts,+ outputs,+ bitcode_link_data,+ double_codegen_state = double_codegen_state,+ merged_cgdata = merged_cgdata,+ ),+ )++ for artifact in sorted_index_link_data:+ if artifact.data_type == LinkDataType("eager_bitcode") or artifact.data_type == LinkDataType("lazy_bitcode"):+ double_codegen_state = DoubleCodegenState("first_round") if double_codegen_enabled else DoubleCodegenState("disabled")+ dynamic_optimize(artifact.link_data, double_codegen_state = double_codegen_state, merged_cgdata = None)++ def merge_cgdata(ctx: AnalysisContext, artifacts, outputs, output_merged_cgdata_file):+ merge_cmd = cmd_args(cxx_toolchain.llvm_cgdata)+ merge_args = cmd_args("--merge")+ for artifact in sorted_index_link_data:+ if artifact.data_type == LinkDataType("eager_bitcode") or artifact.data_type == LinkDataType("lazy_bitcode"):+ optimization_plan = ObjectFileOptimizationPlan(**artifacts[artifact.link_data.plan].read_json())+ if (+ not optimization_plan.loaded_by_linker+ or not optimization_plan.is_bitcode+ or optimization_plan.merge_state == BitcodeMergeState("ABSORBED").value+ ):+ continue++ # Some targets have spaces in them, we wrap in single quotes to make sure they are treated as single files+ merge_args.add(cmd_args(artifact.link_data.output_first_codegen_round_native_object_file, quote = "shell"))+ merge_args.add("--output", outputs[output_merged_cgdata_file].as_output())+ merge_cmd.add(+ at_argfile(+ actions = ctx.actions,+ name = final_binary_out.basename + ".llvm-cgdata-argsfile",+ args = merge_args,+ )+ )+ ctx.actions.run(merge_cmd, category = make_cat("thin_lto_merge_cgdata"), identifier = link_options.identifier)++ if double_codegen_enabled:+ merged_cgdata_file = ctx.actions.declare_output(final_binary_out.basename + ".cgdata", has_content_based_path = uses_content_based_paths)+ ctx.actions.dynamic_output(+ dynamic = [+ artifact.link_data.plan+ for artifact in sorted_index_link_data+ if artifact.data_type == LinkDataType("lazy_bitcode") or artifact.data_type == LinkDataType("eager_bitcode")+ ],+ inputs = [],+ outputs = [merged_cgdata_file.as_output()],+ f = lambda ctx, artifacts, outputs: merge_cgdata(+ ctx,+ artifacts,+ outputs,+ merged_cgdata_file,+ ),+ )++ for artifact in sorted_index_link_data:+ link_data = artifact.link_data+ if artifact.data_type == LinkDataType("eager_bitcode") or artifact.data_type == LinkDataType("lazy_bitcode"):+ dynamic_optimize(link_data, merged_cgdata = merged_cgdata_file, double_codegen_state = DoubleCodegenState("second_round"))++ ctx.actions.symlinked_dir(outputs[external_debug_info_container_directory], debug_info_symlink_map)++ # merge extra outputs produced by opt actions+ def merge_extra_opt_outputs(ctx: AnalysisContext, artifacts, outputs, lto_outputs):+ opt_outputs_to_merge = []+ for artifact in sorted_index_link_data:+ if artifact.data_type == LinkDataType("eager_bitcode") or artifact.data_type == LinkDataType("lazy_bitcode"):+ optimization_plan = ObjectFileOptimizationPlan(**artifacts[artifact.link_data.plan].read_json())+ if (+ not optimization_plan.loaded_by_linker+ or not optimization_plan.is_bitcode+ or optimization_plan.merge_state == BitcodeMergeState("ABSORBED").value+ ):+ continue++ opt_outputs_to_merge.append(artifact.link_data.extra_outputs)++ mapped_lto_outputs = {output_type: outputs[artifact] for output_type, artifact in lto_outputs.items()}+ link_options.extra_distributed_thin_lto_opt_outputs_merger(ctx, mapped_lto_outputs, opt_outputs_to_merge)++ if link_options.extra_distributed_thin_lto_opt_outputs_merger:+ if extra_lto_outputs:+ mapped_lto_outputs = {output_type: outputs[artifact] for output_type, artifact in extra_lto_outputs.items()}+ ctx.actions.dynamic_output(+ dynamic = [+ artifact.link_data.plan+ for artifact in sorted_index_link_data+ if artifact.data_type == LinkDataType("lazy_bitcode") or artifact.data_type == LinkDataType("eager_bitcode")+ ],+ inputs = [],+ outputs = [outputs[artifact].as_output() for artifact in extra_lto_outputs.values()],+ f = lambda ctx, artifacts, outputs: merge_extra_opt_outputs(ctx, artifacts, outputs, mapped_lto_outputs),+ )++ def thin_lto_final_link(ctx: AnalysisContext, artifacts, outputs):+ plan = artifacts[link_plan_out].read_json()+ link_args = cmd_args()++ # non_lto_objects are the ones that weren't compiled with thinlto+ # flags. In that case, we need to link against the original object.+ non_lto_objects = {int(k): 1 for k in plan["non_lto_objects"]}++ object_file_linker_inputs = []++ for idx, artifact in enumerate(sorted_index_link_data):+ if artifact.data_type == LinkDataType("dynamic_library"):+ append_linkable_args(link_args, artifact.link_data.linkable)+ elif artifact.data_type == LinkDataType("eager_bitcode") or artifact.data_type == LinkDataType("lazy_bitcode"):+ optimization_plan = ObjectFileOptimizationPlan(**artifacts[artifact.link_data.plan].read_json())++ # Input bitcode files that were loaded in thin-link, but merged into another bitcode file+ # will not have a native object file output, so we skip them here.+ if optimization_plan.merge_state == BitcodeMergeState("ABSORBED").value:+ continue++ # Same for object files that are not loaded, do not include them in native link.+ if not optimization_plan.loaded_by_linker:+ continue++ link_line_position = optimization_plan.final_link_line_position++ if idx in non_lto_objects:+ object_file_linker_inputs.append((link_line_position, artifact.link_data.input_object_file))+ else:+ object_file_linker_inputs.append((link_line_position, artifact.link_data.output_final_native_object_file))++ link_cmd_parts = cxx_link_cmd_parts(cxx_toolchain, executable_link)+ link_cmd = cmd_args(link_cmd_parts.linker)+ link_args.add(common_link_flags)++ if link_options.extra_linker_outputs_flags_factory != None:+ # We need the inner artifacts here+ mapped_outputs = {output_type: outputs[artifact] for output_type, artifact in extra_native_link_outputs.items()}+ link_args.add(+ link_options.extra_linker_outputs_flags_factory(+ ctx, mapped_outputs, ExtraLinkerOutputCategory("produced-during-distributed-thin-lto-native-link")+ )+ )++ link_args.add("-o", outputs[final_binary_out].as_output())+ if linker_map_out:+ link_args.add(linker_map_args(cxx_toolchain, outputs[linker_map_out].as_output()).flags)+ ordered_object_file_linker_inputs = sorted(object_file_linker_inputs, key = lambda x: x[0])+ for _, artifact in ordered_object_file_linker_inputs:+ link_args.add(artifact)+ link_cmd.add(+ at_argfile(+ actions = ctx.actions,+ name = outputs[linker_argsfile_out],+ args = link_args,+ allow_args = True,+ has_content_based_path = uses_content_based_paths,+ )+ )+ link_cmd.add(link_cmd_parts.post_linker_flags)++ ctx.actions.run(link_cmd, category = make_cat("thin_lto_link"), identifier = link_options.identifier)++ final_link_outputs = [outputs[final_binary_out].as_output(), outputs[linker_argsfile_out].as_output()]+ if linker_map_out:+ final_link_outputs.append(outputs[linker_map_out].as_output())++ # Add outputs produced by native link only+ final_link_outputs += [outputs[output_artifact].as_output() for output_artifact in extra_native_link_outputs.values()]++ ctx.actions.dynamic_output(+ dynamic = [link_plan_out]+ + [+ artifact.link_data.plan+ for artifact in sorted_index_link_data+ if artifact.data_type == LinkDataType("lazy_bitcode") or artifact.data_type == LinkDataType("eager_bitcode")+ ],+ inputs = [],+ outputs = final_link_outputs,+ f = thin_lto_final_link,+ )++PreparedArchiveArtitfacts = record(+ manifest = field(Artifact),+ extracted_object_files_dir = field(Artifact),+)++def generate_shared_library_interface(+ ctx: AnalysisContext,+ identifier: str,+ executable_link: bool,+ link_infos: list[LinkInfo],+ output: Artifact,+ sanitizer_runtime_args: list[ArgLike],+ shared_library_interface_out: Artifact,+):+ # This flag generation logic must be at least semmantically equivalent to the logic used to create a thin-link invocation.+ # Do not for example change the input order in one place, they must be kept in sync to generate an accurate interface.++ common_linker_flags = _get_common_linker_flags(ctx, link_infos, executable_link, sanitizer_runtime_args)++ eager_objects = cmd_args()+ lazy_objects = cmd_args()+ dynamic_libraries = cmd_args()++ for link in link_infos:+ for linkable in link.linkables:+ if isinstance(linkable, ObjectsLinkable):+ for obj in linkable.objects:+ eager_objects.add(obj)+ elif isinstance(linkable, ArchiveLinkable) and linkable.archive.external_objects:+ lazy_objects.add("-Wl,--start-lib")+ for obj in linkable.archive.external_objects:+ lazy_objects.add(obj)+ lazy_objects.add("-Wl,--end-lib")+ elif isinstance(linkable, ArchiveLinkable):+ # Thin link requires that we extract all archives beforehand via dynamic output so that we can declare various+ # artifacts for each member. These artifacts are the link plan, the summary shard, the merged bitcode file etc.+ # However, this linking invocation does not produce any of those, it only produces the shared library interface.+ # Passing the archive directly instead of extracting it, then passing the members between --start-lib --end-lib+ # flags should be semantically equivalent. Note however, that we only do this in this branch where we are dealing+ # with some kind of pre-build static archive where Buck is not aware of the contents. If we built this static archive,+ # just pass the members directly above, don't bother creating an archive for no reason.+ lazy_objects.add(linkable.archive.artifact)+ elif isinstance(linkable, SharedLibLinkable):+ append_linkable_args(dynamic_libraries, linkable)+ elif isinstance(linkable, FrameworksLinkable) or isinstance(linkable, SwiftmoduleLinkable):+ # These linkables are handled separately for flag deduplication purposes, as in append_linkable_args:+ # https://www.internalfb.com/code/fbsource/[c6d2c820b394]/fbcode/buck2/prelude/linking/link_info.bzl?lines=271-278+ pass+ else:+ fail("Unhandled linkable type: {}".format(str(linkable)))++ interface_generation_linker_args = cmd_args()+ interface_generation_linker_args.add(common_linker_flags)+ interface_generation_linker_args.add(eager_objects)+ interface_generation_linker_args.add(lazy_objects)+ interface_generation_linker_args.add(dynamic_libraries)+ output_as_string = cmd_args(output, ignore_artifacts = True)+ interface_generation_linker_args.add("-o", output_as_string)+ interface_generation_linker_argsfile = ctx.actions.declare_output(+ output.basename + ".shared_library_interface_generation_argsfile", has_content_based_path = False+ )+ interface_generation_linker_argsfile, _ = ctx.actions.write(+ interface_generation_linker_argsfile,+ interface_generation_linker_args,+ with_inputs = True,+ allow_args = True,+ )+ cxx_toolchain = get_cxx_toolchain_info(ctx)+ linker = cxx_link_cmd_parts(cxx_toolchain, executable_link).linker+ interface_generation_linker_invocation = cmd_args(linker)+ interface_generation_linker_invocation.add(cmd_args(interface_generation_linker_argsfile, format = "@{}"))++ interface_generation_linker_invocation.add(+ # @oss-disable[end= ]: get_shared_library_interface_generation_linker_flags(shared_library_interface_out),+ cmd_args(),+ )+ ctx.actions.run(interface_generation_linker_invocation, category = "generate_shared_library_interface", identifier = identifier)++def cxx_darwin_dist_link(+ ctx: AnalysisContext,+ # The destination for the link output.+ output: Artifact,+ opts: LinkOptions,+ premerger_enabled: bool,+ double_codegen_enabled: bool,+ executable_link: bool,+ sanitizer_runtime_args: CxxSanitizerRuntimeArguments,+ shared_library_interface: Artifact | None,+ linker_map: Artifact | None = None,+) -> (LinkedObject, dict[str, list[DefaultInfo]]):+ """+ Perform a distributed thin-lto link into the supplied output++ Distributed thinlto splits the link into three stages:+ 1. global "indexing" step+ 2. many individual compilation unit optimization steps+ 3. final global link step++ The 2nd and 3rd of those are done just by constructing compiler/linker commands (in dynamic_output+ sections) using the output of the first.++ For the first, we need to post-process the linker index output to get it into a form+ that is easy for us to consume from within bzl.+ """++ def make_cat(c: str) -> str:+ """Used to make sure categories for our actions include the provided suffix"""+ if opts.category_suffix != None:+ return c + "_" + opts.category_suffix+ return c++ links = opts.links + opts.binary_links++ link_infos = map_to_link_infos(links)++ cxx_toolchain = get_cxx_toolchain_info(ctx)+ lto_prepare = cxx_toolchain.internal_tools.dist_lto.prepare[LinkerType("darwin")]++ archive_manifests = []++ prepare_cat = make_cat("thin_lto_prepare")++ prepared_archive_artifacts = {}++ uses_content_based_paths = get_uses_content_based_paths(ctx)++ recorded_artifact_names = {}+ for link in link_infos:+ for linkable in link.linkables:+ if isinstance(linkable, ArchiveLinkable) and not linkable.archive.external_objects:+ link_name = link.name or "unknown"+ archive_name_candidate = "{}-{}".format(link_name, linkable.archive.artifact.short_path)+ # On case in-sensitive file systems, we need to make sure that, we normalize case before checking for duplicates+ case_insensitive_archive_name_candidate = archive_name_candidate.lower()+ if case_insensitive_archive_name_candidate in recorded_artifact_names:+ recorded_artifact_names[case_insensitive_archive_name_candidate] += 1+ archive_name = "{}-{}".format(archive_name_candidate, recorded_artifact_names[case_insensitive_archive_name_candidate])+ else:+ recorded_artifact_names[case_insensitive_archive_name_candidate] = 1+ archive_name = archive_name_candidate++ archive_manifest = ctx.actions.declare_output(+ "%s/%s/manifest.json" % (prepare_cat, archive_name), has_content_based_path = uses_content_based_paths+ )+ archive_objects = ctx.actions.declare_output(+ "%s/%s/objects" % (prepare_cat, archive_name), has_content_based_path = uses_content_based_paths, dir = True+ )++ prepare_args = cmd_args([+ lto_prepare,+ "--manifest-out",+ archive_manifest.as_output(),+ "--objects-out",+ archive_objects.as_output(),+ "--ar",+ cxx_toolchain.linker_info.archiver,+ "--archive",+ linkable.archive.artifact,+ "--name",+ archive_name,+ "--target-architecture",+ get_apple_architecture(ctx),+ "--lipo",+ cxx_toolchain.lipo,+ ])+ ctx.actions.run(prepare_args, category = make_cat("thin_lto_prepare"), identifier = archive_name)+ prepared_archive_artifacts[linkable.archive.artifact] = PreparedArchiveArtitfacts(+ manifest = archive_manifest, extracted_object_files_dir = archive_objects+ )+ archive_manifests.append(archive_manifest)++ linker_argsfile_out = ctx.actions.declare_output(output.basename + ".thinlto_link_argsfile", has_content_based_path = uses_content_based_paths)+ index_argsfile_out = ctx.actions.declare_output(output.basename + ".thinlto_index_argsfile", has_content_based_path = uses_content_based_paths)++ def prepare_opt_flags(link_infos: list[LinkInfo]) -> cmd_args:+ opt_flags = cmd_args(cxx_toolchain.linker_info.dist_thin_lto_codegen_flags)+ if cxx_toolchain.pass_plugin:+ opt_flags.add(cmd_args(cxx_toolchain.pass_plugin, format = "-fpass-plugin={}"))+ opt_flags.add(get_target_sdk_version_flags(ctx))+ for link in link_infos:+ opt_flags.add(link.dist_thin_lto_codegen_flags)+ return opt_flags++ common_opt_cmd = prepare_opt_flags(link_infos)++ external_debug_info_container_directory = ctx.actions.declare_output(+ output.basename + ".debug_info_dir", dir = True, has_content_based_path = uses_content_based_paths+ )++ extra_linker_outputs_factory = opts.extra_linker_outputs_factory+ link_outputs = [output.as_output(), index_argsfile_out.as_output(), linker_argsfile_out.as_output(), external_debug_info_container_directory.as_output()]++ lto_outputs = ExtraLinkerOutputs()+ native_link_outputs = ExtraLinkerOutputs()+ if extra_linker_outputs_factory:+ lto_outputs = extra_linker_outputs_factory(ctx, ExtraLinkerOutputCategory("produced-during-distributed-thin-lto-opt"))+ native_link_outputs = extra_linker_outputs_factory(ctx, ExtraLinkerOutputCategory("produced-during-distributed-thin-lto-native-link"))++ link_outputs.extend([lto_output.as_output() for lto_output in lto_outputs.artifacts.values()])+ link_outputs.extend([native_link_output.as_output() for native_link_output in native_link_outputs.artifacts.values()])++ if linker_map:+ link_outputs.append(linker_map.as_output())++ if opts.produce_shared_library_interface:+ generate_shared_library_interface(+ ctx = ctx,+ identifier = opts.identifier,+ executable_link = executable_link,+ link_infos = link_infos,+ output = output,+ sanitizer_runtime_args = sanitizer_runtime_args.extra_link_args,+ shared_library_interface_out = shared_library_interface,+ )++ ctx.actions.dynamic_output(+ dynamic = archive_manifests,+ inputs = [],+ outputs = link_outputs,+ f = lambda ctx, artifacts, outputs: complete_distributed_link_with_expanded_archive_link_data(+ ctx,+ artifacts,+ outputs,+ common_opt_cmd = common_opt_cmd,+ executable_link = executable_link,+ external_debug_info_container_directory = external_debug_info_container_directory,+ extra_lto_outputs = lto_outputs.artifacts,+ extra_native_link_outputs = native_link_outputs.artifacts,+ final_binary_out = output,+ index_argsfile_out = index_argsfile_out,+ link_infos = link_infos,+ link_options = opts,+ linker_argsfile_out = linker_argsfile_out,+ linker_map_out = linker_map,+ make_cat = make_cat,+ premerger_enabled = premerger_enabled,+ double_codegen_enabled = double_codegen_enabled,+ prepared_archive_artifacts = prepared_archive_artifacts,+ sanitizer_runtime_args = sanitizer_runtime_args,+ uses_content_based_paths = uses_content_based_paths,+ ),+ )++ final_output = output+ unstripped_output = output+ if opts.strip:+ strip_args = opts.strip_args_factory(ctx) if opts.strip_args_factory else cmd_args()+ final_output = strip_object(ctx, cxx_toolchain, final_output, strip_args, opts.category_suffix)++ external_debug_info = make_artifact_tset(+ actions = ctx.actions,+ artifacts = [external_debug_info_container_directory],+ label = ctx.label,+ children = [unpack_external_debug_info(ctx.actions, link_args) for link_args in links],+ )++ return LinkedObject(+ output = final_output,+ unstripped_output = unstripped_output,+ prebolt_output = output,+ dwp = None,+ external_debug_info = external_debug_info,+ linker_argsfile = linker_argsfile_out,+ linker_command = None, # There is no notion of a single linker command for DistLTO+ index_argsfile = index_argsfile_out,+ ), (lto_outputs.providers | native_link_outputs.providers)
@@ -0,0 +1,108 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//linking:link_info.bzl",+ "append_linkable_args",+)+load(":common_types.bzl", "DThinLTOLinkData", "LinkDataType")++def thin_link(+ ctx: AnalysisContext,+ final_binary_out: Artifact,+ sorted_index_link_data: list[DThinLTOLinkData],+ common_link_flags: cmd_args,+ linker: RunInfo,+ lto_planner: RunInfo,+ post_linker_flags: cmd_args,+ index_argsfile_out: Artifact,+ link_plan_out: Artifact,+ identifier: str | None,+ premerger_enabled: bool,+ use_content_based_output_paths: bool,+ make_cat,+ make_id,+):+ # See comments in dist_lto_planner.py for semantics on the values that are pushed into index_meta.+ index_meta_records = []++ index_cat = make_cat("thin_lto_index")+ index_file_out = ctx.actions.declare_output(make_id(index_cat) + "/index", has_content_based_path = use_content_based_output_paths)+ index_out_dir = cmd_args(index_file_out.as_output(), parent = 1)++ index_args = cmd_args(common_link_flags)+ index_args.add(cmd_args(index_file_out.as_output(), format = "-Wl,--thinlto-index-only={}"))+ index_args.add("-Wl,--thinlto-emit-imports-files")+ index_args.add("-Wl,--thinlto-full-index")++ # By default the linker will write artifacts (import files and sharded indices) next to input bitcode files with+ # a different suffix. This can be problematic if you are running two distributed links on the same machine at the # same time consuming the same input bitcode files. That is the links would overwrite each other's artifacts. This+ # flag allows you to write all these artifacts into a unique directory per link to avoid this problem.+ index_args.add(cmd_args(index_out_dir, format = "-Wl,--thinlto-prefix-replace=;{}/"))++ # buildifier: disable=uninitialized+ for idx, artifact in enumerate(sorted_index_link_data):+ link_data = artifact.link_data++ if artifact.data_type == LinkDataType("eager_bitcode") or artifact.data_type == LinkDataType("lazy_bitcode"):+ if artifact.data_type == LinkDataType("lazy_bitcode") and link_data.archive_start:+ index_args.add("-Wl,--start-lib")++ index_args.add(link_data.input_object_file)++ if artifact.data_type == LinkDataType("lazy_bitcode") and link_data.archive_end:+ index_args.add("-Wl,--end-lib")++ object_file_record = {+ "input_object_file_path": link_data.input_object_file,+ "output_index_shard_file_path": link_data.output_index_shard_file.as_output(),+ "output_plan_file_path": link_data.plan.as_output(),+ "starlark_array_index": idx,+ }+ if premerger_enabled:+ object_file_record["output_premerged_bitcode_file_path"] = link_data.merged_bc.as_output()++ index_meta_records.append(object_file_record)++ elif artifact.data_type == LinkDataType("dynamic_library"):+ append_linkable_args(index_args, link_data.linkable)++ else:+ fail("Unhandled data type: {}".format(str(artifact.data_type)))++ output_as_string = cmd_args(final_binary_out, ignore_artifacts = True)+ index_args.add("-o", output_as_string)+ index_args.add(post_linker_flags)+ index_cmd = cmd_args(linker)+ index_argfile, _ = ctx.actions.write(+ index_argsfile_out.as_output(),+ index_args,+ allow_args = True,+ )+ index_cmd.add(cmd_args(index_argfile, format = "@{}"))++ index_meta_file = ctx.actions.write_json(+ final_binary_out.basename + ".thinlto.meta.json",+ index_meta_records,+ with_inputs = True,+ has_content_based_path = use_content_based_output_paths,+ )++ plan_cmd = cmd_args([lto_planner, "--meta", index_meta_file, "--index", index_out_dir, "--link-plan", link_plan_out.as_output()])+ if premerger_enabled:+ plan_cmd.add("--enable-premerger")+ plan_cmd.add("--", index_cmd)++ plan_cmd.add(+ cmd_args(+ hidden = [+ index_args,+ ]+ )+ )+ ctx.actions.run(plan_cmd, category = index_cat, identifier = identifier)
@@ -0,0 +1,24 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# These records are documented in the dist_lto_planner_darwin.py script and must be kept in sync with those definitions++BitcodeMergeState = enum(+ "STANDALONE",+ "ABSORBED",+ "ROOT",+ "NOT_LOADED",+)++ObjectFileOptimizationPlan = record(+ imports = field(list[int]),+ is_bitcode = field(bool),+ merge_state = field(str | None, None), # BitcodeMergeState+ loaded_by_linker = field(bool),+ final_link_line_position = field(int),+)
@@ -0,0 +1,909 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load(+ "@prelude//:artifact_tset.bzl",+ "make_artifact_tset",+ "project_artifacts",+)+load("@prelude//:paths.bzl", "paths")+load(+ "@prelude//cxx:cxx_bolt.bzl",+ "PRE_BOLT_SUFFIX",+ "bolt",+ "cxx_use_bolt",+)+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")+load(+ "@prelude//cxx:cxx_link_utility.bzl",+ "cxx_link_cmd_parts",+ "gc_sections_args",+ "linker_map_args",+)+load("@prelude//cxx:cxx_toolchain_types.bzl", "LinkerType")+load("@prelude//cxx:debug.bzl", "SplitDebugMode")+load(+ "@prelude//cxx:dwp.bzl",+ "run_dwp_action",+)+load("@prelude//cxx:link_types.bzl", "LinkOptions", "get_dwp_execution_preference")+load("@prelude//linking:execution_preference.bzl", "get_action_execution_attributes")+load(+ "@prelude//linking:link_info.bzl",+ "ArchiveLinkable",+ "FrameworksLinkable",+ "LinkInfo",+ "LinkedObject",+ "ObjectsLinkable",+ "SharedLibLinkable", # @unused Used as a type+ "SwiftmoduleLinkable",+ "append_linkable_args",+ "map_to_link_infos",+ "serialize_linkable_for_thinlto",+ "unpack_external_debug_info",+ "unpack_link_args",+)+load("@prelude//linking:stamp_build_info.bzl", "cxx_stamp_build_info", "stamp_build_info")+load("@prelude//linking:strip.bzl", "strip_object")+load("@prelude//utils:lazy.bzl", "lazy")++# `_BitcodeLinkData` holds data+# that needs to be tracked across ThinLTO phases for Bitcode (LLVM IR) files.+# Bitcode is produced from Phase 1 (compile).+# Tracking data is held to orchestrate between+# Phase 2 (Thin Link) and Phase 3 (ThinLTO Backends).+# Phase 2 (Thin Link) writes a plan for Phase 3 (ThinLTO Backends).+# The plan contains which other bitcode files are needed to perform+# Phase 3.+_BitcodeLinkData = record(+ # `id` is the number that will be used to refer back to this record across the ThinLTO phases.+ id = int,+ name = str,+ initial_object = Artifact,+ bc_file = Artifact,+ plan = Artifact,+ opt_object = Artifact,+ external_debug_info = Artifact | None,+)++# `_ArchiveLinkData` holds data+# that needs to be tracked across ThinLTO phases for Archive (.a) files that contain Bitcode/LLVM IR files.+# See `_BitcodeLinkData` for how this data is used across the Phases.+# `_ArchiveLinkData` is unarchived and tracking for that is held here.+_ArchiveLinkData = record(+ # `id` is the number that will be used to refer back to this record across the ThinLTO phases.+ id = int,+ name = str,+ manifest = Artifact,+ # A file containing paths to artifacts that are known to reside in opt_objects_dir.+ opt_manifest = Artifact,+ objects_dir = Artifact,+ opt_objects_dir = Artifact,+ indexes_dir = Artifact,+ plan = Artifact,+ link_whole = bool,+ prepend = bool,+ # Directory for .dwo files when split_debug_mode is "split".+ dwo_dir = Artifact | None,+)++_DataType = enum(+ "bitcode",+ "archive",+ "cmd_args",+)++# `_LinkDataVariant` is a discriminated union+# that holds the arguments that is feed into the linker and+# tracked throughout the ThinLTO phases.+_LinkDataVariant = record(+ # discriminant/tag field to determine what type of LinkData this is.+ data_type = _DataType,+ # The link_data field has the following invariant:+ # - `list[_BitcodeLinkData]` when data_type is `_DataType("bitcode")`+ # - `_ArchiveLinkData` when data_type is `_DataType("archive")`+ # - `None` when data_type is `_DataType("cmd_args")`+ link_data = list[_BitcodeLinkData] | _ArchiveLinkData | None,+ # The linkable that this is derived from.+ # This field is used to get the `cmd_args` form.+ # FrameworksLinkable / SwiftmoduleLinkable are skipped before a variant is+ # built, so they never appear here.+ origin = ArchiveLinkable | SharedLibLinkable | ObjectsLinkable,+)++# `_ThinLinkInfo` groups together pre/post flags and a list of LinkData.+_ThinLinkInfo = record(+ pre_flags = list,+ post_flags = list,+ link_data_variants = list[_LinkDataVariant],+)++def cxx_gnu_dist_link(+ ctx: AnalysisContext,+ # The destination for the link output.+ output: Artifact,+ opts: LinkOptions,+ linker_map: Artifact | None = None,+ gc_sections_output: Artifact | None = None,+ # This action will only happen if split_dwarf is enabled via the toolchain.+ dwp_tool_available: bool = True,+ executable_link: bool = True,+ build_info_json: Artifact | None = None,+) -> LinkedObject:+ """+ Perform a distributed thin-lto link into the supplied output++ Distributed thinlto splits the link into three stages:+ 1. global "indexing" step+ 2. many individual compilation unit optimization steps+ 3. final global link step++ The 2nd and 3rd of those are done just by constructing compiler/linker commands (in dynamic_output+ sections) using the output of the first.++ For the first, we need to post-process the linker index output to get it into a form+ that is easy for us to consume from within bzl.+ """++ links = opts.links+ binary_links = opts.binary_links++ # A category suffix that will be added to the category of the link action that is generated.+ category_suffix = opts.category_suffix++ # An identifier that will uniquely name this link action in the context of a category. Useful for+ # differentiating multiple link actions in the same rule.+ identifier = opts.identifier++ # Names derived from the identifier below become artifact paths, and callers+ # pass identifiers containing spaces and brackets.+ normalized_identifier = identifier.replace("[", "_").replace("]", "_").replace(" ", "_") if identifier != None else None++ enable_late_build_info_stamping = executable_link and cxx_stamp_build_info(ctx)++ # Unlike the plain link, a `None` (no preference) narrows to `False` here,+ # because this also feeds `bolt` and `strip_object`, which take a plain bool.+ enable_cache_upload = opts.allow_cache_upload or enable_late_build_info_stamping++ link_action_execution_properties = get_action_execution_attributes(opts.link_execution_preference)+ dwp_action_execution_properties = get_action_execution_attributes(get_dwp_execution_preference(opts))+ enable_bolt = executable_link and cxx_use_bolt(ctx)++ def make_cat(c: str) -> str:+ """Used to make sure categories for our actions include the provided suffix"""+ if category_suffix != None:+ return c + "_" + category_suffix+ return c++ def make_id(i: str) -> str:+ """Used to make sure identifiers for our actions include the provided identifier"""+ if normalized_identifier != None:+ return normalized_identifier + "_" + i+ return i++ recorded_outputs = {}++ def name_for_obj(link_name: str, object_artifact: Artifact) -> str:+ """Creates a unique name/path we can use for a particular object file input"""+ prefix = "{}/{}".format(link_name, object_artifact.short_path)++ # it's possible (though unlikely) that we can get duplicate name/short_path, so just uniquify them+ if prefix in recorded_outputs:+ recorded_outputs[prefix] += 1+ extra = recorded_outputs[prefix]+ prefix = "{}-{}".format(prefix, extra)+ else:+ recorded_outputs[prefix] = 1+ return prefix++ names = {}++ def name_for_link(info: LinkInfo) -> str:+ """Creates a unique name for a LinkInfo that we are consuming"""+ name = info.name or "unknown"+ if name not in names:+ names[name] = 1+ else:+ names[name] += 1+ name += "-{}".format(names[name])+ return make_id(name)++ link_infos = map_to_link_infos(links)++ cxx_toolchain = get_cxx_toolchain_info(ctx)+ lto_planner = cxx_toolchain.internal_tools.dist_lto.planner[LinkerType("gnu")]+ lto_opt = cxx_toolchain.internal_tools.dist_lto.opt[LinkerType("gnu")]+ lto_prepare = cxx_toolchain.internal_tools.dist_lto.prepare[LinkerType("gnu")]+ lto_copy = cxx_toolchain.internal_tools.dist_lto.copy+ split_debug_mode = cxx_toolchain.split_debug_mode++ PREPEND_ARCHIVE_NAMES = [+ # T130644072: If linked with `--whole-archive`, Clang builtins must be at the+ # front of the argument list to avoid conflicts with identically-named Rust+ # symbols from the `compiler_builtins` crate.+ #+ # Once linking of C++ binaries starts to use `rlib`s, this may no longer be+ # necessary, because our Rust `rlib`s won't need to contain copies of+ # `compiler_builtins` to begin with, unlike our Rust `.a`s which presently do+ # (T130789782).+ "clang_rt.builtins",+ ]++ # `link_data_repository` is a bridge between the outputs of `dynamic_plan` (Phase 2 Thin Link)+ # and the inputs into `dynamic_optimize` and `dynamic_optimize_archive` (Phase 3 ThinLTO Backends).+ # Note: The index into `link_data_repository` is important as it's how things will appear in+ # the plans produced by indexing. That allows us to map those indexes back to+ # the actual artifacts.+ link_data_repository = [] # type: list[_BitcodeLinkData | _ArchiveLinkData]++ # thin_link_infos contains __ALL__ the arguments used in the Phase 2 Thin link step.+ # It contains LLVM IR bitcode files, machine object files, shared objects, linker flags, etc.+ thin_link_infos = [] # type: list[_ThinLinkInfo]++ # Information used to construct the dynamic plan:+ plan_inputs = [] # type: list[Artifact]+ plan_outputs = [] # type: list[OutputArtifact]++ # Information used to construct the opt dynamic outputs:+ archive_opt_manifests = [] # type: list[Artifact]++ prepare_cat = make_cat("thin_lto_prepare")++ # The `for` loop below reads each `LinkInfo` and transforms it into a `_ThinLinkInfo`.+ # `_ThinLinkInfo` will carry the additional structures used through out the multiple phases of ThinLTO.+ for link in link_infos:+ link_name = name_for_link(link)++ link_data_variants = [] # type: list[_LinkDataVariant]+ for linkable in link.linkables:+ if isinstance(linkable, ObjectsLinkable):+ data_type = _DataType("bitcode")+ link_data = [] # type: list[_BitcodeLinkData]++ for obj in linkable.objects:+ name = name_for_obj(link_name, obj)+ bc_output = ctx.actions.declare_output(name + ".thinlto.bc", has_content_based_path = False)+ plan_output = ctx.actions.declare_output(name + ".opt.plan", has_content_based_path = False)+ opt_output = ctx.actions.declare_output(name + ".opt.o", has_content_based_path = False)+ external_debug_info = None+ if split_debug_mode == SplitDebugMode("split"):+ external_debug_info = ctx.actions.declare_output(name + ".opt.dwo", has_content_based_path = False)+ elif split_debug_mode == SplitDebugMode("single"):+ external_debug_info = opt_output++ bitcode_link_data = _BitcodeLinkData(+ id = len(link_data_repository),+ name = name,+ initial_object = obj,+ bc_file = bc_output,+ plan = plan_output,+ opt_object = opt_output,+ external_debug_info = external_debug_info,+ )+ link_data_repository.append(bitcode_link_data)+ link_data.append(bitcode_link_data)+ plan_outputs.extend([bc_output.as_output(), plan_output.as_output()])+ elif isinstance(linkable, ArchiveLinkable) and linkable.supports_lto:+ data_type = _DataType("archive")+ # Our implementation of Distributed ThinLTO operates on individual objects, not archives. Since these+ # archives might still contain LTO-able bitcode, we first extract the objects within the archive into+ # another directory and write a "manifest" containing the list of objects that the archive contained.+ #+ # Later actions in the LTO compilation pipeline will read this manifest and dynamically dispatch+ # actions on the objects that the manifest reports.++ name = name_for_obj(link_name, linkable.archive.artifact)+ archive_manifest = ctx.actions.declare_output("%s/%s/manifest.json" % (prepare_cat, name), has_content_based_path = False)+ archive_objects = ctx.actions.declare_output("%s/%s/objects" % (prepare_cat, name), dir = True, has_content_based_path = False)+ archive_opt_objects = ctx.actions.declare_output("%s/%s/opt_objects" % (prepare_cat, name), dir = True, has_content_based_path = False)+ archive_indexes = ctx.actions.declare_output("%s/%s/indexes" % (prepare_cat, name), dir = True, has_content_based_path = False)+ archive_plan = ctx.actions.declare_output("%s/%s/plan.json" % (prepare_cat, name), has_content_based_path = False)+ archive_opt_manifest = ctx.actions.declare_output("%s/%s/opt_objects.manifest" % (prepare_cat, name), has_content_based_path = False)+ archive_dwo_dir = None+ if split_debug_mode == SplitDebugMode("split"):+ archive_dwo_dir = ctx.actions.declare_output("%s/%s/dwo" % (prepare_cat, name), dir = True, has_content_based_path = False)+ prepare_args = cmd_args([+ lto_prepare,+ "--manifest-out",+ archive_manifest.as_output(),+ "--objects-out",+ archive_objects.as_output(),+ "--ar",+ cxx_toolchain.linker_info.archiver,+ "--archive",+ linkable.archive.artifact,+ "--name",+ name,+ ])+ ctx.actions.run(prepare_args, category = make_cat("thin_lto_prepare"), identifier = name)++ link_data = _ArchiveLinkData(+ id = len(link_data_repository),+ name = name,+ manifest = archive_manifest,+ opt_manifest = archive_opt_manifest,+ objects_dir = archive_objects,+ opt_objects_dir = archive_opt_objects,+ indexes_dir = archive_indexes,+ plan = archive_plan,+ link_whole = linkable.link_whole,+ prepend = link_name in PREPEND_ARCHIVE_NAMES,+ dwo_dir = archive_dwo_dir,+ )+ link_data_repository.append(link_data)+ archive_opt_manifests.append(archive_opt_manifest)+ plan_inputs.extend([archive_manifest, archive_objects])+ plan_outputs.extend([archive_indexes.as_output(), archive_plan.as_output()])+ elif isinstance(linkable, FrameworksLinkable) or isinstance(linkable, SwiftmoduleLinkable):+ # These add no linker inputs on GNU: append_linkable_args no-ops them+ # and serialize_linkable_for_thinlto rejects them, so there is nothing+ # to emit here (the Darwin planner skips them likewise). Use `continue`,+ # not `pass`: link_data_variants is appended below the if/elif/else, so+ # falling through would emit a variant from the previous linkable.+ continue+ else:+ data_type = _DataType("cmd_args")+ link_data = None++ link_data_variants.append(+ _LinkDataVariant(+ data_type = data_type,+ link_data = link_data,+ origin = linkable,+ )+ )++ thin_link_infos.append(+ _ThinLinkInfo(+ pre_flags = link.pre_flags,+ post_flags = link.post_flags,+ link_data_variants = link_data_variants,+ )+ )++ index_argsfile_out = ctx.actions.declare_output(output.short_path + ".thinlto_index_argsfile", has_content_based_path = False)+ final_link_index = ctx.actions.declare_output(output.short_path + ".final_link_index", has_content_based_path = False)++ def dynamic_plan(+ link_plan: Artifact,+ index_argsfile_out: Artifact,+ final_link_index: Artifact,+ ) -> None:+ def plan(ctx: AnalysisContext, artifacts, outputs):+ # index link command args+ prepend_index_args = cmd_args()+ index_args = cmd_args()++ # index_meta is the comprehensive source-of-truth for Phase 2 Thin Link.+ # It holds the record of all the flags, linkable files, and their associated data.+ # See comments in dist_lto_planner.py for semantics on the values that are pushed into index_meta.+ index_meta = []++ # buildifier: disable=uninitialized+ for thin_link_info in thin_link_infos:+ metadata_entry = {+ "linkables": [],+ "post_flags": thin_link_info.post_flags,+ "pre_flags": thin_link_info.pre_flags,+ }+ index_meta.append(metadata_entry)++ if thin_link_info.pre_flags:+ index_args.add(thin_link_info.pre_flags)++ for link_data_variant in thin_link_info.link_data_variants:+ if link_data_variant.data_type == _DataType("bitcode"):+ append_linkable_args(index_args, link_data_variant.origin)++ for link_data in link_data_variant.link_data:+ metadata_linkable = {+ "idx": link_data.id,+ "output": outputs[link_data.bc_file].as_output(),+ "path": link_data.initial_object,+ "plan_output": outputs[link_data.plan].as_output(),+ "type": "bitcode",+ }+ metadata_entry["linkables"].append(metadata_linkable)++ elif link_data_variant.data_type == _DataType("archive"):+ link_data = link_data_variant.link_data+ manifest = artifacts[link_data.manifest].read_json()++ metadata_linkable = {+ "archive_idx": link_data.id,+ "archive_index_dir": outputs[link_data.indexes_dir].as_output(),+ "archive_name": link_data.name,+ # `opt_objects_dir` is produced downstream of this plan, so it+ # can only be passed as a path: `ignore_artifacts` keeps it out+ # of the meta file's inputs, and `delimiter` makes it serialize+ # as a string rather than a single-element list.+ "archive_opt_objects_dir": cmd_args(link_data.opt_objects_dir, delimiter = "", ignore_artifacts = True),+ "archive_plan": outputs[link_data.plan].as_output(),+ "objects": [] if manifest["objects"] else None,+ "prepend": link_data.prepend,+ "type": "archive",+ }+ metadata_entry["linkables"].append(metadata_linkable)++ if not manifest["objects"]:+ # Despite not having any objects (and thus not needing a plan), we still need to bind the plan output.+ ctx.actions.write(outputs[link_data.plan].as_output(), "{}")+ cmd = cmd_args(["/bin/sh", "-c", "mkdir", "-p", outputs[link_data.indexes_dir].as_output()])+ ctx.actions.run(cmd, category = make_cat("thin_lto_mkdir"), identifier = link_data.name)+ continue++ archive_args = prepend_index_args if link_data.prepend else index_args++ archive_args.add(cmd_args(hidden = link_data.objects_dir))++ if not link_data.link_whole:+ archive_args.add("-Wl,--start-lib")++ for obj in manifest["objects"]:+ metadata_linkable["objects"].append({+ "idx": link_data.id,+ "output": "",+ "path": obj,+ "plan_output": "",+ })+ archive_args.add(obj)++ if not link_data.link_whole:+ archive_args.add("-Wl,--end-lib")+ elif link_data_variant.data_type == _DataType("cmd_args"):+ linkable_args = cmd_args()+ append_linkable_args(linkable_args, link_data_variant.origin)+ index_args.add(linkable_args)++ metadata_linkable = {+ "cmd_args": linkable_args,+ "object": serialize_linkable_for_thinlto(link_data_variant.origin),+ "type": "cmd_args",+ }+ metadata_entry["linkables"].append(metadata_linkable)+ else:+ fail("Unknown data type:", link_data_variant)++ if thin_link_info.post_flags:+ index_args.add(thin_link_info.post_flags)++ prepend_index_args.add(index_args)+ index_argfile, _ = ctx.actions.write(+ outputs[index_argsfile_out].as_output(),+ prepend_index_args,+ allow_args = True,+ )++ index_cat = make_cat("thin_lto_index")+ index_file_out = ctx.actions.declare_output(make_id(index_cat) + "/index", has_content_based_path = False)+ index_out_dir = cmd_args(index_file_out.as_output(), parent = 1)++ index_cmd_parts = cxx_link_cmd_parts(cxx_toolchain, executable_link)++ index_cmd = index_cmd_parts.link_cmd+ index_cmd.add(cmd_args(index_argfile, format = "@{}", hidden = prepend_index_args))++ # Binary-only link flags (e.g. --wrap) must be present at the index+ # step so symbol resolution matches the final link. They are+ # intentionally omitted from the per-object opt actions so those+ # actions stay identical across links and can be deduplicated.+ for link in binary_links:+ index_cmd.add(unpack_link_args(link))++ output_as_string = cmd_args(output, ignore_artifacts = True)+ index_cmd.add("-o", output_as_string)+ index_cmd.add(cmd_args(index_file_out.as_output(), format = "-Wl,--thinlto-index-only={}"))+ index_cmd.add("-Wl,--thinlto-emit-imports-files")+ index_cmd.add("-Wl,--thinlto-full-index")+ index_cmd.add(cmd_args(index_out_dir, format = "-Wl,--thinlto-prefix-replace=;{}/"))+ index_cmd.add(index_cmd_parts.post_linker_flags)++ index_meta_file = ctx.actions.write_json(+ output.short_path + ".thinlto.meta.json",+ index_meta,+ with_inputs = True,+ has_content_based_path = False,+ )++ plan_cmd = cmd_args(+ [+ lto_planner,+ "--meta",+ index_meta_file,+ "--index",+ index_out_dir,+ "--link-plan",+ outputs[link_plan].as_output(),+ "--final-link-index",+ outputs[final_link_index].as_output(),+ "--",+ ],+ )+ plan_cmd.add(index_cmd)++ ctx.actions.run(+ plan_cmd,+ category = index_cat,+ identifier = identifier,+ prefer_local = link_action_execution_properties.prefer_local,+ prefer_remote = link_action_execution_properties.prefer_remote,+ local_only = link_action_execution_properties.local_only,+ weight = opts.link_weight,+ force_full_hybrid_if_capable = link_action_execution_properties.full_hybrid,+ )++ # TODO(T117513091) - dynamic_output does not allow for an empty list of dynamic inputs. If we have no archives+ # to process, we will have no dynamic inputs, and the plan action can be non-dynamic.+ #+ # However, buck2 disallows `dynamic_output` with a empty input list. We also can't call our `plan` function+ # directly, since it uses `ctx.outputs` to bind its outputs. Instead of doing Starlark hacks to work around+ # the lack of `ctx.outputs`, we declare an empty file as a dynamic input.+ plan_inputs.append(ctx.actions.write(output.short_path + ".plan_hack.txt", "", has_content_based_path = False))+ plan_outputs.extend([+ link_plan.as_output(),+ index_argsfile_out.as_output(),+ final_link_index.as_output(),+ ])+ ctx.actions.dynamic_output(dynamic = plan_inputs, inputs = [], outputs = plan_outputs, f = plan)++ link_plan_out = ctx.actions.declare_output(output.short_path + ".link-plan.json", has_content_based_path = False)+ dynamic_plan(+ link_plan = link_plan_out,+ index_argsfile_out = index_argsfile_out,+ final_link_index = final_link_index,+ )++ def prepare_opt_flags(link_infos: list[LinkInfo]) -> cmd_args:+ opt_cmd_parts = cxx_link_cmd_parts(cxx_toolchain, executable_link)+ opt_args = opt_cmd_parts.link_cmd++ if cxx_toolchain.linker_info.dist_thin_lto_codegen_flags != None:+ opt_args.add(cxx_toolchain.linker_info.dist_thin_lto_codegen_flags)++ # buildifier: disable=uninitialized+ for link in link_infos:+ for raw_flag in link.pre_flags + link.post_flags:+ opt_args.add(raw_flag)+ opt_args.add(link.dist_thin_lto_codegen_flags)++ opt_args.add(opt_cmd_parts.post_linker_flags)+ return opt_args++ opt_common_flags = prepare_opt_flags(link_infos)++ # Create an argsfile and dump all the flags to be processed later by lto_opt.+ # These flags are common to all opt actions, we don't need an argfile for each action, one+ # for the entire link unit will do.+ opt_argsfile = ctx.actions.declare_output(output.short_path + ".lto_opt_argsfile", has_content_based_path = False)+ ctx.actions.write(opt_argsfile.as_output(), opt_common_flags, allow_args = True)++ # We declare a separate dynamic_output for every object file. It would+ # maybe be simpler to have a single dynamic_output that produced all the+ # opt actions, but an action needs to re-run whenever the analysis that+ # produced it re-runs. And so, with a single dynamic_output, we'd need to+ # re-run all actions when any of the plans changed.+ def dynamic_optimize(name: str, initial_object: Artifact, bc_file: Artifact, plan: Artifact, opt_object: Artifact, external_debug_info: Artifact | None):+ def optimize_object(ctx: AnalysisContext, artifacts, outputs):+ plan_json = artifacts[plan].read_json()++ # If the object was not compiled with thinlto flags, then there+ # won't be valid outputs for it from the indexing, but we still+ # need to bind the artifact.+ if not plan_json["is_bc"]:+ ctx.actions.write(outputs[opt_object], "")+ if external_debug_info != None and external_debug_info != opt_object:+ ctx.actions.write(outputs[external_debug_info], "")+ return++ opt_cmd = cmd_args(lto_opt)+ opt_cmd.add("--out", outputs[opt_object].as_output())+ opt_cmd.add("--input", initial_object)+ opt_cmd.add("--index", bc_file)++ # When invoking opt and llc via clang, clang will not respect IR metadata to generate+ # dwo files unless -gsplit-dwarf is explicitly passed in. In other words, even if+ # 'splitDebugFilename' set in IR 'DICompileUnit', we still need to force clang to tell+ # llc to generate dwo sections.+ #+ # Local thinlto generates .dwo files by default. For distributed thinlto, however, we+ # want to keep all dwo debug info in the object file to reduce the number of files to+ # materialize.+ if split_debug_mode == SplitDebugMode("none"):+ opt_cmd.add("--split-dwarf=none")+ elif split_debug_mode == SplitDebugMode("single"):+ opt_cmd.add("--split-dwarf=single")+ elif split_debug_mode == SplitDebugMode("split"):+ opt_cmd.add("--split-dwarf=split")+ opt_cmd.add("--dwo", outputs[external_debug_info].as_output())++ opt_cmd.add(cmd_args(hidden = opt_common_flags))+ opt_cmd.add("--args", opt_argsfile)++ opt_cmd.add("--")+ opt_cmd.add(cxx_toolchain.cxx_compiler_info.compiler)++ imports = [link_data_repository[idx].initial_object for idx in plan_json["imports"]]+ archives = [link_data_repository[idx].objects_dir for idx in plan_json["archive_imports"]]+ opt_cmd.add(cmd_args(hidden = imports + archives))+ ctx.actions.run(opt_cmd, category = make_cat("thin_lto_opt_object"), identifier = name)++ outputs = [opt_object.as_output()]+ if external_debug_info != None:+ outputs.append(external_debug_info.as_output())+ ctx.actions.dynamic_output(dynamic = [plan], inputs = [], outputs = outputs, f = optimize_object)++ def dynamic_optimize_archive(archive: _ArchiveLinkData):+ def optimize_archive(ctx: AnalysisContext, artifacts, outputs):+ plan_json = artifacts[archive.plan].read_json()+ if "objects" not in plan_json or not plan_json["objects"] or lazy.is_all(lambda e: not e["is_bc"], plan_json["objects"]):+ # Nothing in this directory was lto-able; let's just copy the archive.+ # `opt_objects_dir` is the only dir of an lto-able archive that the final+ # link materializes, and it must hold every member at the member's path+ # relative to the archive's base dir -- the layout the per-member branch+ # below builds, and the one the planner derives final-link paths from.+ ctx.actions.copied_dir(outputs[archive.opt_objects_dir], {"objects": archive.objects_dir})+ ctx.actions.write(outputs[archive.opt_manifest], "")+ if archive.dwo_dir != None:+ ctx.actions.symlinked_dir(outputs[archive.dwo_dir], {})+ return++ output_dir = {}+ output_manifest = cmd_args()+ dwo_dir = {}+ for entry in plan_json["objects"]:+ base_dir = plan_json["base_dir"]+ source_path = paths.relativize(entry["path"], base_dir)+ if not entry["is_bc"]:+ opt_object = ctx.actions.declare_output("%s/%s" % (make_cat("thin_lto_opt_copy"), source_path), has_content_based_path = False)+ output_manifest.add(opt_object)+ copy_cmd = cmd_args(+ [+ lto_copy,+ "--to",+ opt_object.as_output(),+ "--from",+ entry["path"],+ ],+ hidden = archive.objects_dir,+ )+ ctx.actions.run(copy_cmd, category = make_cat("thin_lto_opt_copy"), identifier = source_path)+ output_dir[source_path] = opt_object+ continue++ opt_object = ctx.actions.declare_output("%s/%s" % (make_cat("thin_lto_opt_archive"), source_path), has_content_based_path = False)+ output_manifest.add(opt_object)+ output_dir[source_path] = opt_object++ opt_cmd = cmd_args(lto_opt)+ opt_cmd.add("--out", opt_object.as_output())+ opt_cmd.add("--input", entry["path"])+ opt_cmd.add("--index", entry["bitcode_file"])++ if split_debug_mode == SplitDebugMode("none"):+ opt_cmd.add("--split-dwarf=none")+ elif split_debug_mode == SplitDebugMode("single"):+ opt_cmd.add("--split-dwarf=single")+ elif split_debug_mode == SplitDebugMode("split"):+ opt_cmd.add("--split-dwarf=split")+ dwo_path = source_path.removesuffix(".o") + ".dwo"+ dwo_output = ctx.actions.declare_output("%s/%s" % (make_cat("thin_lto_opt_archive"), dwo_path), has_content_based_path = False)+ dwo_dir[dwo_path] = dwo_output+ opt_cmd.add("--dwo", dwo_output.as_output())++ opt_cmd.add(cmd_args(hidden = opt_common_flags))+ opt_cmd.add("--args", opt_argsfile)++ opt_cmd.add("--")+ opt_cmd.add(cxx_toolchain.cxx_compiler_info.compiler)++ imports = [link_data_repository[idx].initial_object for idx in entry["imports"]]+ archives = [link_data_repository[idx].objects_dir for idx in entry["archive_imports"]]+ opt_cmd.add(+ cmd_args(+ hidden = imports + archives + [archive.indexes_dir, archive.objects_dir],+ )+ )+ ctx.actions.run(opt_cmd, category = make_cat("thin_lto_opt_archive"), identifier = source_path)++ ctx.actions.symlinked_dir(outputs[archive.opt_objects_dir], output_dir)+ ctx.actions.write(outputs[archive.opt_manifest], output_manifest, allow_args = True)+ if archive.dwo_dir != None:+ ctx.actions.symlinked_dir(outputs[archive.dwo_dir], dwo_dir)++ archive_opt_inputs = [archive.plan]+ archive_opt_outputs = [archive.opt_objects_dir.as_output(), archive.opt_manifest.as_output()]+ if archive.dwo_dir != None:+ archive_opt_outputs.append(archive.dwo_dir.as_output())+ ctx.actions.dynamic_output(dynamic = archive_opt_inputs, inputs = [], outputs = archive_opt_outputs, f = optimize_archive)++ objects_external_debug_info = []+ for link_data in link_data_repository:+ if isinstance(link_data, _BitcodeLinkData):+ external_debug_info = link_data.external_debug_info+ dynamic_optimize(+ name = link_data.name,+ initial_object = link_data.initial_object,+ bc_file = link_data.bc_file,+ plan = link_data.plan,+ opt_object = link_data.opt_object,+ external_debug_info = link_data.external_debug_info,+ )++ if external_debug_info != None:+ objects_external_debug_info.append(external_debug_info)+ elif isinstance(link_data, _ArchiveLinkData):+ dynamic_optimize_archive(link_data)++ # For split mode, add the dwo directory to external_debug_info.+ # For single mode, the debug info is embedded in the opt_objects.+ if split_debug_mode == SplitDebugMode("split") and link_data.dwo_dir != None:+ objects_external_debug_info.append(link_data.dwo_dir)+ elif split_debug_mode == SplitDebugMode("single"):+ objects_external_debug_info.append(link_data.opt_objects_dir)++ def thin_lto_final_link(ctx: AnalysisContext, artifacts, outputs):+ plan = artifacts[link_plan_out].read_json()+ plan_index = {int(k): v for k, v in plan["index"].items()}++ # non_lto_objects are the ones that weren't compiled with thinlto+ # flags. In that case, we need to link against the original object.+ non_lto_objects = {int(k): 1 for k in plan["non_lto_objects"]}+ current_index = 0+ link_cmd_hidden = cmd_args()+ for link in link_infos:+ for linkable in link.linkables:+ if isinstance(linkable, ObjectsLinkable):+ for obj in linkable.objects:+ if current_index in plan_index:+ link_cmd_hidden.add(link_data_repository[current_index].opt_object)+ elif current_index in non_lto_objects:+ link_cmd_hidden.add(obj)+ current_index += 1+ elif isinstance(linkable, ArchiveLinkable) and linkable.supports_lto:+ current_index += 1+ else:+ append_linkable_args(link_cmd_hidden, linkable)++ # pre/post flags may reference artifacts (e.g. linker scripts via+ # `-Wl,--script=path`).+ link_cmd_hidden.add(link.pre_flags)+ link_cmd_hidden.add(link.post_flags)++ link_cmd_parts = cxx_link_cmd_parts(cxx_toolchain, executable_link)+ link_cmd = link_cmd_parts.link_cmd++ # buildifier: disable=uninitialized+ for link_data in link_data_repository:+ if isinstance(link_data, _ArchiveLinkData):+ link_cmd_hidden.add(link_data.opt_objects_dir)++ link_cmd.add(cmd_args(final_link_index, format = "@{}", hidden = link_cmd_hidden))+ for link in binary_links:+ link_cmd.add(unpack_link_args(link))+ link_cmd.add("-o", outputs[output].as_output())+ if linker_map:+ link_cmd.add(linker_map_args(cxx_toolchain, outputs[linker_map].as_output()).flags)+ if gc_sections_output:+ link_cmd.add(gc_sections_args(cxx_toolchain, outputs[gc_sections_output].as_output()).flags)+ link_cmd.add(link_cmd_parts.post_linker_flags)++ ctx.actions.run(+ link_cmd,+ category = make_cat("thin_lto_link"),+ identifier = identifier,+ prefer_local = link_action_execution_properties.prefer_local,+ prefer_remote = link_action_execution_properties.prefer_remote,+ local_only = link_action_execution_properties.local_only,+ weight = opts.link_weight,+ force_full_hybrid_if_capable = link_action_execution_properties.full_hybrid,+ allow_cache_upload = enable_cache_upload,+ )++ final_link_inputs = [link_plan_out, final_link_index] + archive_opt_manifests+ ctx.actions.dynamic_output(+ dynamic = final_link_inputs,+ inputs = [],+ outputs = [output.as_output()] + ([linker_map.as_output()] if linker_map else []) + ([gc_sections_output.as_output()] if gc_sections_output else []),+ f = thin_lto_final_link,+ )++ external_debug_info = make_artifact_tset(+ label = ctx.label,+ actions = ctx.actions,+ artifacts = objects_external_debug_info,+ children = [unpack_external_debug_info(ctx.actions, link_args) for link_args in links],+ )++ if enable_bolt:+ bolt_output = bolt(ctx, output, external_debug_info, identifier, dwp_tool_available, allow_cache_upload = enable_cache_upload)+ final_output = bolt_output.output+ split_debug_output = bolt_output.dwo_output+ else:+ final_output = output+ split_debug_output = None++ if dwp_tool_available:+ dwp_output = ctx.actions.declare_output(output.short_path.removesuffix(PRE_BOLT_SUFFIX) + ".dwp", has_content_based_path = False)++ def dynamic_run_dwp_action(ctx: AnalysisContext, artifacts, outputs):+ plan = artifacts[link_plan_out].read_json()+ plan_index = {int(k): v for k, v in plan["index"].items()}+ non_lto_objects = {int(k): 1 for k in plan["non_lto_objects"]}++ referenced_objects = list(final_link_inputs)++ # Include hidden dependencies for the final link.+ for idx, link_data in enumerate(link_data_repository):+ if isinstance(link_data, _BitcodeLinkData):+ if idx in plan_index:+ referenced_objects.append(link_data.opt_object)+ elif idx in non_lto_objects:+ referenced_objects.append(link_data.initial_object)+ elif isinstance(link_data, _ArchiveLinkData):+ referenced_objects.append(link_data.opt_objects_dir)+ if link_data.dwo_dir != None:+ referenced_objects.append(link_data.dwo_dir)+ else:+ fail("Unexpected link_data type", link_data)++ if split_debug_output:+ referenced_objects += [split_debug_output]+ else:+ referenced_objects += project_artifacts(ctx.actions, external_debug_info)++ run_dwp_action(+ ctx = ctx,+ toolchain = cxx_toolchain,+ obj = final_output,+ identifier = identifier,+ category_suffix = category_suffix,+ referenced_objects = referenced_objects,+ dwp_output = outputs[dwp_output],+ # Mirror the link action's execution preference so dwp runs+ # alongside the link (avoids round-tripping dwo files when link+ # is local) -- unless the caller asked for dwp to be scheduled+ # separately, e.g. because the link is only local for+ # build-info stamping.+ action_execution_properties = dwp_action_execution_properties,+ )++ ctx.actions.dynamic_output(+ dynamic = [link_plan_out],+ inputs = [],+ outputs = [dwp_output.as_output()],+ f = dynamic_run_dwp_action,+ )+ else:+ dwp_output = None++ unstripped_output = final_output+ if opts.strip:+ strip_args = opts.strip_args_factory(ctx) if opts.strip_args_factory else cmd_args()+ final_output = strip_object(ctx, cxx_toolchain, final_output, strip_args, category_suffix, allow_cache_upload = enable_cache_upload)++ final_output = (+ stamp_build_info(+ ctx,+ final_output,+ links = opts.links,+ build_info_json = build_info_json,+ )+ if executable_link+ else final_output+ )++ return LinkedObject(+ output = final_output,+ unstripped_output = unstripped_output,+ prebolt_output = output,+ dwp = dwp_output,+ external_debug_info = external_debug_info,+ linker_argsfile = final_link_index,+ linker_command = None, # There is no notion of a single linker command for DistLTO+ index_argsfile = index_argsfile_out,+ )
@@ -0,0 +1,55 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//cxx:cxx_toolchain_types.bzl", "DistLtoToolsInfo", "LinkerType")++def _impl(ctx):+ return [+ DefaultInfo(),+ DistLtoToolsInfo(+ compiler_stats_merger = ctx.attrs.compiler_stats_merger[RunInfo],+ planner = {LinkerType(linker_type): planner[RunInfo] for linker_type, planner in ctx.attrs.planner.items()},+ opt = {LinkerType(linker_type): opt[RunInfo] for linker_type, opt in ctx.attrs.opt.items()},+ prepare = {LinkerType(linker_type): prepare[RunInfo] for linker_type, prepare in ctx.attrs.prepare.items()},+ copy = ctx.attrs.copy[RunInfo],+ archive_mapper = ctx.attrs.archive_mapper[RunInfo],+ ),+ ]++dist_lto_tools = rule(+ impl = _impl,+ attrs = {+ "archive_mapper": attrs.dep(providers = [RunInfo], default = "prelude//cxx/dist_lto/tools:dist_lto_archive_mapper"),+ "compiler_stats_merger": attrs.dep(providers = [RunInfo], default = "prelude//cxx/dist_lto/tools:dist_lto_compiler_stats_merger"),+ "copy": attrs.dep(providers = [RunInfo], default = "prelude//cxx/dist_lto/tools:dist_lto_copy"),+ "opt": attrs.dict(+ key = attrs.enum(LinkerType.values()),+ value = attrs.dep(providers = [RunInfo]),+ default = {+ "darwin": "prelude//cxx/dist_lto/tools:dist_lto_opt_darwin",+ "gnu": "prelude//cxx/dist_lto/tools:dist_lto_opt_gnu",+ },+ ),+ "planner": attrs.dict(+ key = attrs.enum(LinkerType.values()),+ value = attrs.dep(providers = [RunInfo]),+ default = {+ "darwin": "prelude//cxx/dist_lto/tools:dist_lto_planner_darwin",+ "gnu": "prelude//cxx/dist_lto/tools:dist_lto_planner_gnu",+ },+ ),+ "prepare": attrs.dict(+ key = attrs.enum(LinkerType.values()),+ value = attrs.dep(providers = [RunInfo]),+ default = {+ "darwin": "prelude//cxx/dist_lto/tools:dist_lto_prepare_darwin",+ "gnu": "prelude//cxx/dist_lto/tools:dist_lto_prepare_gnu",+ },+ ),+ },+)
@@ -0,0 +1,75 @@+load("@prelude//cxx/dist_lto:tools.bzl", "dist_lto_tools")+load("@prelude//utils:source_listing.bzl", "source_listing")++oncall("build_infra")++source_listing()++prelude = native++prelude.python_bootstrap_binary(+ name = "dist_lto_planner_gnu",+ main = "dist_lto_planner_gnu.py",+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "dist_lto_planner_darwin",+ main = "dist_lto_planner_darwin.py",+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "dist_lto_opt_gnu",+ main = "dist_lto_opt_gnu.py",+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "dist_lto_opt_darwin",+ main = "dist_lto_opt_darwin.py",+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "dist_lto_prepare_gnu",+ main = "dist_lto_prepare_gnu.py",+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "dist_lto_prepare_darwin",+ main = "dist_lto_prepare_darwin.py",+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "dist_lto_copy",+ main = "dist_lto_copy.py",+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "dist_lto_archive_mapper",+ main = "dist_lto_archive_mapper.py",+ visibility = ["PUBLIC"],+)++prelude.python_bootstrap_binary(+ name = "dist_lto_compiler_stats_merger",+ main = "dist_lto_compiler_stats_merger.py",+ visibility = ["PUBLIC"],+)++dist_lto_tools(+ name = "dist_lto_tools",+ visibility = ["PUBLIC"],+)++prelude.python_test(+ name = "test_dist_lto_opt",+ srcs = [+ "dist_lto_opt_gnu.py",+ "tests/test_dist_lto_opt.py",+ ],+)
@@ -0,0 +1,54 @@+#!/usr/bin/env python3+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+This script is used to transform an opaque directory Buck artifact filled with+files into a number of Buck artifacts that can each be operated on individually.++This script is used to take a directory filled with object files created+through dynamic_output and a list of name, output destination path pairs.+For each such pair, we look for a file in the directory matching the name,+and copy it to the destination path.++This allows buck to declare and operate on each file individually, rather than+the entire opaque directory.+"""++import argparse+import pathlib+import shutil+import sys++EXIT_SUCCESS = 0+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--objects_dir")+ parser.add_argument("--object_to_map", nargs=2, action="append")+ args = parser.parse_args(argv[1:])++ copy_map = {}+ for object_mapping in args.object_to_map:+ directory_member_name = object_mapping[0]+ dest = object_mapping[1]+ copy_map[directory_member_name] = pathlib.Path(dest)++ directory_to_map = pathlib.Path(args.objects_dir)+ for file in directory_to_map.iterdir():+ if file.name in copy_map:+ shutil.copy(file, copy_map[file.name])+ else:+ raise Exception("Object mapping is missing a file.")++ return EXIT_SUCCESS+++if __name__ == "__main__":+ sys.exit(main(sys.argv))
@@ -0,0 +1,47 @@+#!/usr/bin/env python3+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.+++import argparse+import json+import sys++"""+A helper script designed to merge multiple JSON files storing LLVM stats produced by -stats -stats-json -info-out-file=. All stats are summed together, to form a new JSON file.+"""+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument(+ "--input-stats-filelist",+ help="A filelist of JSON static files produced by LLVM's -stats -stats-json",+ )+ parser.add_argument(+ "--output-stats-file", help="A path to write the merged JSON static file to."+ )+ args = parser.parse_args(argv[1:])+ merged_stats: dict[int, str] = {}+ with open(args.input_stats_filelist) as stats_filelist:+ for stats_file in stats_filelist:+ with open(stats_file.strip()) as f:+ stats = json.load(f)+ for key, value in stats.items():+ if key in merged_stats:+ merged_stats[key] += value+ else:+ merged_stats[key] = value++ with open(args.output_stats_file, "w") as f:+ json.dump(merged_stats, f, sort_keys=True, indent=4)+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv))
@@ -0,0 +1,26 @@+#!/usr/bin/env python3+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import argparse+import shutil+import sys+from typing import List+++def main(argv: List[str]) -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--to")+ parser.add_argument("--from", dest="from_")+ args = parser.parse_args(argv[1:])+ shutil.copy(args.from_, args.to)+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv))
@@ -0,0 +1,124 @@+#!/usr/bin/env python3+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Python wrapper around Clang intended to optimize and codegen bitcode files+to native object files for distributed thin lto targeting darwin. This script+exists to work around Clang bugs where Clang will fail silently.+"""++import argparse+import os+import subprocess+import sys+import traceback+from typing import List++EXIT_SUCCESS, EXIT_FAILURE = 0, 1+++def main(argv: List[str]) -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--out", help="The output native object file.", required=True)+ parser.add_argument("--input", help="The input bitcode object file.", required=True)+ parser.add_argument("--index", help="The thinlto index file.", required=True)+ parser.add_argument(+ "--compiler", help="The path to the Clang compiler binary.", required=True+ )+ parser.add_argument(+ "--shared-args",+ help="The argsfile containing unfiltered and unprocessed flags, common to all opt actions in this link.",+ required=True,+ )+ parser.add_argument(+ "--extra-outputs-args",+ help="The argsfile containing unfiltered and unprocessed flags, specifying extra outputs produced by this opt action.",+ )+ parser.add_argument(+ "--print-command",+ action="store_true",+ help="Print the clang invocation and exit.",+ )+ parser.add_argument(+ "--generate-cgdata",+ help="Save cgdata to special section in produced object file",+ action="store_true",+ )+ parser.add_argument("--read-cgdata", help="Read cgdata from the provided file")+ parser.add_argument(+ "--save-precodegen-ir",+ help="Save optimized pre-codegen IR to the specified path",+ )+ parser.add_argument(+ "--codegen-only",+ action="store_true",+ help="Skip IR optimization passes (input is already optimized pre-codegen IR)",+ )+ parser.add_argument("additional_opt_args", nargs=argparse.REMAINDER)+ args = parser.parse_args(argv[1:])++ clang_invocation = [+ args.compiler,+ f"@{args.shared_args}",+ "-o",+ args.out,+ "-x",+ "ir", # Without this the input file type is incorrectly inferred.+ "-c",+ args.input,+ # When lto_mode=thin/full all compile actions are passed `-flto=thin/full`. We+ # want to generate a native object file here.+ "-fno-lto",+ "-Werror=unused-command-line-argument",+ f"-fthinlto-index={args.index}",+ ]++ if args.codegen_only:+ clang_invocation.append("-fthinlto-codegen-only")++ if args.save_precodegen_ir:+ clang_invocation.append(f"-save-precodegen-ir={args.save_precodegen_ir}")++ clang_invocation += args.additional_opt_args[1:]++ if args.generate_cgdata:+ clang_invocation.extend(["-mllvm", "-codegen-data-generate"])++ if args.read_cgdata:+ clang_invocation.append(f"-fcodegen-data-use={args.read_cgdata}")++ if args.print_command:+ print(" ".join(clang_invocation))+ return EXIT_SUCCESS++ result = subprocess.run(+ clang_invocation,+ capture_output=True,+ text=True,+ )+ if result.returncode:+ print(result.stderr, file=sys.stderr)+ return result.returncode++ # Work around Clang bug where it fails silently: T187767815+ if os.stat(args.out).st_size == 0:+ print("error: clang produced empty file", file=sys.stderr)+ return EXIT_FAILURE+ if args.save_precodegen_ir and os.stat(args.save_precodegen_ir).st_size == 0:+ print("error: clang produced empty precodegen IR file", file=sys.stderr)+ return EXIT_FAILURE+ return EXIT_SUCCESS+++if __name__ == "__main__":+ try:+ sys.exit(main(sys.argv))+ except subprocess.CalledProcessError as e:+ traceback.print_exc()+ sys.exit(e.returncode)
@@ -0,0 +1,323 @@+#!/usr/bin/env python3+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Python wrapper around `clang` intended for use by the parallel opt phase of+a Distributed ThinLTO compilation. This script works around a LLVM bug where+LLVM will return a zero exit code in the case where ThinLTO fails with a+fatal error.++Instead of trusting the exit code of the compiler, this script checks the+output file and returns 1 if the file has zero size.+"""++import argparse+import os+import subprocess+import sys+import traceback+from typing import List++EXIT_SUCCESS, EXIT_FAILURE = 0, 1+++# Filter opt related flags+def _filter_flags(clang_flags: List[str]) -> List[str]: # noqa: C901+ # List of llvm flags to be ignored.+ # They either don't have an valid mapping or unused during opt.+ IGNORE_OPT_FLAGS = [+ "-Wl,-plugin-opt,-function-sections",+ "-Wl,--lto-whole-program-visibility",+ "-Wl,--no-lto-whole-program-visibility",+ "-flto=thin",+ ]+ # Conservatively, we only translate llvms flags in our known list+ KNOWN_LLVM_SHARED_LIBRARY_FLAGS = ["-pie", "-shared"]++ # Start with default flags for opt.+ # The default values may change across compiler versions.+ # Make sure they are always synced with the current values.+ opt_flags = [+ # TODO(T139459294):+ # -O2 is the default optimization flag for the link-time optimizer+ # this setting matches current llvm implementation:+ # https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/LTO/Config.h#L57+ "-O2",+ "-ffunction-sections",+ "-fdata-sections",+ ]++ # Clang driver passes through lld flags with "-Wl," prefix. There are 4 type of flags with unique+ # prefixes:+ # 1. "--lto-...": these are native lld flags.+ # 2. "-plugin-opt,..." or "-plugin-opt=...": these are the aliases of the native lld flags (1).+ # 3. "-mllvm,...": these are llvm flags.+ # 4. "-plugin-opt,-..." or "-plugin-opt=-...": these are the aliases of llvm flags (3). Note that they differ from (2) and always start with "-".+ #+ # For (1) and (2), we need to convert them case by case.+ # For (3) and (4), we should be able to pass them through into the optimizer directly by prefixing "-mllvm".+ # TODO(T139448744): Cover all the flags. Check available flags using "ld.lld --help | grep -A 1 '\-\-plugin-opt='"+ PLUGIN_OPT_PREFIXES = ["-Wl,-plugin-opt,", "-Wl,-plugin-opt="]++ def _find_plugin_opt_prefix(flag: str) -> str:+ matched_prefix = [+ prefix for prefix in PLUGIN_OPT_PREFIXES if flag.startswith(prefix)+ ]+ if matched_prefix:+ return matched_prefix[0]+ return ""++ plugin_opt_to_llvm_flag_map = {+ "sample-profile=": "-fprofile-sample-use=",+ "O": "-O",+ }++ def _plugin_opt_to_clang_flag(flag: str) -> str:+ for k, v in plugin_opt_to_llvm_flag_map.items():+ if flag.startswith(k):+ return flag.replace(k, v)+ return None++ index = 0+ while index < len(clang_flags):+ raw_flag = clang_flags[index]+ flag = raw_flag.replace('"', "")+ if flag in IGNORE_OPT_FLAGS:+ index += 1+ continue+ if _find_plugin_opt_prefix(flag):+ # Convert "-Wl,-plugin-opt,...".+ flag = flag.replace(_find_plugin_opt_prefix(flag), "", 1)+ if flag.startswith("-"):+ # If flag starts with "-", it is an llvm flag. Pass it through directly.+ opt_flags.extend(["-mllvm", flag])+ else:+ flag = _plugin_opt_to_clang_flag(flag)+ if flag is None:+ # Bail on any unknown flag.+ print(f"error: unrecognized flag {raw_flag}")+ return None+ opt_flags.append(flag)+ elif flag.startswith("-Wl,-mllvm,"):+ # Convert "-Wl,-mllvm,...". It is an llvm flag. Pass it through directly.+ flag = flag.replace("-Wl,-mllvm,", "", 1)+ opt_flags.extend(["-mllvm", flag])+ elif flag in KNOWN_LLVM_SHARED_LIBRARY_FLAGS:+ # The target is a shared library, `-fPIC` is needed in opt phase to correctly generate PIC ELF.+ opt_flags.append("-fPIC")+ elif flag.startswith("-f"):+ # Always pass in -f flags which are presumed to be Clang flags.+ opt_flags.append(flag)+ elif flag == "-Xlinker":+ # Handle -Xlinker -xxxx flags. -Xlinker flags are passed in two+ # lines, the first line being just "-Xlinker" and the second line+ # being the actual arg.+ if index + 1 >= len(clang_flags):+ print(+ f"error: cannot handle -Xlinker flags {clang_flags}, "+ "-Xlinker should be followed by an option"+ )+ return EXIT_FAILURE+ if clang_flags[index + 1] == "-mllvm":+ # Validate -Xlinker+ # -mllvm+ # -Xlinker+ # -xxxx structure+ # This assumes -mllvm and its arg are provided consecutively,+ # mostly to handle the case where they come from Buck's+ # linker_flags.+ # TODO(T159109840): Generalize this logic to handle -Xlinker+ # -mllvm -unrelated-flag -Xlinker -actual-mllvm-arg+ if (+ index + 2 >= len(clang_flags)+ or index + 3 >= len(clang_flags)+ or clang_flags[index + 2] != "-Xlinker"+ ):+ print(+ f"error: cannot handle -Xlinker flags {clang_flags}, "+ "-mllvm should be followed by an llvm option"+ )+ return EXIT_FAILURE+ opt_flags.extend(["-mllvm", clang_flags[index + 3]])+ index += 3+ else:+ # Otherwise skip this -Xlinker flag and its arg+ index += 1+ index += 1+ return opt_flags+++# Clean up clang flags by obtaining the cc1 flags and filtering out those unwanted.+# clang_opt_flags is mutated after calling this function.+def _cleanup_flags(clang_opt_flags: List[str]) -> List[str]:+ for i, arg in enumerate(clang_opt_flags):+ if arg.startswith("--cc="):+ # Find the clang binary path.+ clang_opt_flags[i] = arg.replace("--cc=", "")+ if arg.startswith("--log-fbcc"):+ # Remove the log-fbcc flag since the compiler is called directly below.+ clang_opt_flags.pop(i)++ # Get the cc1 flag dump with '-###'+ try:+ output = (+ subprocess.check_output(+ clang_opt_flags + ["-###"], stderr=subprocess.STDOUT+ )+ .decode()+ .splitlines()+ )+ except subprocess.CalledProcessError as e:+ print(e.output.decode())+ return None++ # Flags that may conflict with the existing bitcode attributes.+ # The value indicates if the flag is followed with a value.+ flags_to_delete = {+ "-mframe-pointer=none": False,+ "-fmath-errno": False,+ "-fno-rounding-math": False,+ "-mconstructor-aliases": False,+ "-munwind-tables": False,+ "-target-cpu": True,+ "-tune-cpu": True,+ }++ clean_output = []+ skip_next = False+ for f in output[-1].split()[1:]:+ if skip_next:+ skip_next = False+ else:+ f = f.strip('"')+ if f in flags_to_delete:+ skip_next = flags_to_delete[f]+ else:+ clean_output.append(f)+ return clean_output+++# Flags that fbcc consumes and does NOT pass through to the compiler.+# See fbcode/tools/build/buck/wrappers/fbcc.py for the full list.+_FBCC_CONSUMED_PREFIXES = (+ "--log-fbcc",+ "--fbcc-create-external-debug-info=",+ "--show-flags",+)+++def _fbcc_prefix_end(opt_args: List[str]) -> int:+ """Return the slice end for the fbcc prefix within opt_args.++ opt_args layout:+ ['--', <fbcc>, '--cc=<compiler>', <optional fbcc-consumed args>, ...]++ Only args that fbcc *consumes* (strips before invoking the compiler)+ belong in the prefix. Pass-through args like ``--target=`` must be+ excluded: they are already folded into cc1 flags by ``_cleanup_flags``+ and including them in ``fbcc_cmd`` would place them before ``-cc1``,+ which prevents clang from entering cc1 mode.+ """+ end = 3 # ['--', fbcc, '--cc=...']+ while end < len(opt_args) and any(+ opt_args[end].startswith(p) for p in _FBCC_CONSUMED_PREFIXES+ ):+ end += 1+ return end+++def main(argv: List[str]) -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--out", help="The output native object file.")+ parser.add_argument("--input", help="The input bitcode object file.")+ parser.add_argument("--index", help="The thinlto index file.")+ parser.add_argument("--split-dwarf", help="Split dwarf option.", default="none")+ parser.add_argument("--dwo", help="Split-dwarf .dwo file to be created.")+ parser.add_argument(+ "--args", help="The argsfile containing unfiltered and unprocessed flags."+ )+ parser.add_argument("--debug", action="store_true", help="Dump clang -cc1 flags.")+ parser.add_argument("opt_args", nargs=argparse.REMAINDER)+ args = parser.parse_args(argv[1:])+ split_dwarf: str = args.split_dwarf+ dwo: str | None = args.dwo++ with open(args.args, "r") as argsfile:+ clang_opt_flags = _filter_flags(argsfile.read().splitlines())+ if clang_opt_flags is None:+ return EXIT_FAILURE++ clang_opt_flags.extend(+ [+ "-o",+ args.out,+ "-x",+ "ir",+ "-c",+ args.input,+ f"-fthinlto-index={args.index}",+ ]+ )+ if split_dwarf == "none":+ assert dwo is None+ clang_opt_flags.append("-gno-split-dwarf")+ else:+ # Note that -gsplit-dwarf=single does not create a .dwo file.+ assert (dwo is not None) == (split_dwarf == "split")+ clang_opt_flags.append(f"-gsplit-dwarf={args.split_dwarf}")++ # The following args slices manipulating may be confusing. The opt_args are:+ # 1. a spliter "--", it's not used anywhere;+ # 2. the fbcc wrapper script path+ # 3. the "--cc" arg pointing to the compiler we use+ # 4. (optional) fbcc-consumed args like "--log-fbcc"+ # 5. (optional) pass-through args like "--target=" (from buckified toolchains)+ # EXAMPLE: ['--', 'buck-out/v2/gen/fbcode/8e3db19fe005003a/tools/build/buck/wrappers/__fbcc__/fbcc', '--cc=fbcode/third-party-buck/platform010/build/llvm-fb/<ver>/bin/clang++', '--log-fbcc=False', '--target=x86_64-redhat-linux-gnu', ...]+ clang_cc1_flags = _cleanup_flags(args.opt_args[2:] + clang_opt_flags)+ if clang_cc1_flags is None:+ return EXIT_FAILURE++ # Determine the end of fbcc-specific prefix args (fbcc path, --cc=, and+ # optionally args that fbcc consumes like --log-fbcc).+ # Only fbcc-consumed args belong in the prefix; pass-through args like+ # --target= are already folded into clang_cc1_flags by _cleanup_flags+ # and must NOT appear in fbcc_cmd where they would precede -cc1 and+ # prevent clang from entering cc1 mode.+ fbcc_prefix_end = _fbcc_prefix_end(args.opt_args)+ fbcc_cmd = args.opt_args[1:fbcc_prefix_end] + clang_cc1_flags++ if args.debug:+ # Print fbcc commandline and exit.+ print(" ".join(fbcc_cmd))+ return EXIT_SUCCESS++ subprocess.check_call(fbcc_cmd)+ if os.stat(args.out).st_size == 0:+ print("error: opt produced empty file")+ return EXIT_FAILURE++ if dwo is not None:+ # Unfortunately some users manually add `-gno-split-dwarf` to the+ # compiler flags contradicting the --split-dwarf setting. Create an+ # empty file so buck rules are not missing the file...+ try:+ with open(dwo, "x") as _:+ pass+ except IOError:+ pass++ return EXIT_SUCCESS+++if __name__ == "__main__":+ try:+ sys.exit(main(sys.argv))+ except subprocess.CalledProcessError as e:+ traceback.print_exc()+ sys.exit(e.returncode)
@@ -0,0 +1,331 @@+#!/usr/bin/env python3+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+A wrapper script around the linker invocation that completes distributed thin-lto thin-link.++This script:++(1) Parses the meta file, which specifies various file paths for each input object file.+(2) Writes "plan" json files for each input object file or archive describing to Buck starlark logic how to create opt + codegen actions for each+(3) Writes a "link plan" and a "final index". The link plan is used to identify which input object files are already native object files, and the final index constitutes a filelist used in the final native link. This filelist is a transformed version of the "index.full" file the linker produces.++Starlark code holds a representation of each input object file or archive in memory in an array. When code here needs to communicate characteristics about a particular element of this array, it encodes this using the index into this array. These indices are referred to as "starlark array index"+"""++import argparse+import dataclasses+import json+import os+import os.path+import subprocess+import sys+import tempfile+import traceback+from dataclasses import dataclass+from enum import Enum+from typing import Optional+++class BitcodeMergeState(str, Enum):+ STANDALONE = "STANDALONE"+ ABSORBED = "ABSORBED"+ ROOT = "ROOT"+ NOT_LOADED = "NOT_LOADED"+++def is_file_llvm_bitcode_wrapper_file(filepath: str) -> bool:+ LLVM_BITCODE_WRAPPER_FILE_MAGIC = 0xDEC0170B+ with open(filepath, "rb") as f:+ file_magic = int.from_bytes(f.read(4), "big")+ return file_magic == LLVM_BITCODE_WRAPPER_FILE_MAGIC+++def read_merged_bitcode_file(merged_bitcode_path) -> BitcodeMergeState:+ if os.path.getsize(merged_bitcode_path) == 0:+ return BitcodeMergeState.NOT_LOADED++ if is_file_llvm_bitcode_wrapper_file(merged_bitcode_path):+ return BitcodeMergeState.ROOT++ with open(merged_bitcode_path) as merged_bitcode_file:+ for line in merged_bitcode_file:+ if "standalone" in line:+ return BitcodeMergeState.STANDALONE+ if "absorbed" in line:+ return BitcodeMergeState.ABSORBED++ raise Exception(f"unexpected merged bitcode file contents: {merged_bitcode_path}")+++@dataclass+class ObjectFile:+ """An object files passed directly to the distributed link. The object file may or may not be lazy."""++ input_object_file_path: str+ output_index_shard_file_path: str+ output_premerged_bitcode_file_path: Optional[str]+ output_plan_file_path: str+ starlark_array_index: int++ def __init__(+ self,+ input_object_file_path: str,+ output_index_shard_file_path: str,+ output_plan_file_path: str,+ starlark_array_index: int,+ output_premerged_bitcode_file_path: Optional[str] = None,+ ):+ self.input_object_file_path = input_object_file_path+ self.output_index_shard_file_path = output_index_shard_file_path+ self.output_premerged_bitcode_file_path = output_premerged_bitcode_file_path+ self.output_plan_file_path = output_plan_file_path+ self.starlark_array_index = int(starlark_array_index)+++@dataclass+class ObjectFileOptimizationPlan:+ """A structure holding the information required to optimize and codegen a single bitcode object file passed+ directly to the link"""++ # A list of indices into the sorted_index_link_data starlark array+ # that identify other bitcode files this bitcode file imports from,+ # and thus should be optimized along side+ imports: list[int]+ is_bitcode: bool+ merge_state: Optional[BitcodeMergeState]+ loaded_by_linker: bool+++BITCODE_SUFFIX = ".thinlto.bc"+IMPORTS_SUFFIX = ".imports"+OPT_OBJECTS_SUFFIX = ".opt.o" # please note the files are not exist yet, this is to generate the index file use in final link+MERGED_BITCODE_SUFFIX = ".merged.bc"+++def _parse_meta_file_records(+ meta_file_path: str,+) -> tuple[dict[str, ObjectFile]]:+ object_file_records_map: dict[str, ObjectFile] = {}++ with open(meta_file_path) as meta:+ object_file_records_json = json.load(meta)+ for record in object_file_records_json:+ object_file_record = ObjectFile(**record)+ object_file_records_map[object_file_record.input_object_file_path] = (+ object_file_record+ )++ return object_file_records_map+++def _populate_premerger_path_conversion_maps(+ object_file_records_map: dict[str, ObjectFile],+) -> tuple[dict[str, str], dict[str, str]]:+ original_bitcode_to_merged_bitcode_path_mapping = {}+ merged_bitcode_to_original_bitcode_path_mapping = {}+ for (+ input_object_file_path,+ object_file_record,+ ) in object_file_records_map.items():+ output_merged_bitcode_file_path = None+ assert object_file_record.output_premerged_bitcode_file_path is not None+ output_merged_bitcode_file_path = (+ object_file_record.output_premerged_bitcode_file_path+ )++ original_bitcode_to_merged_bitcode_path_mapping[input_object_file_path] = (+ output_merged_bitcode_file_path+ )+ merged_bitcode_to_original_bitcode_path_mapping[+ output_merged_bitcode_file_path+ ] = input_object_file_path++ return (+ original_bitcode_to_merged_bitcode_path_mapping,+ merged_bitcode_to_original_bitcode_path_mapping,+ )+++def _run_thin_link(+ premerger_enabled: bool,+ original_bitcode_to_merged_bitcode_path_mapping: dict[str, str],+ thin_link_args: list[str],+):+ if premerger_enabled:+ # Buck requires actions write output files to a location set by the build system. When toolchain+ # binaries cannot for whatever reason easily produce output files at known locations configurable+ # locations, the usual approach is to use a wrapper Python script such as this one to place the+ # files at the locations buck expects. In this case, this will not work as sharded summaries embed+ # paths to other bitcode files within the bitcode. That means the toolchain must write the merged+ # bitcode files to locations buck expects in the first place. This json document is parsed by the+ # linker and communicates the locations at which the toolchain must write the merged bitcode files.+ with tempfile.NamedTemporaryFile(mode="w+t") as premerger_output_mapping:+ json.dump(+ original_bitcode_to_merged_bitcode_path_mapping,+ premerger_output_mapping,+ )+ premerger_output_mapping.flush()+ thin_link_args.append(+ f"-Wl,-mllvm,-premerger-output-map={premerger_output_mapping.name}"+ )+ subprocess.check_call(thin_link_args)+ else:+ subprocess.check_call(thin_link_args)+++def main(argv):+ parser = argparse.ArgumentParser()+ parser.add_argument("--meta")+ parser.add_argument("--index")+ parser.add_argument("--link-plan")+ parser.add_argument("--enable-premerger", action="store_true")+ parser.add_argument("index_args", nargs=argparse.REMAINDER)+ args = parser.parse_args(argv[1:])++ premerger_enabled = args.enable_premerger++ def read_imports(imports_path):+ with open(imports_path) as infile:+ if not premerger_enabled:+ return [line.strip() for line in infile.readlines()]++ result = []+ for line in infile.readlines():+ if line.strip().endswith(".merged.bc"):+ result.append(+ merged_bitcode_to_original_bitcode_path_mapping[line.strip()]+ )+ else:+ result.append(line.strip())+ return result++ def index_path(path):+ return os.path.join(args.index, path)++ object_file_records_map = _parse_meta_file_records(args.meta)++ original_bitcode_to_merged_bitcode_path_mapping = {}+ if premerger_enabled:+ (+ original_bitcode_to_merged_bitcode_path_mapping,+ merged_bitcode_to_original_bitcode_path_mapping,+ ) = _populate_premerger_path_conversion_maps(object_file_records_map)++ _run_thin_link(+ premerger_enabled,+ original_bitcode_to_merged_bitcode_path_mapping,+ args.index_args[1:],+ )++ loaded_input_files_positions = {}+ with open(index_path("index.full")) as indexfile:+ for position, line in enumerate(indexfile):+ if line.startswith(args.index):+ # Bitcode files that appear in the index are prefixed with the argument to --thinlto-prefix-replace+ # which in our case is the directory index is placed in. Remove this prefix to get the original path.+ input_bitcode_file_path = os.path.relpath(+ line.strip(), start=args.index+ )+ loaded_input_files_positions[input_bitcode_file_path] = position+ else:+ loaded_input_files_positions[line.strip()] = position++ def _input_file_path_is_loaded_by_linker(path):+ return path in loaded_input_files_positions++ absorbed_source_files = set()+ non_lto_objects = {}++ # Generate plans for object files+ for path, data in sorted(object_file_records_map.items(), key=lambda v: v[0]):+ # The linker will not write the sharded index to the location buck expects it to be by default, we need+ # to move it there.+ final_sharded_index_output_path = data.output_index_shard_file_path+ os.makedirs(os.path.dirname(final_sharded_index_output_path), exist_ok=True)++ temporary_sharded_index_location = index_path(path) + BITCODE_SUFFIX+ imports_file_path = index_path(path) + IMPORTS_SUFFIX+ merged_bitcode_path = (+ original_bitcode_to_merged_bitcode_path_mapping[path]+ if premerger_enabled+ else None+ )++ final_link_line_position = -1+ if path in loaded_input_files_positions:+ final_link_line_position = loaded_input_files_positions[path]++ # import files are only written for bitcode files+ if os.path.exists(imports_file_path):+ assert os.path.exists(temporary_sharded_index_location), (+ "missing sharded index file for %s" % path+ )+ os.rename(temporary_sharded_index_location, final_sharded_index_output_path)++ imports = read_imports(imports_file_path)+ imports_list = []+ for import_path in imports:+ imported_object_file_record = object_file_records_map[import_path]+ imports_list.append(imported_object_file_record.starlark_array_index)++ merge_state = None+ if premerger_enabled:+ assert os.path.exists(merged_bitcode_path), (+ f"missing merged bitcode file at {merged_bitcode_path}"+ )+ merge_state = read_merged_bitcode_file(merged_bitcode_path)+ if merge_state == BitcodeMergeState.ABSORBED:+ absorbed_source_files.add(path)++ plan = ObjectFileOptimizationPlan(+ imports=imports_list,+ merge_state=merge_state,+ is_bitcode=True,+ loaded_by_linker=_input_file_path_is_loaded_by_linker(path),+ final_link_line_position=final_link_line_position,+ )+ else:+ # The linker will not generate an index shard, or a merged bitcode file if the input is not bitcode.+ # Buck still expect the output, so write an empty file.+ non_lto_objects[data.starlark_array_index] = 1+ with open(final_sharded_index_output_path, "w"):+ pass++ if premerger_enabled:+ with open(merged_bitcode_path, "w"):+ pass+ plan = ObjectFileOptimizationPlan(+ imports=[],+ merge_state=None,+ is_bitcode=False,+ loaded_by_linker=_input_file_path_is_loaded_by_linker(path),+ final_link_line_position=final_link_line_position,+ )++ with open(data.output_plan_file_path, "w") as planout:+ json.dump(dataclasses.asdict(plan), planout, sort_keys=True)++ # Dump the set of input object files that were already native object files instead of bitcode+ with open(args.link_plan, "w") as outfile:+ json.dump(+ {+ "non_lto_objects": non_lto_objects,+ },+ outfile,+ sort_keys=True,+ )+++if __name__ == "__main__":+ try:+ sys.exit(main(sys.argv))+ except subprocess.CalledProcessError as e:+ traceback.print_exc()+ sys.exit(e.returncode)
@@ -0,0 +1,600 @@+#!/usr/bin/env python3+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+A simple wrapper around a distributed thinlto index command to fit into buck2's+distributed thinlto build.++This reads in a couple of things:+ 1. The "meta" JSON file. This is a list of all the linkable information.+ It contains the object file, index output, plan output.+ As well as associated pre/post flags for linkables.+ 2. The index and link plan output paths+ 3. The commands for the actual index command.++It will invoke the index command and then copy the index outputs to the+requested locations and write a plan for each of those objects. This "plan" is+a simple json file with the most important thing being a list of the indices+of the imports needed for that file.++It will then additionally write a link plan, which is just a translation of+the thinlto index (which lists the objects actually needed for the final link).+++Both opt and link plans use indices to refer to other files because it allows the bzl+code to easily map back to other objects held in buck memory.+"""++import argparse+import json+import os+import os.path+import resource+import subprocess+import sys+import traceback+from typing import List, TextIO+++def _flatten_deep(items):+ """Flatten recursive list of lists to a single list.++ Example:+ >>> _flatten_deep([1, [2, 3], 4, [5, [6]]]) == [1, 2, 3, 4, 5, 6]+ """++ def flatten_deep_helper(items, result):+ for item in items:+ if isinstance(item, (list, tuple)):+ flatten_deep_helper(item, result)+ else:+ result.append(item)++ result = []+ flatten_deep_helper(items, result)++ return result+++def _get_argsfile(args) -> str:+ # go through the flags passed to linker and find the index argsfile+ argsfiles = list(+ filter(lambda arg: arg.endswith("thinlto_index_argsfile"), args.index_args)+ )+ assert len(argsfiles) == 1, (+ f"expect only 1 argsfile but seeing multiple ones: {argsfiles}"+ )+ argsfile = argsfiles[0]+ if argsfile.startswith("@"):+ argsfile = argsfile[1:]+ return argsfile+++def _extract_lib_search_path(argsfile_path: str) -> List[str]:+ lib_search_path = []+ with open(argsfile_path) as argsfile:+ for line in argsfile:+ if line.startswith("-L"):+ lib_search_path.append(line.strip())+ return lib_search_path+++def _write_args(argsfile: TextIO, args: List[str]) -> None:+ for arg in args:+ argsfile.write(arg.strip())+ argsfile.write("\n")+++def _enable_core_dumps() -> None:+ # The index step runs the system linker, which -- unlike Meta binaries --+ # installs no userspace crash handler, so a crash only leaves a core dump if+ # the kernel writes one, and the kernel writes nothing while the RLIMIT_CORE+ # soft limit is 0. buck2 sets no per-action rlimits, so raise the soft limit+ # to the inherited hard limit here (best effort: a no-op when the hard limit+ # is itself 0, which needs a host/container-level change instead).+ try:+ _, hard = resource.getrlimit(resource.RLIMIT_CORE)+ resource.setrlimit(resource.RLIMIT_CORE, (hard, hard))+ except (OSError, ValueError) as e:+ print(f"warning: failed to enable core dumps: {e}", file=sys.stderr)+++def main(argv):+ parser = argparse.ArgumentParser()+ parser.add_argument("--meta")+ parser.add_argument("--index")+ parser.add_argument("--link-plan")+ parser.add_argument("--final-link-index")+ parser.add_argument("index_args", nargs=argparse.REMAINDER)+ args = parser.parse_args(argv[1:])++ _enable_core_dumps()+ subprocess.check_call(args.index_args[1:])++ bitcode_suffix = ".thinlto.bc"+ imports_suffix = ".imports"+ opt_objects_suffix = ".opt.o" # please note the files are not exist yet, this is to generate the index file use in final link++ # `linkables_index` contains the linkables that are NOT LLVM IR bitcode files (e.g., machine code archives, shared libraries).+ # `linkables_index`'s key is the path to the linkable and the value is a dictionary containing the cmd_args and the meta_index.+ # `linkables_index` is used to re-attach associated flags (pre/post flags and flags in the cmd_args form like `-Wl,--whole-archive`/`-Wl,--no-whole-archive`)+ # for the final_link_index @argsfile used in the the Phase 4 final link.+ # The associated flags are otherwise dropped because `ld.lld` produces an `index.full` file in the Phase 2 Thin Link step+ # only contains the path to the linkable and no flags.+ linkables_index = {}++ with open(args.meta) as f:+ meta = json.load(f)++ for meta_entry_index1, meta_entry1 in enumerate(meta):+ for linkable in meta_entry1["linkables"]:+ if linkable["type"] == "cmd_args":+ obj = linkable["object"]++ if obj["type"] == "archive":+ linkable_path = obj["archive"]+ linkables_index[linkable_path] = {+ "cmd_args": linkable["cmd_args"],+ "meta_index": meta_entry_index1,+ }+ elif obj["type"] == "shared_lib":+ linkable_path = obj["name"]+ linkables_index[linkable_path] = {+ "cmd_args": linkable["cmd_args"],+ "meta_index": meta_entry_index1,+ }+ else:+ raise Exception(f"unknown linkable type: {obj}")++ def read_imports(path, imports_path):+ with open(imports_path) as infile:+ return [line.strip() for line in infile.readlines()]++ def index_path(path):+ return os.path.join(args.index, path)++ # The meta file comes directly from dist_lto.bzl and consists of a list of JSON objects.+ #+ # Example:+ # ```+ # [+ # {+ # "linkables": [+ # {+ # "type": "bitcode",+ # "path": "buck-out/v2/art/spongebob/Gary.cpp.o",+ # "output": "buck-out/v2/art/spongebob/Gary.cpp.o.thinlto.bc",+ # "plan_output": "buck-out/v2/art/spongebob/Gary.cpp.o.opt.plan",+ # "idx": 0+ # },+ # ...+ # ],+ # "pre_flags": [],+ # "post_flags": [],+ # },+ # {+ # "linkables": [+ # {+ # "type": "cmd_args",+ # "cmd_args": [ "build/glog/lib/libglog.a" ],+ # "linkable_type": "archive_linkable",+ # "object": {+ # "type": "archive",+ # "archive": "build/glog/lib/libglog.a",+ # }+ # }+ # ]+ # },+ # ...+ # ]+ # ```+ #+ # Inside objects with type "bitcode" and "archive", there are several attributes:+ # - path: The path to the source bitcode file from Phase 1 Compile.+ # This is used as an index into a dictionary (`mapping`) that records much of the metadata coming+ # from these lines.+ # - output: The path to output location of Phase 2 Thin Link's analysis result for this individual module.+ # This script is expected to place a ThinLTO index file at this location (suffixed `.thinlto.bc`).+ # - plan_output: The path to an output plan. This script is expected to place a link+ # plan here (a JSON document indicating which other object files this)+ # object file depends on, among other things.+ # - idx: The link data's index in the Starlark array.+ # - archive_name: If this object file came from an archive, the name of the archive.+ # Otherwise, this line is empty.+ # - archive_plan: If this object file came from an archive, the path to an output plan.+ # This script is expected to produce an archive link plan here (a JSON)+ # document similar to the object link plan, except containing link+ # information for every file in the archive from which this object+ # came. Otherwise, this line is empty.+ # - archive_index_dir: If this object file came from an archive, the indexes directory of that+ # archive. This script is expected to place all ThinLTO indexes derived+ # from object files originating from this archive in that directory.+ # Otherwise, this line is empty.+ # - archive_opt_objects_dir: If this object file came from an archive, the directory where+ # Phase 3 stages every member of that archive, each at its path relative+ # to the archive's base dir (the dir holding `archive_plan`). It is the+ # only dir of the archive that Phase 4 Final Link materializes, so the+ # final-link index must refer to members through it.+ #+ # There are two indices that are derived from this meta file: the object+ # index (mapping["index"]) and the archive index (mapping["archive_index"]).+ # These indices are indices into Starlark arrays for all objects and archive+ # linkables, respectively. This script does not inspect them.+ mapping = {}+ archives = {}+ for meta_entry_index2, meta_entry2 in enumerate(meta):+ for linkable in meta_entry2["linkables"]:+ if linkable["type"] == "bitcode":+ path = linkable["path"]+ output = linkable["output"]+ plan_output = linkable["plan_output"]+ idx = linkable["idx"]+ mapping[path] = {+ "output": output,+ "plan_output": plan_output,+ "index": idx,+ "meta_index": meta_entry_index2,+ "archive_index": None,+ "archive_name": "",+ "opt_object_path": "",+ }+ elif linkable["type"] == "archive":+ archive_idx = linkable["archive_idx"]+ archive_name = linkable["archive_name"]+ archive_plan = linkable["archive_plan"]+ archive_index_dir = linkable["archive_index_dir"]+ archive_opt_objects_dir = linkable["archive_opt_objects_dir"]+ archive_base_dir = os.path.dirname(archive_plan)++ obj_mapping_entry = {+ "output": "",+ "plan_output": "",+ "index": archive_idx,+ "meta_index": meta_entry_index2,+ "archive_index": archive_idx,+ "archive_name": archive_name,+ }+ for obj in linkable["objects"] or ():+ path = obj["path"]+ mapping[path] = dict(+ obj_mapping_entry,+ # Where Phase 3 stages this member, and thus the path Phase 4+ # Final Link must use for it.+ opt_object_path=os.path.join(+ archive_opt_objects_dir,+ os.path.relpath(path, archive_base_dir),+ ),+ )++ archives[archive_idx] = {+ "name": archive_name,+ "objects": [],+ "plan": archive_plan,+ "index_dir": archive_index_dir,+ }++ non_lto_objects = {}+ for path, data in sorted(mapping.items(), key=lambda v: v[0]):+ output_loc = data["output"]+ if os.path.exists(output_loc):+ continue++ if data["archive_index"] is not None:+ archives[data["archive_index"]]["objects"].append(path)+ continue++ bc_file = index_path(path) + bitcode_suffix+ imports_path = index_path(path) + imports_suffix+ os.makedirs(os.path.dirname(output_loc), exist_ok=True)++ if os.path.exists(imports_path):+ assert os.path.exists(bc_file), "missing bc file for %s" % path+ os.rename(bc_file, output_loc)+ imports = read_imports(path, imports_path)+ imports_list = []+ archives_list = []+ for import_path in imports:+ if import_path not in mapping:+ continue+ entry = mapping[import_path]+ if entry["archive_index"] is not None:+ archives_list.append(int(entry["archive_index"]))+ else:+ imports_list.append(entry["index"])+ plan = {+ "imports": imports_list,+ "archive_imports": archives_list,+ "index": data["index"],+ "bitcode_file": bc_file,+ "path": path,+ "is_bc": True,+ }+ else:+ non_lto_objects[data["index"]] = 1+ with open(output_loc, "w"):+ pass+ plan = {+ "is_bc": False,+ }++ with open(data["plan_output"], "w") as planout:+ json.dump(plan, planout, sort_keys=True)++ for archive in archives.values():+ # For archives, we must produce a plan that provides Starlark enough+ # information about how to launch a dynamic opt for each object file+ # in the archive.+ archive_plan = {}++ # This is convenient to store, since it's difficult for Starlark to+ # calculate it.+ archive_plan["base_dir"] = os.path.dirname(archive["plan"])+ object_plans = []+ for obj in archive["objects"]:+ imports_path = index_path(obj) + imports_suffix+ output_path = archive["index_dir"]+ os.makedirs(output_path, exist_ok=True)+ if os.path.exists(imports_path):+ bc_file = index_path(obj) + bitcode_suffix+ os.rename(bc_file, os.path.join(output_path, os.path.basename(bc_file)))+ imports = read_imports(path, imports_path)++ imports_list = []+ archives_list = []+ for path in imports:+ if path not in mapping:+ continue+ entry = mapping[path]+ if entry["archive_index"] is not None:+ archives_list.append(int(entry["archive_index"]))+ else:+ imports_list.append(entry["index"])+ object_plans.append(+ {+ "is_bc": True,+ "path": obj,+ "imports": imports_list,+ "archive_imports": archives_list,+ "bitcode_file": os.path.join(+ output_path, os.path.basename(bc_file)+ ),+ }+ )+ else:+ object_plans.append(+ {+ "is_bc": False,+ "path": obj,+ }+ )++ archive_plan["objects"] = object_plans+ with open(archive["plan"], "w") as planout:+ json.dump(archive_plan, planout, sort_keys=True)++ # We read the `index` and `index.full` files produced by linker in index stage+ # and translate them to 2 outputs:+ # 1. A link plan build final_link args. (This one may be able to be removed if we refactor the workflow)+ # 2. A files list (*.final_link_index) used for final link stage which includes all the+ # files needed. it's based on index.full with some modification, like path updates+ # and redundant(added by toolchain) dependencies removing.+ # The `index` file is a list of the LLVM IR bitcode files that were analyzed in the Phase 2 Thin Link Step.+ # The `index.full` file is of ALL linkables used in the linking process, ordered by their symbol resolution.+ # For a full discussion on `index.full` see https://reviews.llvm.org/D130229+ # The file paths in `index` and the LLVM IR Bitcode files in `index.full` are listed as a child of the `args.index` directory.+ # HOWEVER, the LLVM IR Bitcode files do NOT exist there and instead exist in the location with the `args.index` directory stripped off (i.e., with `os.path.relpath(start=args.index)`).+ # The files suffixed with `.imports` and `.thinlto.bc` DO exist in the directory under `args.index`.+ index = {}+ index_files_set = set()+ # TODO(T130322878): since we call linker wrapper twice (in index and in final_link), to avoid these libs get+ # added twice we remove them from the index file for now.+ KNOWN_REMOVABLE_DEPS_SUFFIX = [+ "glibc/lib/crt1.o",+ "glibc/lib/crti.o",+ "glibc/lib/Scrt1.o",+ "crtbegin.o",+ "crtbeginS.o",+ ".build_info.o",+ "crtend.o",+ "crtendS.o",+ "glibc/lib/crtn.o",+ ]+ GENERATED_BUILD_INFO_OBJECT_BASENAME_PREFIX = "__buck2_generated_build_info.c"+ with open(index_path("index")) as indexfile:+ for line in indexfile:+ line = line.strip()+ index_files_set.add(line)+ path = os.path.relpath(line, start=args.index)+ if path in mapping:+ index[mapping[path]["index"]] = 1++ with open(args.link_plan, "w") as outfile:+ json.dump(+ {+ "non_lto_objects": non_lto_objects,+ "index": index,+ },+ outfile,+ indent=2,+ sort_keys=True,+ )++ # Append all search path flags (e.g -Lfbcode/third-party-buck/platform010/build/glibc/lib) from argsfile to final_index+ # this workaround is to make dist_lto compatible with link_group. see T136415235 for more info+ argsfile = _get_argsfile(args)+ lib_search_path = _extract_lib_search_path(argsfile)++ # build index file for final link use+ with (+ open(index_path("index.full")) as full_index_input,+ open(args.final_link_index, "w") as final_link_index_output,+ ):+ final_link_index_output.write("\n".join(lib_search_path) + "\n")++ # Keep track of the flags that were written because the ones that weren't are written at the end.+ # The index into `flags_written_tracker` corresponds to the `index` into `meta`.+ flags_written_tracker = bytearray(len(meta))++ # Write out first flags without an associated linkable in the meta.+ # Stop once we see the first linkable because+ # flags with an associated linkables are written in the order they are seen in `full_index_input`.+ for meta_entry_index3, meta_entry3 in enumerate(meta):+ if meta_entry3["linkables"]:+ # Break once we see the first linkable entry.+ break+ else:+ pre_flags = _flatten_deep(meta_entry3["pre_flags"])+ _write_args(final_link_index_output, pre_flags)++ post_flags = _flatten_deep(meta_entry3["post_flags"])+ _write_args(final_link_index_output, post_flags)+ flags_written_tracker[meta_entry_index3] = 1++ # Keep track of the previous meta_index so when the meta_index changes between loop iterations+ # the post flags are written for the previous meta_index and pre_flags are written for the new meta_index.+ prev_meta_index = None++ for line in full_index_input:+ line = line.strip()+ if any(+ filter(line.endswith, KNOWN_REMOVABLE_DEPS_SUFFIX)+ ) or os.path.basename(line).startswith(+ GENERATED_BUILD_INFO_OBJECT_BASENAME_PREFIX+ ):+ continue+ # LLVM IR files that are indexed in Phase 2 Thin Link are reported by `ld.lld` to exist under the directory `args.index`,+ # but they actually exist at the path with the prefix `args.index` removed.+ # Remove the prefix `args.index` with `os.path.relpath`.+ path = os.path.relpath(line, start=args.index)++ if path in mapping:+ mapping_entry = mapping[path]+ meta_index = mapping_entry["meta_index"]+ elif line in mapping:+ # This case happens when a library is marked with `enable_distributed_thinlto = True`, but+ # has `compiler_flags = ["-fno-lto"]`.+ # In this case the .o file is a machine code file and thus it is NOT indexed by Phase 2 Thin Link,+ # and `line` is NOT prefixed with `args.index`.+ mapping_entry = mapping[line]+ meta_index = mapping_entry["meta_index"]+ elif line in linkables_index:+ mapping_entry = None+ meta_index = linkables_index[line]["meta_index"]+ else:+ mapping_entry = None+ meta_index = None++ has_meta_entry = meta_index is not None++ if has_meta_entry:+ # For simplicity, mark now that we have written the flags for this entry.+ flags_written_tracker[meta_index] = 1++ write_post_flags = (+ prev_meta_index is not None and prev_meta_index != meta_index+ )+ if write_post_flags:+ if post_flags := meta[prev_meta_index]["post_flags"]:+ _write_args(final_link_index_output, _flatten_deep(post_flags))++ write_pre_flags = has_meta_entry and (+ prev_meta_index is None or prev_meta_index != meta_index+ )+ if write_pre_flags:+ # Before writing the pre_flags for THIS entry,+ # write the preceding pre_flags/post_flags without linkables.+ # Since this iterates backwards, we'll store the flags in a stack,+ # and do a 2nd pass that writes them in the correct order into `final_index_args`.+ preceding_flags_stack = []+ for preceding_meta_index in range(meta_index - 1, -1, -1):+ if flags_written_tracker[preceding_meta_index]:+ break++ preceding_meta_entry = meta[preceding_meta_index]+ if preceding_meta_entry["linkables"]:+ # Only write up-to the next linkable+ break++ if preceding_post_flags := preceding_meta_entry["post_flags"]:+ preceding_flags_stack.append(preceding_post_flags)++ if preceding_pre_flags := preceding_meta_entry["pre_flags"]:+ preceding_flags_stack.append(preceding_pre_flags)++ flags_written_tracker[preceding_meta_index] = 1++ for preceding_flags in reversed(preceding_flags_stack):+ _write_args(final_link_index_output, _flatten_deep(preceding_flags))++ if pre_flags := meta[meta_index]["pre_flags"]:+ _write_args(final_link_index_output, _flatten_deep(pre_flags))++ prev_meta_index = meta_index++ if line in index_files_set and path in mapping and mapping[path]["output"]:+ # This case is for a known and true LLVM IR Bitcode file that was+ # NOT extracted from an archive.++ # Get the output path to the actual file that is linked in Phase 4 Final Link,+ # which is resulting file from Phase 3 ThinLTO Backends.+ # These files are suffixed with ".opt.o" and are siblings to the ".thinlto.bc" files,+ # so the path is obtained by replacing the suffix.+ output = mapping[path]["output"].replace(+ bitcode_suffix, opt_objects_suffix+ )+ final_link_index_output.write(output + "\n")+ elif (+ mapping_entry is not None and mapping_entry["archive_index"] is not None+ ):+ # A member extracted from an LTO-able archive. Phase 3 stages every+ # member -- bitcode and machine code alike -- in the archive's+ # `opt_objects` dir, so both kinds are redirected there. Machine-code+ # members occur for e.g. Rust `compiler_builtins`, which rustc emits as+ # native objects even under `-Clinker-plugin-lto` (the crate is+ # `#![no_builtins]`), so `ld.lld` produces no ThinLTO index for them.+ final_link_index_output.write(mapping_entry["opt_object_path"] + "\n")+ elif line in linkables_index:+ # If this is a known linkable, then use the original cmd_args from the linkable entry,+ # which could contain for example, "-Wl,--whole-archive" and "-Wl,--no-whole-archive" flags.+ linkable_entry = linkables_index[line]+ cmd_args = linkable_entry["cmd_args"]+ if isinstance(cmd_args, list):+ _write_args(final_link_index_output, _flatten_deep(cmd_args))+ else:+ final_link_index_output.write(cmd_args + "\n")+ else:+ # handle:+ # - objects from genrule archives (not tracked by dist_lto)+ # - pre-built archives+ # - input files that did not come from linker input, e.g. linkerscirpts+ final_link_index_output.write(line + "\n")++ # Write post flags for the last iteration of the loop+ if prev_meta_index is not None:+ if post_flags := meta[prev_meta_index]["post_flags"]:+ _write_args(final_link_index_output, _flatten_deep(post_flags))++ # Write out the remaining unwritten flags+ for flags_written_tracker_index, flags_written_tracker_entry in enumerate(+ flags_written_tracker+ ):+ if not flags_written_tracker_entry:+ meta_entry5 = meta[flags_written_tracker_index]+ pre_flags = _flatten_deep(meta_entry5["pre_flags"])+ _write_args(final_link_index_output, pre_flags)+ post_flags = _flatten_deep(meta_entry5["post_flags"])+ _write_args(final_link_index_output, post_flags)+++if __name__ == "__main__":+ try:+ sys.exit(main(sys.argv))+ except subprocess.CalledProcessError as e:+ traceback.print_exc()+ sys.exit(e.returncode)
@@ -0,0 +1,158 @@+#!/usr/bin/env python3+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Prepares for an object-only ThinLTO link by extracting a given archive and+producing a manifest of the objects contained within.+"""++import argparse+import json+import os+import shutil+import subprocess+import sys+import tempfile+import traceback+from typing import List+++def _gen_path(parent_path: str, filename: str) -> str:+ # concat file path and check the file exist before return+ obj_path = os.path.join(parent_path, filename)+ assert os.path.exists(obj_path)+ return obj_path+++def _gen_filename(filename: str, num_of_instance: int) -> str:+ # generate the filename based on the instance,+ # for 1st instance, it's file.o+ # for 2nd instance, it's file_1.o+ if num_of_instance > 1:+ basename, extension = os.path.splitext(filename)+ return f"{basename}_{num_of_instance - 1}{extension}"+ else:+ return filename+++def is_universal_archive(archive_path: str) -> bool:+ output = subprocess.check_output(["file", archive_path]).decode()+ return "Mach-O universal binary" in output+++def extract_slice_from_universal_archive(+ lipo_path: str, target_architecture: str, archive_path: str+) -> str:+ temp_file_name = os.path.join(tempfile.mkdtemp(), "extracted_archive.a")+ subprocess.check_call(+ [+ lipo_path,+ "-thin",+ target_architecture,+ "-output",+ temp_file_name,+ archive_path,+ ]+ )+ return temp_file_name+++def main(argv: List[str]) -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--manifest-out")+ parser.add_argument("--objects-out")+ parser.add_argument("--ar")+ parser.add_argument("--name")+ parser.add_argument("--archive")+ parser.add_argument("--target-architecture")+ parser.add_argument("--lipo")+ args = parser.parse_args(argv[1:])++ objects_path = args.objects_out+ os.makedirs(objects_path, exist_ok=True)++ known_objects = []++ archive_path = os.path.abspath(args.archive)+ if is_universal_archive(archive_path):+ archive_path = extract_slice_from_universal_archive(+ args.lipo, args.target_architecture, archive_path+ )++ # Unfortunately, we use llvm-ar and, while binutils ar has had --output for+ # a long time, llvm-ar does not support --output and the change in llvm-ar+ # looks like it has stalled for years (https://reviews.llvm.org/D69418)+ # So, we need to invoke ar in the directory that we want it to extract into, and so+ # need absolute paths.+ ar_path = os.path.abspath(args.ar)+ output = subprocess.check_output(+ [ar_path, "t", archive_path], cwd=objects_path+ ).decode()+ member_list = [member for member in output.split("\n") if member]++ # This will extract all the members of the archive, including duplicates+ # replacing existing duplicates. That is if first/foo.txt and second/foo.txt+ # are placed in an archive in that order, this will leave second/foo.txt+ # in the objects_path.+ output = subprocess.check_output(+ [ar_path, "xv", archive_path], cwd=objects_path+ ).decode()++ # Count all members of the same name.+ counter = {}+ for member in member_list:+ counter.setdefault(member, 0)+ counter[member] += 1+ # Insert all objects at most once into the list of known objects+ if counter[member] == 1:+ known_objects.append(member)++ with tempfile.TemporaryDirectory() as temp_dir:+ # For each duplicate member, rename and extract duplicates 1 through N+ # inclusive. While N was already extracted above, we don't want to rely+ # upon this implementation detail of llvm-ar.+ for member, count in counter.items():+ if count <= 1:+ continue+ for current in range(1, count + 1):+ # extract the file from archive+ output = subprocess.check_output(+ [+ ar_path,+ "xN",+ str(current),+ archive_path,+ member,+ ],+ cwd=temp_dir,+ ).decode()+ unique_name = _gen_filename(member, current)+ # rename and move the newly extracted file to objects_path+ shutil.move(+ os.path.join(temp_dir, member),+ os.path.join(os.path.abspath(objects_path), unique_name),+ )+ if current > 1:+ known_objects.append(unique_name)++ manifest = {+ "objects": known_objects,+ }+ with open(os.path.join(args.manifest_out), "w") as outfile:+ json.dump(manifest, outfile, indent=2, sort_keys=True)++ return 0+++if __name__ == "__main__":+ try:+ sys.exit(main(sys.argv))+ except subprocess.CalledProcessError as e:+ traceback.print_exc()+ sys.exit(e.returncode)
@@ -0,0 +1,172 @@+#!/usr/bin/env python3+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++"""+Prepares for an object-only ThinLTO link by extracting a given archive and+producing a manifest of the objects contained within.+"""++import argparse+import enum+import json+import os+import shutil+import subprocess+import sys+import tempfile+import traceback+from typing import List, Tuple+++class ArchiveKind(enum.IntEnum):+ UNKNOWN = 0+ ARCHIVE = 1+ THIN_ARCHIVE = 2+++def _gen_path(parent_path: str, filename: str) -> str:+ # concat file path and check the file exist before return+ obj_path = os.path.join(parent_path, filename)+ assert os.path.exists(obj_path)+ return obj_path+++def _gen_filename(filename: str, num_of_instance: int) -> str:+ # generate the filename based on the instance,+ # for 1st instance, it's file.o+ # for 2nd instance, it's file_1.o+ if num_of_instance > 1:+ basename, extension = os.path.splitext(filename)+ return f"{basename}_{num_of_instance - 1}{extension}"+ else:+ return filename+++def identify_file(path: str) -> Tuple[ArchiveKind, str]:+ path = os.path.realpath(path)++ if path.endswith(".rlib"):+ # `file -b` sometimes misfires and reports a Rust rlib+ # as "DOS/MBR boot sector"+ output = "current ar archive\n"+ return (ArchiveKind.ARCHIVE, output)++ output = subprocess.check_output(["file", "-b", path]).decode()+ if "ar archive" in output:+ return (ArchiveKind.ARCHIVE, output)+ elif "thin archive" in output:+ return (ArchiveKind.THIN_ARCHIVE, output)+ else:+ with open(path, "rb") as infile:+ head = infile.read(7)++ if head == "!<thin>".encode():+ return (ArchiveKind.THIN_ARCHIVE, output)++ return (ArchiveKind.UNKNOWN, output)+++def main(argv: List[str]) -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--manifest-out")+ parser.add_argument("--objects-out")+ parser.add_argument("--ar")+ parser.add_argument("--name")+ parser.add_argument("--archive")+ args = parser.parse_args(argv[1:])++ objects_path = args.objects_out+ os.makedirs(objects_path, exist_ok=True)++ known_objects = []+ file_type, debug_output = identify_file(args.archive)+ if file_type == ArchiveKind.ARCHIVE:+ # Unfortunately, we use llvm-ar and, while binutils ar has had --output for+ # a long time, llvm-ar does not support --output and the change in llvm-ar+ # looks like it has stalled for years (https://reviews.llvm.org/D69418)+ # So, we need to invoke ar in the directory that we want it to extract into, and so+ # need absolute paths.+ ar_path = os.path.abspath(args.ar)+ archive_path = os.path.abspath(args.archive)+ output = subprocess.check_output(+ [ar_path, "t", archive_path], cwd=objects_path+ ).decode()+ member_list = [member for member in output.split("\n") if member]++ # This will extract all the members of the archive, including duplicates+ # replacing existing duplicates. That is if first/foo.txt and second/foo.txt+ # are placed in an archive in that order, this will leave second/foo.txt+ # in the objects_path.+ output = subprocess.check_output(+ [ar_path, "xv", archive_path], cwd=objects_path+ ).decode()++ # Count all members of the same name.+ counter = {}+ for member in member_list:+ counter.setdefault(member, 0)+ counter[member] += 1+ # Insert all objects at most once into the list of known objects+ if counter[member] == 1:+ known_objects.append(_gen_path(objects_path, member))++ with tempfile.TemporaryDirectory() as temp_dir:+ # For each duplicate member, rename and extract duplicates 1 through N+ # inclusive. While N was already extracted above, we don't want to rely+ # upon this implementation detail of llvm-ar.+ for member, count in counter.items():+ if count <= 1:+ continue+ for current in range(1, count + 1):+ # extract the file from archive+ output = subprocess.check_output(+ [+ ar_path,+ "xN",+ str(current),+ archive_path,+ member,+ ],+ cwd=temp_dir,+ ).decode()+ unique_name = _gen_filename(member, current)+ # rename and move the newly extracted file to objects_path+ shutil.move(+ os.path.join(temp_dir, member),+ os.path.join(os.path.abspath(objects_path), unique_name),+ )+ if current > 1:+ known_objects.append(_gen_path(objects_path, unique_name))++ elif file_type == ArchiveKind.THIN_ARCHIVE:+ output = subprocess.check_output([args.ar, "t", args.archive]).decode()+ for line in output.splitlines():+ assert os.path.exists(line)+ known_objects.append(line)+ elif file_type == ArchiveKind.UNKNOWN:+ raise AssertionError(+ f"unknown archive kind for file {args.archive}: {debug_output}"+ )++ manifest = {+ "debug": debug_output,+ "objects": known_objects,+ }+ with open(os.path.join(args.manifest_out), "w") as outfile:+ json.dump(manifest, outfile, indent=2, sort_keys=True)++ return 0+++if __name__ == "__main__":+ try:+ sys.exit(main(sys.argv))+ except subprocess.CalledProcessError as e:+ traceback.print_exc()+ sys.exit(e.returncode)
@@ -0,0 +1,325 @@+#!/usr/bin/env fbpython+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++import unittest++from cxx.dist_lto.tools.dist_lto_opt_gnu import _fbcc_prefix_end, _filter_flags+++class TestDistLtoOpt(unittest.TestCase):+ def test_filter_flags(self):+ inputs = [+ "-not-opt-flag",+ "-Wl,-plugin-opt,-llvm_flag1",+ "-Wl,-plugin-opt=-llvm_flag1_different_format",+ "-Wl,-plugin-opt,sample-profile=/fbcode/abc/autofdo.profile",+ "-Wl,--lto-whole-program-visibility",+ "-Wl,-mllvm,-llvm-flag2",+ "-Wl,-plugin-opt,O3",+ "-Wl,-plugin-opt,-function-sections",+ "-Wl,-mllvm,-hot-callsite-threshold=12000",+ "-shared",+ ]+ flags = _filter_flags(inputs)+ self.assertListEqual(+ flags,+ [+ "-O2",+ "-ffunction-sections",+ "-fdata-sections",+ "-mllvm",+ "-llvm_flag1",+ "-mllvm",+ "-llvm_flag1_different_format",+ "-fprofile-sample-use=/fbcode/abc/autofdo.profile",+ "-mllvm",+ "-llvm-flag2",+ "-O3",+ "-mllvm",+ "-hot-callsite-threshold=12000",+ "-fPIC",+ ],+ )++ def test_fbcc_prefix_end_tp2_with_log_fbcc(self):+ """TP2 toolchain: --log-fbcc is consumed by fbcc and included in prefix."""+ opt_args = [+ "--",+ "buck-out/fbcc",+ "--cc=fbcode/third-party-buck/platform010/build/llvm-fb/19/bin/clang++",+ "--log-fbcc=False",+ "--target=x86_64-redhat-linux-gnu",+ "-nostdinc",+ ]+ self.assertEqual(_fbcc_prefix_end(opt_args), 4)++ def test_fbcc_prefix_end_buckified_no_log_fbcc(self):+ """Buckified toolchain: --target is NOT consumed by fbcc and must be+ excluded from prefix to avoid breaking -cc1 mode."""+ opt_args = [+ "--",+ "buck-out/fbcc",+ "--cc=buck-out/v2/art/fbsource/third-party/llvm-fb/19/__build/bin/clang++__/out/clang++",+ "--target=x86_64-redhat-linux-gnu",+ "-nostdinc",+ "-nostdinc++",+ ]+ self.assertEqual(_fbcc_prefix_end(opt_args), 3)++ def test_fbcc_prefix_end_minimal(self):+ """Minimal case: only --cc= present."""+ opt_args = [+ "--",+ "buck-out/fbcc",+ "--cc=some/clang++",+ ]+ self.assertEqual(_fbcc_prefix_end(opt_args), 3)++ def test_fbcc_prefix_end_with_fbcc_debug_info(self):+ """--fbcc-create-external-debug-info is consumed by fbcc."""+ opt_args = [+ "--",+ "buck-out/fbcc",+ "--cc=some/clang++",+ "--fbcc-create-external-debug-info=/tmp/foo.dwo",+ "--target=x86_64-redhat-linux-gnu",+ ]+ self.assertEqual(_fbcc_prefix_end(opt_args), 4)++ def test_fbcc_prefix_end_multiple_consumed_flags(self):+ """Multiple fbcc-consumed flags in a row."""+ opt_args = [+ "--",+ "buck-out/fbcc",+ "--cc=some/clang++",+ "--log-fbcc=True",+ "--fbcc-create-external-debug-info=/tmp/foo.dwo",+ "--target=x86_64-redhat-linux-gnu",+ ]+ self.assertEqual(_fbcc_prefix_end(opt_args), 5)++ def test_filter_flags_hhvm_case_rev_0f8618f31(self):+ inputs = [+ "--target=x86_64-redhat-linux-gnu",+ "-nostdinc",+ "-resource-dir",+ "-idirafter",+ "-idirafter",+ "fbcode/third-party-buck/platform010/build/glibc/include",+ "-idirafter",+ "fbcode/third-party-buck/platform010/build/kernel-headers/include",+ "-Bfbcode/third-party-buck/platform010/build/binutils/x86_64-facebook-linux/bin",+ "--cflag=--target=x86_64-redhat-linux-gnu",+ "-Bfbcode/third-party-buck/platform010/build/glibc/lib",+ "-Bfbcode/third-party-buck/platform010/tools/gcc/lib/gcc/x86_64-redhat-linux-gnu/trunk",+ "-Lfbcode/third-party-buck/platform010/build/libgcc/lib/gcc/x86_64-facebook-linux/trunk",+ "-Wl,-nostdlib",+ "-Wl,--dynamic-linker,/usr/local/fbcode/platform010/lib/ld.so",+ "-Wl,--disable-new-dtags",+ "-Bfbcode/third-party-buck/platform010/build/binutils/x86_64-facebook-linux/bin",+ "-Wl,--no-mmap-output-file",+ "-nodefaultlibs",+ "--target=x86_64-redhat-linux-gnu",+ "-Lfbcode/third-party-buck/platform010/build/glibc/lib",+ "-Lfbcode/third-party-buck/platform010/build/libgcc/lib",+ "-Wl,-z,notext",+ "-Wl,-z,relro",+ "-Wl,--gc-sections",+ "-fuse-ld=lld",+ "-Wl,--discard-section=.nv_fatbin",+ "-Wl,--discard-section=.nvFatBinSegment",+ "-Wl,--discard-section=.rela.debug_info",+ "-Wl,--discard-section=.rela.debug_ranges",+ "-Wl,--discard-section=.rela.debug_loc",+ "-Wl,--discard-section=.rela.debug_line",+ "-Wl,--discard-section=.rela.debug_aranges",+ "-Wl,--discard-section=.rela.debug_types",+ "-Wl,-O1",+ "-Wl,--build-id=sha1",+ "-Wl,-mllvm,-hot-callsite-threshold=12000",+ "-Wl,--lto-whole-program-visibility",+ "-fwhole-program-vtables",+ "-Wl,--no-discard-section=.nv_fatbin",+ "-Wl,--no-discard-section=.nvFatBinSegment",+ "fbcode/tools/build/lib/move_gpu_sections_implicit_linker_script.txt",+ "-fuse-ld=lld",+ "--build-info=full",+ "--build-info-build-mode=opt-hhvm-lto",+ "--build-info-build-tool=buck2",+ "--build-info-compiler=clang",+ "--build-info-fdo-profile=",+ "--build-info-platform=platform010",+ "--build-info-rule=fbcode:scripts/fnz/minimal:minimal",+ "--build-info-rule-type=cpp_binary",+ "-flto=thin",+ "-Wl,-plugin-opt,-function-sections",+ "-Wl,-plugin-opt,-profile-guided-section-prefix=false",+ "-Wl,-plugin-opt,-generate-type-units",+ "-Wl,-plugin-opt,-enable-lto-ir-verification=false",+ "-Xlinker",+ "--export-dynamic-symbol=mallocx",+ "-Xlinker",+ "--export-dynamic-symbol=rallocx",+ "-Xlinker",+ "--export-dynamic-symbol=xallocx",+ "-Xlinker",+ "--export-dynamic-symbol=sallocx",+ "-Xlinker",+ "--export-dynamic-symbol=dallocx",+ "-Xlinker",+ "--export-dynamic-symbol=sdallocx",+ "-Xlinker",+ "--export-dynamic-symbol=nallocx",+ "-Xlinker",+ "--export-dynamic-symbol=mallctl",+ "-Xlinker",+ "--export-dynamic-symbol=mallctlnametomib",+ "-Xlinker",+ "--export-dynamic-symbol=mallctlbymib",+ "-Xlinker",+ "--export-dynamic-symbol=malloc_stats_print",+ "-Xlinker",+ "--export-dynamic-symbol=malloc_usable_size",+ "-Xlinker",+ "--export-dynamic-symbol=malloc_message",+ ]+ flags = _filter_flags(inputs)+ self.assertIsNotNone(flags)+ self.assertListEqual(+ flags,+ [+ "-O2",+ "-ffunction-sections",+ "-fdata-sections",+ "-fuse-ld=lld",+ "-mllvm",+ "-hot-callsite-threshold=12000",+ "-fwhole-program-vtables",+ "-fuse-ld=lld",+ "-mllvm",+ "-profile-guided-section-prefix=false",+ "-mllvm",+ "-generate-type-units",+ "-mllvm",+ "-enable-lto-ir-verification=false",+ ],+ )++ def test_filter_flags_unicorn_case_rev_0f8618f31(self):+ inputs = [+ "--cflag=--target=x86_64-redhat-linux-gnu",+ "-Bfbcode/third-party-buck/platform010/build/glibc/lib",+ "-Bfbcode/third-party-buck/platform010/tools/gcc/lib/gcc/x86_64-redhat-linux-gnu/trunk",+ "-Lfbcode/third-party-buck/platform010/build/libgcc/lib/gcc/x86_64-facebook-linux/trunk",+ "-Wl,-nostdlib",+ "-Wl,--dynamic-linker,/usr/local/fbcode/platform010/lib/ld.so",+ "-Wl,--disable-new-dtags",+ "-Bfbcode/third-party-buck/platform010/build/binutils/x86_64-facebook-linux/bin",+ "-Wl,--no-mmap-output-file",+ "-nodefaultlibs",+ "--target=x86_64-redhat-linux-gnu",+ "-Lfbcode/third-party-buck/platform010/build/glibc/lib",+ "-Lfbcode/third-party-buck/platform010/build/libgcc/lib",+ "-Wl,-z,notext",+ "-Wl,-z,relro",+ "-Wl,--gc-sections",+ "-fuse-ld=lld",+ "-Wl,--discard-section=.nv_fatbin",+ "-Wl,--discard-section=.nvFatBinSegment",+ "-Wl,--discard-section=.rela.debug_info",+ "-Wl,--discard-section=.rela.debug_ranges",+ "-Wl,--discard-section=.rela.debug_loc",+ "-Wl,--discard-section=.rela.debug_line",+ "-Wl,--discard-section=.rela.debug_aranges",+ "-Wl,--discard-section=.rela.debug_types",+ "-Wl,-O1",+ "-Wl,--build-id=sha1",+ "-Xlinker",+ "-znow",+ "-Xlinker",+ "--emit-relocs",+ "--build-info=full",+ "--build-info-build-mode=opt-clang-thinlto",+ "--build-info-build-tool=buck2",+ "--build-info-compiler=clang",+ "--build-info-fdo-profile=fbcode//fdo/autofdo/default_profile:autofdo",+ "--build-info-platform=platform010",+ "--build-info-rule=fbcode:unicorn:index_server",+ "--build-info-rule-type=cpp_binary",+ "-flto=thin",+ "-Wl,-plugin-opt,sample-profile=buck-out/v2/gen/fbcode/40fc99293b37c503/fdo/autofdo/default_profile/__autofdo__/out/profile",+ "-Wl,-plugin-opt,-function-sections",+ "-Wl,-plugin-opt,-profile-guided-section-prefix=false",+ "-Wl,-plugin-opt,-generate-type-units",+ "-Wl,-plugin-opt,-enable-lto-ir-verification=false",+ "-Xlinker",+ "--push-state",+ "-Xlinker",+ "--no-as-needed",+ "-Xlinker",+ "--pop-state",+ "-Wl,--undefined,Global",+ "-Wl,--undefined,Local",+ "-Wl,--undefined,MockConnection",+ "-Wl,--undefined,Global",+ "-Wl,--undefined,Local",+ "-Wl,--undefined,MockConnection",+ "-Xlinker",+ "--start-group",+ "fbcode/third-party-buck/platform010/build/IntelComposerXE/mkl/lib/intel64/libmkl_intel_lp64.a",+ "fbcode/third-party-buck/platform010/build/IntelComposerXE/mkl/lib/intel64/libmkl_core.a",+ "fbcode/third-party-buck/platform010/build/IntelComposerXE/mkl/lib/intel64/libmkl_intel_thread.a",+ "-Xlinker",+ "--end-group",+ "-lpthread",+ "-Xlinker",+ "--export-dynamic-symbol=mallocx",+ "-Xlinker",+ "--export-dynamic-symbol=rallocx",+ "-Xlinker",+ "--export-dynamic-symbol=xallocx",+ "-Xlinker",+ "--export-dynamic-symbol=sallocx",+ "-Xlinker",+ "--export-dynamic-symbol=dallocx",+ "-Xlinker",+ "--export-dynamic-symbol=sdallocx",+ "-Xlinker",+ "--export-dynamic-symbol=nallocx",+ "-Xlinker",+ "--export-dynamic-symbol=mallctl",+ "-Xlinker",+ "--export-dynamic-symbol=mallctlnametomib",+ "-Xlinker",+ "--export-dynamic-symbol=mallctlbymib",+ "-Xlinker",+ "--export-dynamic-symbol=malloc_stats_print",+ "-Xlinker",+ "--export-dynamic-symbol=malloc_usable_size",+ "-Xlinker",+ "--export-dynamic-symbol=malloc_message",+ ]+ flags = _filter_flags(inputs)+ self.assertIsNotNone(flags)+ self.assertListEqual(+ flags,+ [+ "-O2",+ "-ffunction-sections",+ "-fdata-sections",+ "-fuse-ld=lld",+ "-fprofile-sample-use=buck-out/v2/gen/fbcode/40fc99293b37c503/fdo/autofdo/default_profile/__autofdo__/out/profile",+ "-mllvm",+ "-profile-guided-section-prefix=false",+ "-mllvm",+ "-generate-type-units",+ "-mllvm",+ "-enable-lto-ir-verification=false",+ ],+ )
@@ -0,0 +1,104 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")+load("@prelude//utils:actions.bzl", "ActionExecutionAttributes")+load("@prelude//utils:arglike.bzl", "ArgLike") # @unused Used as a type+load(":debug.bzl", "SplitDebugMode")++def dwp_available(toolchain: CxxToolchainInfo):+ dwp = toolchain.binary_utilities_info.dwp+ split_debug_mode = toolchain.split_debug_mode+ return dwp != None and split_debug_mode != SplitDebugMode("none")++def run_dwp_action(+ ctx: AnalysisContext,+ toolchain: CxxToolchainInfo,+ obj: Artifact,+ identifier: [str, None],+ category_suffix: [str, None],+ referenced_objects: [ArgLike, list[Artifact]],+ dwp_output: Artifact,+ action_execution_properties: ActionExecutionAttributes = ActionExecutionAttributes(),+ from_exe = True,+):+ dwp = toolchain.binary_utilities_info.dwp++ if from_exe:+ args = cmd_args(+ [dwp, "-o", dwp_output.as_output(), "-e", obj] + getattr(ctx.attrs, "extra_dwp_flags", []),+ # All object/dwo files referenced in the library/executable are implicitly+ # processed by dwp.+ hidden = referenced_objects,+ )+ else:+ args = cmd_args(+ [dwp, "-o", dwp_output.as_output()] + getattr(ctx.attrs, "extra_dwp_flags", []),+ )+ argsfile, _ = ctx.actions.write(+ "dwp{}{}.argsfile".format(+ "_" + category_suffix if category_suffix else "",+ "_" + identifier if identifier else "",+ ),+ referenced_objects,+ allow_args = True,+ has_content_based_path = False,+ )+ args.add(cmd_args(argsfile, format = "@{}", hidden = referenced_objects))++ category = "dwp"+ if category_suffix != None:+ category += "_" + category_suffix++ ctx.actions.run(+ args,+ category = category,+ identifier = identifier,+ prefer_local = action_execution_properties.prefer_local,+ prefer_remote = action_execution_properties.prefer_remote,+ local_only = action_execution_properties.local_only,+ force_full_hybrid_if_capable = action_execution_properties.full_hybrid,+ # dwp merges the debug info of the corpus the link consumed and its+ # memory scales the same way, so share the link's local-slot weight.+ weight = toolchain.linker_info.link_weight,+ )++def dwp(+ ctx: AnalysisContext,+ toolchain: CxxToolchainInfo,+ # Executable/library to extra dwo paths from.+ obj: Artifact,+ # An identifier that will uniquely name this link action in the context of a category. Useful for+ # differentiating multiple link actions in the same rule.+ identifier: [str, None],+ # A category suffix that will be added to the category of the link action that is generated.+ category_suffix: [str, None],+ # All `.o`/`.dwo` paths referenced in `obj`.+ # TODO(T110378122): Ideally, referenced objects are a list of artifacts,+ # but currently we don't track them properly. So, we just pass in the full+ # link line and extract all inputs from that, which is a bit of an+ # overspecification.+ referenced_objects: [ArgLike, list[Artifact]],+ name_suffix: str = "",+ action_execution_properties: ActionExecutionAttributes = ActionExecutionAttributes(),+ from_exe = True,+) -> Artifact:+ # gdb/lldb expect to find a file named $file.dwp next to $file.+ output = ctx.actions.declare_output(obj.short_path + name_suffix + ".dwp", has_content_based_path = False)+ run_dwp_action(+ ctx,+ toolchain,+ obj,+ identifier,+ category_suffix,+ referenced_objects,+ output,+ action_execution_properties = action_execution_properties,+ from_exe = from_exe,+ )+ return output
@@ -0,0 +1,14 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++# Provider that exposes the .gcno files produced during compilation+GcnoFilesInfo = provider(+ fields = {+ "gcno_files": provider_field(list[Artifact]),+ }+)
@@ -0,0 +1,497 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//cxx:groups_types.bzl", "Traversal")+load("@prelude//linking:types.bzl", "Linkage")+load(+ "@prelude//utils:build_target_pattern.bzl",+ "BuildTargetPattern",+ "parse_build_target_pattern",+)+load(+ "@prelude//utils:graph_utils.bzl",+ "depth_first_traversal_by",+)+load(+ "@prelude//utils:strings.bzl",+ "strip_prefix",+)+load(+ "@prelude//utils:utils.bzl",+ "value_or",+)+load(+ ":groups_types.bzl",+ "Group",+ "GroupAttrs",+ "GroupDefinition",+ "GroupFilterInfo",+ "GroupMapping",+)++_VALID_ATTRS = [+ "enable_distributed_thinlto",+ "enable_if_node_count_exceeds",+ "discard_group",+ "linker_flags",+ "linker_script",+ "version_script",+ "exported_linker_flags",+ "link_execution_preference",+ "no_as_needed",+ "requires_root_node_exists",+ "prohibit_file_duplicates",+ "prefer_optimized_experimental",+]++# Traversal types in this list will only assign the node+# to a target (as opposed to the transitive deps of the node's tree).+_TRAVERSALS_TO_ASSIGN_NODE = [+ Traversal("node"),+ Traversal("subfolders"),+ # TODO (dust): Possible perf optimization:+ # When intersecting configured targets, it's not possible to intersect+ # a parent without also intersecting it's children.+ #+ # As a result, there's a possible perf optimization to assign 'tree'+ # to intersected targets instead, and leverage that to avoid traversing+ # the entire tree of every root.+ #+ # For example:+ # If iterating the tree of 'root2' we find a node which+ # was also present in 'root1', we can skip traversing the subtree+ # because it's evitable that everything is going to match there too.+ Traversal("intersect_any_roots"),+]++# Creates a group from an existing group, overwriting any properties provided+def create_group(+ group: Group,+ name: [None, str] = None,+ mappings: [None, list[GroupMapping]] = None,+ attrs: [None, GroupAttrs] = None,+ definition_type: [None, GroupDefinition] = None,+):+ return Group(+ name = value_or(name, group.name),+ mappings = value_or(mappings, group.mappings),+ attrs = value_or(attrs, group.attrs),+ definition_type = value_or(definition_type, group.definition_type),+ )++def get_roots_from_mapping(mapping):+ deps = mapping[0] if type(mapping[0]) == "list" else [mapping[0]]+ return filter(None, deps)++def parse_groups_definitions(+ map: list,+ # Function to parse a root label from the input type, allowing different+ # callers to have different top-level types for the `root`s.+ parse_root: typing.Callable = lambda d: d,+) -> list[Group]:+ groups = []+ group_names = set()+ for map_entry in map:+ name = map_entry[0]++ # Dedup the link group specs, take the deinition from the first definition+ if name in group_names:+ continue+ group_names.add(name)+ mappings = map_entry[1]+ attrs = (map_entry[2] or {}) if len(map_entry) > 2 else {}++ for attr in attrs:+ if attr not in _VALID_ATTRS:+ fail("invalid attr '{}' for link group '{}' found. Valid attributes are {}.".format(attr, name, _VALID_ATTRS))+ group_attrs = GroupAttrs(+ enable_distributed_thinlto = attrs.get("enable_distributed_thinlto", False),+ enable_if_node_count_exceeds = attrs.get("enable_if_node_count_exceeds", None),+ discard_group = attrs.get("discard_group", False),+ linker_flags = attrs.get("linker_flags", []),+ linker_script = attrs.get("linker_script", None),+ version_script = attrs.get("version_script", None),+ exported_linker_flags = attrs.get("exported_linker_flags", []),+ link_execution_preference = attrs.get("link_execution_preference", None),+ no_as_needed = attrs.get("no_as_needed", False),+ requires_root_node_exists = attrs.get("requires_root_node_exists", True),+ prohibit_file_duplicates = attrs.get("prohibit_file_duplicates", False),+ prefer_optimized_experimental = attrs.get("prefer_optimized_experimental", False),+ )++ parsed_mappings = []+ for entry in mappings:+ traversal = _parse_traversal_from_mapping(entry[1])+ mapping = GroupMapping(+ roots = filter(None, [parse_root(root) for root in get_roots_from_mapping(entry)]),+ traversal = traversal,+ filters = _parse_filter_from_mapping(entry[2]),+ preferred_linkage = Linkage(entry[3]) if len(entry) > 3 and entry[3] else None,+ )+ num_roots = len(mapping.roots) if mapping.roots else 0+ if num_roots > 1 and mapping.traversal != Traversal("intersect_any_roots"):+ fail("Invariant. A link_group mapping with traversal type: {} can only have 1 root node. {} found.".format(mapping.traversal, mapping.roots))+ elif mapping.traversal == Traversal("intersect_any_roots") and num_roots < 2:+ fail("Invariant. A link_group mapping with traversal type 'intersect' must have at least 2 root nodes. {} found.".format(mapping.roots))++ parsed_mappings.append(mapping)++ group = Group(+ name = name,+ mappings = parsed_mappings,+ attrs = group_attrs,+ definition_type = GroupDefinition("explicit"),+ )+ groups.append(group)++ return groups++def _parse_traversal_from_mapping(entry: str) -> Traversal:+ if entry == "tree":+ return Traversal("tree")+ elif entry == "node":+ return Traversal("node")+ elif entry == "subfolders":+ return Traversal("subfolders")+ elif entry == "intersect_any_roots":+ return Traversal("intersect_any_roots")+ else:+ fail("Unrecognized group traversal type: " + entry)++def _parse_filter(entry: str) -> GroupFilterInfo:+ for prefix in ("label:", "tag:"):+ label_regex = strip_prefix(prefix, entry)+ if label_regex != None:+ # We need the anchors "^"" and "$" because experimental_regex match+ # anywhere in the text, while we want full text match for group label+ # text.+ regex_expr = regex("^{}$".format(label_regex), fancy = False)++ def matches_regex(_r, _t, labels):+ return regex_expr.any_match(labels)++ return GroupFilterInfo(+ matches = matches_regex,+ info = {"regex": str(regex_expr)},+ )++ target_regex = strip_prefix("target_regex:", entry)+ if target_regex != None:+ regex_expr = regex("^{}$".format(target_regex), fancy = True)++ def matches_regex(_r, t, _labels):+ return regex_expr.match(str(t.raw_target()))++ return GroupFilterInfo(+ matches = matches_regex,+ info = {"target_regex": str(regex_expr)},+ )++ pattern = strip_prefix("pattern:", entry)+ if pattern != None:+ build_target_pattern = parse_build_target_pattern(pattern)++ def matches_target_pattern(_r, t, _labels):+ return build_target_pattern.matches(t)++ return GroupFilterInfo(+ matches = matches_target_pattern,+ info = _make_json_info_for_build_target_pattern(build_target_pattern),+ )++ fail("Invalid group mapping filter: {}\nFilter must begin with `label:`, `tag:`, `target_regex` or `pattern:`.".format(entry))++def _parse_filter_from_mapping(entry: [list[str | Dependency], str, Dependency, None]) -> list[GroupFilterInfo]:+ if type(entry) == type([]):+ return [_parse_filter(e) if isinstance(e, str) else e[GroupFilterInfo] for e in entry]+ elif isinstance(entry, Dependency):+ return [entry[GroupFilterInfo]]+ elif type(entry) == type(""):+ return [_parse_filter(entry)]+ return []++def compute_mappings(groups_map: dict[str, Group], graph_map: dict[Label, typing.Any]) -> dict[Label, str]:+ """+ Returns the group mappings {target label -> group name} based on the provided groups_map and graph.+ """+ if not groups_map:+ return {}++ target_to_group_map = {}+ node_traversed_targets = {}++ group_mappings_with_roots = []+ group_mappings_without_roots = []+ group_to_targets = {}++ groups = groups_map.values()+ for group in groups:+ for mapping in group.mappings:+ if mapping and not mapping.roots:+ group_mappings_without_roots.append((group, mapping))+ else:+ group_mappings_with_roots.append((group, mapping))++ # We assume there's more targets in the build graph then there are groups+ for target in graph_map:+ graph_node_labels = graph_map[target].labels+ for group, mapping in group_mappings_without_roots:+ all_match = True+ for filter in mapping.filters:+ if not filter.matches(None, target, graph_node_labels):+ all_match = False+ break+ if all_match:+ group_to_targets.setdefault(group.name, []).append((target, mapping))++ for group, mapping in group_mappings_with_roots:+ targets_in_mapping = _find_targets_in_mapping(graph_map, mapping)+ for target in targets_in_mapping:+ # If the target doesn't exist in our graph, skip the mapping.+ if target not in graph_map:+ continue+ group_to_targets.setdefault(group.name, []).append((target, mapping))++ for group in groups_map.values():+ for target, mapping in group_to_targets.get(group.name, []):+ _update_target_to_group_mapping(graph_map, target_to_group_map, node_traversed_targets, group, groups_map, mapping, target)++ return target_to_group_map++def get_dedupped_roots_from_groups(groups: list[Group]) -> list[Label]:+ roots = {}+ for group in groups:+ for mapping in group.mappings:+ if not mapping.roots:+ continue++ for root in mapping.roots:+ roots[root] = True++ return list(roots.keys())++def _find_targets_in_mapping(graph_map: dict[Label, typing.Any], mapping: GroupMapping) -> list[Label]:+ # If we have no filtering, we don't need to do any traversal to find targets to include.+ if not mapping.filters:+ if not mapping.roots:+ # Some link groups may want to partially define their mapping roots based on constraint+ # that potentially can be resolved to `None`.+ #+ # E.g:+ # ```+ # ("evict-mkl", [+ # (":mkl_ilp64_omp", "node", None, "shared"),+ # (select(+ # {"DEFAULT": None, "ovr_config//runtime:platform010": "//IntelComposerXE:mkl_ilp64_omp" }),+ # "node", None, "shared"+ # ),+ # ])+ # ```+ # Second mapping will be resolved to `(None, "node", None, "shared")` and will not handle anything.+ # There is no convenient way to gracefully handle that in user-facing link groups API.+ return []++ elif mapping.traversal != Traversal("intersect_any_roots"):+ return mapping.roots++ # Else find all dependencies that match the filter.+ matching_targets = {}++ def populate_matching_targets(node, root = None): # Label -> bool:+ graph_node = graph_map[node]++ # This callsite was migrated away from `lazy.is_any()`+ # because we saw a non-trivial increase in retained bytes+ # associated with the lambda required by the function.+ if mapping.filters:+ for filter in mapping.filters:+ if not filter.matches(root, node, graph_node.labels):+ # Filters can specify if they should stop once the first+ # non-match occurs.+ if filter.stop_at_first_non_match:+ return False+ return True++ matching_targets[node] = None+ if mapping.traversal == Traversal("tree"):+ # We can stop traversing the tree at this point because we've added the+ # build target to the list of all targets that will be traversed by the+ # algorithm that applies the groups.+ return False+ return True++ def populate_matching_targets_bfs_wrapper(node): # (Label) -> list+ if populate_matching_targets(node):+ graph_node = graph_map[node]+ return graph_node.deps + graph_node.exported_deps+ return []++ def populate_matching_targets_with_root(root, node): # (Label, Label) -> list+ if populate_matching_targets(node, root = root):+ graph_node = graph_map[node]+ return graph_node.deps + graph_node.exported_deps+ return []++ if not mapping.roots:+ for node in graph_map:+ populate_matching_targets(node)+ elif mapping.traversal == Traversal("intersect_any_roots"):+ targets_to_counter = {}+ for root in mapping.roots:+ # This is a captured variable inside `populate_matching_targets`.+ # We reset it for each root we visit so that we don't have results+ # from other roots.+ matching_targets = {}+ depth_first_traversal_by(graph_map, [root], partial(populate_matching_targets_with_root, root))+ for t in matching_targets:+ targets_to_counter[t] = targets_to_counter.get(t, 0) + 1++ return [t for t, count in targets_to_counter.items() if count > 1]+ else:+ if len(mapping.roots) == 1:+ matching_fn = partial(populate_matching_targets_with_root, mapping.roots[0])+ else:+ # When we have multiple roots there is no way to determine which+ # root is being traversed, so just set it to None.+ matching_fn = populate_matching_targets_bfs_wrapper++ depth_first_traversal_by(graph_map, mapping.roots, matching_fn)++ return matching_targets.keys()++# Extracted from `_update_target_to_group_mapping` to avoid function allocations inside the loop+def _assign_target_to_group(+ target_to_group_map, #: {"label": str}+ node_traversed_targets, #: {"label": None}+ group, # Group,+ groups_map, # {str: Group}+ mapping, # GroupMapping+ target, # Label+ node_traversal,+): # bool+ # If the target hasn't already been assigned to a group, assign it to the+ # first group claiming the target. Return whether the target was already assigned.+ if target not in target_to_group_map:+ if mapping.traversal == Traversal("subfolders"):+ generated_group_name = _generate_group_subfolder_name(group.name, target.package)+ _add_to_implicit_link_group(generated_group_name, group, groups_map, target_to_group_map, target)+ else:+ target_to_group_map[target] = group.name++ if node_traversal:+ node_traversed_targets[target] = None+ return False+ else:+ return True++# Extracted from `_update_target_to_group_mapping` to avoid function allocations inside the loop+def _transitively_add_targets_to_group_mapping(+ assign_target_to_group, # (Label, bool) -> bool+ node_traversed_targets, #: {"label": None}+ graph_map, # {"label": "_b"}+ node,+): # ([Label]) -> None+ previously_processed = assign_target_to_group(node, False)++ # If the node has been previously processed, and it was via tree (not node), all child nodes have been assigned+ if previously_processed and node not in node_traversed_targets:+ return None+ graph_node = graph_map[node]+ return graph_node.deps + graph_node.exported_deps++# Types removed to avoid unnecessary type checking which degrades performance.+def _update_target_to_group_mapping(+ graph_map, # {"label": "_b"}+ target_to_group_map, #: {"label": str}+ node_traversed_targets, #: {"label": None}+ group, # Group,+ groups_map, # {str: Group}+ mapping, # GroupMapping+ target,+): # Label+ assign_target_to_group = partial(_assign_target_to_group, target_to_group_map, node_traversed_targets, group, groups_map, mapping) # (Label, bool) -> bool+ transitively_add_targets_to_group_mapping = partial(+ _transitively_add_targets_to_group_mapping, assign_target_to_group, node_traversed_targets, graph_map+ ) # (Label) -> list[Label]++ if mapping.traversal in _TRAVERSALS_TO_ASSIGN_NODE:+ assign_target_to_group(target, True)+ else: # tree+ depth_first_traversal_by(graph_map, [target], transitively_add_targets_to_group_mapping)++def _add_to_implicit_link_group(+ generated_group_name, # str+ group, # Group+ groups_map, # {str: Group}+ target_to_group_map, # {Label: str}+ target,+): # Label+ target_to_group_map[target] = generated_group_name+ if generated_group_name not in groups_map:+ groups_map[generated_group_name] = create_group(+ group = group,+ name = generated_group_name,+ definition_type = GroupDefinition("implicit"),+ )+ elif groups_map[generated_group_name].definition_type == GroupDefinition("explicit"):+ hashed_group_name = _hash_group_name(group.name, generated_group_name)+ _add_to_implicit_link_group(hashed_group_name, group, groups_map, target_to_group_map, target)++def _generate_group_subfolder_name(+ group, # str,+ package,+): # str+ """Dynamically generating link group name for "subfolders" traversal."""+ name = group + "_" + package.replace("/", "_")++ if len(name) > 246:+ # Maximum filename size in unix is 255.+ # We prefix all libraries with "lib" (3 symbols) and suffix with ".dylib" (6 symbols) or ".so" (3 symbols).+ # Assuming ".dylib" suffix cause it's the longest, we can allow (255 - 3 - 6) = 246 symbols for the rest of the name.+ name = _hash_group_name(group, name)+ return name++def _hash_group_name(prefix: str, name: str) -> str:+ """+ Creates new name via simple hashing.+ Hash algorithm is stable in starlark: https://fburl.com/code/ptegkov6+ """+ return "{}_{}".format(prefix, str(hash(name)))++def _make_json_info_for_build_target_pattern(build_target_pattern: BuildTargetPattern) -> dict[str, typing.Any]:+ # `BuildTargetPattern` contains lambdas which are not serializable, so+ # have to generate the JSON representation+ return {+ "cell": build_target_pattern.cell,+ "kind": build_target_pattern.kind,+ "name": build_target_pattern.name,+ "path": build_target_pattern.path,+ }++def _make_json_info_for_group_mapping(group_mapping: GroupMapping) -> dict[str, typing.Any]:+ return {+ "filters": [filter.info for filter in group_mapping.filters],+ "preferred_linkage": group_mapping.preferred_linkage,+ "roots": group_mapping.roots,+ "traversal": group_mapping.traversal,+ }++def _make_json_info_for_group(group: Group) -> dict[str, typing.Any]:+ return {+ "attrs": group.attrs,+ "mappings": [_make_json_info_for_group_mapping(mapping) for mapping in group.mappings],+ "name": group.name,+ }++def make_info_subtarget_providers(ctx: AnalysisContext, groups: list[Group], mappings: dict[Label, str]) -> list[Provider]:+ info_json = {+ "groups": {group.name: _make_json_info_for_group(group) for group in groups},+ "mappings": mappings,+ }+ json_output = ctx.actions.write_json("link_group_map_info.json", info_json, pretty = True, has_content_based_path = False)+ return [DefaultInfo(default_output = json_output)]
@@ -0,0 +1,121 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is dual-licensed under either the MIT license found in the+# LICENSE-MIT file in the root directory of this source tree or the Apache+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory+# of this source tree. You may select, at your option, one of the+# above-listed licenses.++load("@prelude//linking:types.bzl", "Linkage")++# Label for special group mapping which makes every target associated with it to be included in all groups+MATCH_ALL_LABEL = "MATCH_ALL"++# Label for special group mapping which makes every target associated with it to be linked directly+# against the final binary+NO_MATCH_LABEL = "NO_MATCH"++# Label for special group mapping which causes every target associated with it to be included+# in any groups that contain any targets with direct dependencies on it.+# Sample use case: Vendor-supplied shared libraries that are used from multiple link-groups.+MATCH_DIRECT_DEPS_LABEL = "MATCH_DIRECT_DEPS"++Traversal = enum(+ # Includes the target and all of it's transitive dependencies in the group.+ "tree",+ # Includes only the target in the group.+ "node",+ # Uses pattern and separates all targets by full folder path.+ "subfolders",+ # Includes targets found in the transitive deps of *any* roots.+ # Filters for these mappings will be applied to the intersected deps.+ "intersect_any_roots",+)++GroupFilterInfo = provider(+ fields = {+ # What should be dumped in the link-groups-info subtarget.+ "info": provider_field(dict[str, typing.Any]),+ # A function which is given an optional root label, a target label and+ # a list of its labels returns if the target label matches.+ "matches": provider_field(typing.Callable[[[Label, None], Label, list[str]], bool]),+ # If the matching should stop once the filter no longer matches.+ "stop_at_first_non_match": provider_field(bool, default = False),+ },+)++# Representation of a parsed group mapping+GroupMapping = record(+ # The root to apply this mapping to.+ roots = field(list[Label], []),+ # The type of traversal to use.+ traversal = field(Traversal, Traversal("tree")),+ # Optional filter type to apply to the traversal.+ filters = field(list[GroupFilterInfo], []),+ # Preferred linkage for this target when added to a link group.+ preferred_linkage = field([Linkage, None], None),+)++# Representation of group attributes+GroupAttrs = record(+ # Use distributed thinlto to build the link group shared library.+ enable_distributed_thinlto = field(bool, False),+ # Enable this link group if the binary's node count exceeds the given threshold+ enable_if_node_count_exceeds = field([int, None], None),+ # Discard all dependencies in the link group, useful for dropping unused dependencies+ # from the build graph.+ discard_group = field(bool, False),+ # Adds additional linker flags used to link the link group shared object.+ linker_flags = field(list[typing.Any], []),+ # Passes a linker script to the link group shared library's link command.+ linker_script = field([Artifact, None], None),+ # Passes a version script to the link group shared library's link command.+ # Tagging a group's symbols with a version keeps them from satisfying an+ # identically-named *versioned* reference in another copy of the same library+ # loaded into the process, which is otherwise allowed: glibc lets an+ # unversioned definition satisfy a versioned reference, so whichever copy+ # reaches the global scope first captures the other.+ version_script = field([Artifact, None], None),+ # Adds additional linker flags to apply to dependents that link against the+ # link group's shared object.+ exported_linker_flags = field(list[typing.Any], []),+ # Controls link execution location: "any" (default), "full_hybrid", "local",+ # "local_only", or "remote".+ link_execution_preference = field([str, None, typing.Any], None),+ # Wraps the link group shared library with `--no-as-needed/--as-needed`,+ # used for link groups that are required at runtime but not statically referenced.+ # Only applicable to gnu.+ no_as_needed = field(bool, False),+ # Requires root nodes in specs to always exist in dependency graph.+ # Otherwise fails.+ requires_root_node_exists = field(bool, True),+ # For certain wide-scale generic link groups we want to enable+ # initial duplicate analysis. This is useful for detecting dduplicated symbols problem early+ # for automatoc link groups that we not aware about (e.g. evicting whole root package folder into link group)+ prohibit_file_duplicates = field(bool, False),+ # Uses optimized compilation outputs if available.+ prefer_optimized_experimental = field(bool, False),+)++# Types of group traversal+GroupDefinition = enum(+ # Group is explicitly defined in mapping provided by user.+ # That is the default behavior.+ "explicit",+ # Group is implicitly created during mapping computations.+ # For example, group can be created for "subfolders" traversal.+ "implicit",+)++# Representation of a parsed group+Group = record(+ # The name for this group.+ name = str,+ # The mappings that are part of this group.+ mappings = list[GroupMapping],+ attrs = GroupAttrs,+ definition_type = field(GroupDefinition, GroupDefinition("explicit")),+)++def should_discard_group(group: [Group, None]) -> bool:+ return group != None and group.attrs.discard_group
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff