fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
69ca2611
0.5.0
1# Copyright 2018 The Bazel Authors. All rights reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""Functionality for constructing actions that invoke the Rust compiler""" 16 17load ( 18"@bazel_tools//tools/build_defs/cc:action_names.bzl" , 19"CPP_LINK_EXECUTABLE_ACTION_NAME" , 20) 21load ( "//rust/private:common.bzl" , "rust_common" ) 22load ( "//rust/private:providers.bzl" , _BuildInfo = "BuildInfo" ) 23load ( "//rust/private:stamp.bzl" , "is_stamping_enabled" ) 24load ( 25"//rust/private:utils.bzl" , 26"abs" , 27"expand_dict_value_locations" , 28"expand_list_element_locations" , 29"find_cc_toolchain" , 30"get_lib_name" , 31"get_preferred_artifact" , 32"is_exec_configuration" , 33"make_static_lib_symlink" , 34"relativize" , 35) 36 37BuildInfo = _BuildInfo 38 39AliasableDepInfo = provider ( 40doc = "A provider mapping an alias name to a Crate's information." , 41fields = { 42"dep" : "CrateInfo" , 43"name" : "str" , 44}, 45) 46 47_error_format_values = [ "human" , "json" , "short" ] 48 49ErrorFormatInfo = provider ( 50doc = "Set the --error-format flag for all rustc invocations" , 51fields = { "error_format" : "(string) [" + ", " . join ( _error_format_values ) + "]" }, 52) 53 54ExtraRustcFlagsInfo = provider ( 55doc = "Pass each value as an additional flag to non-exec rustc invocations" , 56fields = { "extra_rustc_flags" : "List[string] Extra flags to pass to rustc in non-exec configuration" }, 57) 58 59ExtraExecRustcFlagsInfo = provider ( 60doc = "Pass each value as an additional flag to exec rustc invocations" , 61fields = { "extra_exec_rustc_flags" : "List[string] Extra flags to pass to rustc in exec configuration" }, 62) 63 64def _get_rustc_env ( attr , toolchain , crate_name ): 65"""Gathers rustc environment variables 66 67Args: 68attr (struct): The current target's attributes 69toolchain (rust_toolchain): The current target's rust toolchain context 70crate_name (str): The name of the crate to be compiled 71 72Returns: 73dict: Rustc environment variables 74""" 75version = attr . version if hasattr ( attr , "version" ) else "0.0.0" 76major , minor , patch = version . split ( "." , 2 ) 77if "-" in patch : 78patch , pre = patch . split ( "-" , 1 ) 79else : 80pre = "" 81return { 82"CARGO_CFG_TARGET_ARCH" : toolchain . target_arch , 83"CARGO_CFG_TARGET_OS" : toolchain . os , 84"CARGO_CRATE_NAME" : crate_name , 85"CARGO_PKG_AUTHORS" : "" , 86"CARGO_PKG_DESCRIPTION" : "" , 87"CARGO_PKG_HOMEPAGE" : "" , 88"CARGO_PKG_NAME" : attr . name , 89"CARGO_PKG_VERSION" : version , 90"CARGO_PKG_VERSION_MAJOR" : major , 91"CARGO_PKG_VERSION_MINOR" : minor , 92"CARGO_PKG_VERSION_PATCH" : patch , 93"CARGO_PKG_VERSION_PRE" : pre , 94} 95 96def get_compilation_mode_opts ( ctx , toolchain ): 97"""Gathers rustc flags for the current compilation mode (opt/debug) 98 99Args: 100ctx (ctx): The current rule's context object 101toolchain (rust_toolchain): The current rule's `rust_toolchain` 102 103Returns: 104struct: See `_rust_toolchain_impl` for more details 105""" 106comp_mode = ctx . var [ "COMPILATION_MODE" ] 107if not comp_mode in toolchain . compilation_mode_opts : 108fail ( "Unrecognized compilation mode {} for toolchain." . format ( comp_mode )) 109 110return toolchain . compilation_mode_opts [ comp_mode ] 111 112def _are_linkstamps_supported ( feature_configuration , has_grep_includes ): 113# Are linkstamps supported by the C++ toolchain? 114return ( cc_common . is_enabled ( feature_configuration = feature_configuration , feature_name = "linkstamps" ) and 115# Is Bazel recent enough to support Starlark linkstamps? 116hasattr ( cc_common , "register_linkstamp_compile_action" ) and 117# The current rule doesn't define _grep_includes attribute; this 118# attribute is required for compiling linkstamps. 119has_grep_includes ) 120 121def _should_use_pic ( cc_toolchain , feature_configuration , crate_type ): 122if crate_type in ( "cdylib" , "dylib" ): 123return cc_toolchain . needs_pic_for_dynamic_libraries ( feature_configuration = feature_configuration ) 124return False 125 126def collect_deps ( 127deps , 128proc_macro_deps , 129aliases , 130are_linkstamps_supported = False ): 131"""Walks through dependencies and collects the transitive dependencies. 132 133Args: 134deps (list): The deps from ctx.attr.deps. 135proc_macro_deps (list): The proc_macro deps from ctx.attr.proc_macro_deps. 136aliases (dict): A dict mapping aliased targets to their actual Crate information. 137are_linkstamps_supported (bool): Whether the current rule and the toolchain support building linkstamps.. 138 139Returns: 140tuple: Returns a tuple of: 141DepInfo, 142BuildInfo, 143linkstamps (depset[CcLinkstamp]): A depset of CcLinkstamps that need to be compiled and linked into all linked binaries. 144 145""" 146direct_crates = [] 147transitive_crates = [] 148transitive_noncrates = [] 149transitive_build_infos = [] 150transitive_link_search_paths = [] 151build_info = None 152linkstamps = [] 153transitive_crate_outputs = [] 154 155aliases = { k . label : v for k , v in aliases . items ()} 156for dep in depset ( transitive = [ deps , proc_macro_deps ]). to_list (): 157( crate_info , dep_info ) = _get_crate_and_dep_info ( dep ) 158cc_info = _get_cc_info ( dep ) 159dep_build_info = _get_build_info ( dep ) 160 161if cc_info and are_linkstamps_supported : 162linkstamps . append ( cc_info . linking_context . linkstamps ()) 163 164if crate_info : 165# This dependency is a rust_library 166 167# When crate_info.owner is set, we use it. When the dep type is Target we get the 168# label from dep.label 169owner = getattr ( crate_info , "owner" , dep . label if type ( dep ) == "Target" else None ) 170 171direct_crates . append ( AliasableDepInfo ( 172name = aliases . get ( owner , crate_info . name ), 173dep = crate_info , 174)) 175 176transitive_crates . append ( 177depset ( 178[ crate_info ], 179transitive = [] if "proc-macro" in [ 180crate_info . type , 181crate_info . wrapped_crate_type , 182] else [ dep_info . transitive_crates ], 183), 184) 185transitive_crate_outputs . append ( 186depset ( 187[ crate_info . output ], 188transitive = [] if "proc-macro" in [ 189crate_info . type , 190crate_info . wrapped_crate_type , 191] else [ dep_info . transitive_crate_outputs ], 192), 193) 194 195if "proc-macro" not in [ crate_info . type , crate_info . wrapped_crate_type ]: 196transitive_noncrates . append ( dep_info . transitive_noncrates ) 197transitive_build_infos . append ( dep_info . transitive_build_infos ) 198transitive_link_search_paths . append ( dep_info . link_search_path_files ) 199 200elif cc_info : 201# This dependency is a cc_library 202transitive_noncrates . append ( cc_info . linking_context . linker_inputs ) 203elif dep_build_info : 204if build_info : 205fail ( "Several deps are providing build information, " + 206"only one is allowed in the dependencies" ) 207build_info = dep_build_info 208transitive_build_infos . append ( depset ([ build_info ])) 209transitive_link_search_paths . append ( depset ([ build_info . link_search_paths ])) 210else : 211fail ( "rust targets can only depend on rust_library, rust_*_library or cc_library " + 212"targets." ) 213 214transitive_crates_depset = depset ( transitive = transitive_crates ) 215 216return ( 217rust_common . dep_info ( 218direct_crates = depset ( direct_crates ), 219transitive_crates = transitive_crates_depset , 220transitive_noncrates = depset ( 221transitive = transitive_noncrates , 222order = "topological" , #dylib link flag ordering matters . 223), 224transitive_crate_outputs = depset ( transitive = transitive_crate_outputs ), 225transitive_build_infos = depset ( transitive = transitive_build_infos ), 226link_search_path_files = depset ( transitive = transitive_link_search_paths ), 227dep_env = build_info . dep_env if build_info else None , 228), 229build_info , 230depset ( transitive = linkstamps ), 231) 232 233def _collect_libs_from_linker_inputs ( linker_inputs , use_pic ): 234# TODO: We could let the user choose how to link, instead of always preferring to link static libraries. 235return [ 236get_preferred_artifact ( lib , use_pic ) 237for li in linker_inputs 238for lib in li . libraries 239] 240 241def _get_crate_and_dep_info ( dep ): 242if type ( dep ) == "Target" and rust_common . crate_info in dep : 243return ( dep [ rust_common . crate_info ], dep [ rust_common . dep_info ]) 244elif type ( dep ) == "struct" and hasattr ( dep , "crate_info" ): 245return ( dep . crate_info , dep . dep_info ) 246return ( None , None ) 247 248def _get_cc_info ( dep ): 249if type ( dep ) == "Target" and CcInfo in dep : 250return dep [ CcInfo ] 251elif type ( dep ) == "struct" and hasattr ( dep , "cc_info" ): 252return dep . cc_info 253return None 254 255def _get_build_info ( dep ): 256if type ( dep ) == "Target" and BuildInfo in dep : 257return dep [ BuildInfo ] 258elif type ( dep ) == "struct" and hasattr ( dep , "build_info" ): 259return dep . build_info 260return None 261 262def get_cc_user_link_flags ( ctx ): 263"""Get the current target's linkopt flags 264 265Args: 266ctx (ctx): The current rule's context object 267 268Returns: 269depset: The flags passed to Bazel by --linkopt option. 270""" 271return ctx . fragments . cpp . linkopts 272 273def get_linker_and_args ( ctx , attr , cc_toolchain , feature_configuration , rpaths ): 274"""Gathers cc_common linker information 275 276Args: 277ctx (ctx): The current target's context object 278attr (struct): Attributes to use in gathering linker args 279cc_toolchain (CcToolchain): cc_toolchain for which we are creating build variables. 280feature_configuration (FeatureConfiguration): Feature configuration to be queried. 281rpaths (depset): Depset of directories where loader will look for libraries at runtime. 282 283 284Returns: 285tuple: A tuple of the following items: 286- (str): The tool path for given action. 287- (sequence): A flattened command line flags for given action. 288- (dict): Environment variables to be set for given action. 289""" 290user_link_flags = get_cc_user_link_flags ( ctx ) 291 292# Add linkopt's from dependencies. This includes linkopts from transitive 293# dependencies since they get merged up. 294for dep in getattr ( attr , "deps" , []): 295if CcInfo in dep and dep [ CcInfo ]. linking_context : 296for linker_input in dep [ CcInfo ]. linking_context . linker_inputs . to_list (): 297for flag in linker_input . user_link_flags : 298user_link_flags . append ( flag ) 299link_variables = cc_common . create_link_variables ( 300feature_configuration = feature_configuration , 301cc_toolchain = cc_toolchain , 302is_linking_dynamic_library = False , 303runtime_library_search_directories = rpaths , 304user_link_flags = user_link_flags , 305) 306link_args = cc_common . get_memory_inefficient_command_line ( 307feature_configuration = feature_configuration , 308action_name = CPP_LINK_EXECUTABLE_ACTION_NAME , 309variables = link_variables , 310) 311link_env = cc_common . get_environment_variables ( 312feature_configuration = feature_configuration , 313action_name = CPP_LINK_EXECUTABLE_ACTION_NAME , 314variables = link_variables , 315) 316ld = cc_common . get_tool_for_action ( 317feature_configuration = feature_configuration , 318action_name = CPP_LINK_EXECUTABLE_ACTION_NAME , 319) 320 321return ld , link_args , link_env 322 323def _process_build_scripts ( 324build_info , 325dep_info , 326compile_inputs ): 327"""Gathers the outputs from a target's `cargo_build_script` action. 328 329Args: 330build_info (BuildInfo): The target Build's dependency info. 331dep_info (DepInfo): The Depinfo provider form the target Crate's set of inputs. 332compile_inputs (depset): A set of all files that will participate in the build. 333 334Returns: 335tuple: A tuple: A tuple of the following items: 336- (depset[File]): A list of all build info `OUT_DIR` File objects 337- (str): The `OUT_DIR` of the current build info 338- (File): An optional path to a generated environment file from a `cargo_build_script` target 339- (depset[File]): All direct and transitive build flags from the current build info. 340""" 341extra_inputs , out_dir , build_env_file , build_flags_files = _create_extra_input_args ( build_info , dep_info ) 342compile_inputs = depset ( transitive = [ extra_inputs , compile_inputs ]) 343return compile_inputs , out_dir , build_env_file , build_flags_files 344 345def _symlink_for_ambiguous_lib ( actions , toolchain , crate_info , lib ): 346"""Constructs a disambiguating symlink for a library dependency. 347 348Args: 349actions (Actions): The rule's context actions object. 350toolchain: The Rust toolchain object. 351crate_info (CrateInfo): The target crate's info. 352lib (File): The library to symlink to. 353 354Returns: 355(File): The disambiguating symlink for the library. 356""" 357# FIXME: Once the relative order part of the native-link-modifiers rustc 358# feature is stable, we should be able to eliminate the need to construct 359# symlinks by passing the full paths to the libraries. 360# https://github.com/rust-lang/rust/issues/81490. 361 362# Take the absolute value of hash() since it could be negative. 363path_hash = abs ( hash ( lib . path )) 364lib_name = get_lib_name ( lib ) 365 366prefix = "lib" 367extension = ".a" 368if toolchain . os . startswith ( "windows" ): 369prefix = "" 370extension = ".lib" 371 372# Ensure the symlink follows the lib<name>.a pattern on Unix-like platforms 373# or <name>.lib on Windows. 374# Add a hash of the original library path to disambiguate libraries with the same basename. 375symlink_name = "{}{}-{}{}" . format ( prefix , lib_name , path_hash , extension ) 376 377# Add the symlink to a target crate-specific _ambiguous_libs/ subfolder, 378# to avoid possible collisions with sibling crates that may depend on the 379# same ambiguous libraries. 380symlink = actions . declare_file ( "_ambiguous_libs/" + crate_info . output . basename + "/" + symlink_name ) 381actions . symlink ( 382output = symlink , 383target_file = lib , 384progress_message = "Creating symlink to ambiguous lib: {}" . format ( lib . path ), 385) 386return symlink 387 388def _disambiguate_libs ( actions , toolchain , crate_info , dep_info , use_pic ): 389"""Constructs disambiguating symlinks for ambiguous library dependencies. 390 391The symlinks are all created in a _ambiguous_libs/ subfolder specific to 392the target crate to avoid possible collisions with sibling crates that may 393depend on the same ambiguous libraries. 394 395Args: 396actions (Actions): The rule's context actions object. 397toolchain: The Rust toolchain object. 398crate_info (CrateInfo): The target crate's info. 399dep_info: (DepInfo): The target crate's dependency info. 400use_pic: (boolean): Whether the build should use PIC. 401 402Returns: 403dict[String, File]: A mapping from ambiguous library paths to their 404disambiguating symlink. 405""" 406# FIXME: Once the relative order part of the native-link-modifiers rustc 407# feature is stable, we should be able to eliminate the need to construct 408# symlinks by passing the full paths to the libraries. 409# https://github.com/rust-lang/rust/issues/81490. 410 411# A dictionary from file paths of ambiguous libraries to the corresponding 412# symlink. 413ambiguous_libs = {} 414 415# A dictionary maintaining a mapping from preferred library name to the 416# last visited artifact with that name. 417visited_libs = {} 418for link_input in dep_info . transitive_noncrates . to_list (): 419for lib in link_input . libraries : 420# FIXME: Dynamic libs are not disambiguated right now, there are 421# cases where those have a non-standard name with version (e.g., 422# //test/unit/versioned_libs). We hope that the link modifiers 423# stabilization will come before we need to make this work. 424if _is_dylib ( lib ): 425 continue 426artifact = get_preferred_artifact ( lib , use_pic ) 427name = get_lib_name ( artifact ) 428 429# On Linux-like platforms, normally library base names start with 430# `lib`, following the pattern `lib[name].(a|lo)` and we pass 431# -lstatic=name. 432# On Windows, the base name looks like `name.lib` and we pass 433# -lstatic=name. 434# FIXME: Under the native-link-modifiers unstable rustc feature, 435# we could use -lstatic:+verbatim instead. 436needs_symlink_to_standardize_name = ( 437( toolchain . os . startswith ( "linux" ) or toolchain . os . startswith ( "mac" ) or toolchain . os . startswith ( "darwin" )) and 438artifact . basename . endswith ( ".a" ) and not artifact . basename . startswith ( "lib" ) 439) or ( 440toolchain . os . startswith ( "windows" ) and not artifact . basename . endswith ( ".lib" ) 441) 442 443# Detect cases where we need to disambiguate library dependencies 444# by constructing symlinks. 445if ( 446needs_symlink_to_standardize_name or 447# We have multiple libraries with the same name. 448( name in visited_libs and visited_libs [ name ]. path != artifact . path ) 449): 450# Disambiguate the previously visited library (if we just detected 451# that it is ambiguous) and the current library. 452if name in visited_libs : 453old_path = visited_libs [ name ]. path 454if old_path not in ambiguous_libs : 455ambiguous_libs [ old_path ] = _symlink_for_ambiguous_lib ( actions , toolchain , crate_info , visited_libs [ name ]) 456ambiguous_libs [ artifact . path ] = _symlink_for_ambiguous_lib ( actions , toolchain , crate_info , artifact ) 457 458visited_libs [ name ] = artifact 459return ambiguous_libs 460 461def collect_inputs ( 462ctx , 463file , 464files , 465linkstamps , 466toolchain , 467cc_toolchain , 468feature_configuration , 469crate_info , 470dep_info , 471build_info , 472stamp = False ): 473"""Gather's the inputs and required input information for a rustc action 474 475Args: 476ctx (ctx): The rule's context object. 477file (struct): A struct containing files defined in label type attributes marked as `allow_single_file`. 478files (list): A list of all inputs (`ctx.files`). 479linkstamps (depset): A depset of CcLinkstamps that need to be compiled and linked into all linked binaries. 480toolchain (rust_toolchain): The current `rust_toolchain`. 481cc_toolchain (CcToolchainInfo): The current `cc_toolchain`. 482feature_configuration (FeatureConfiguration): Feature configuration to be queried. 483crate_info (CrateInfo): The Crate information of the crate to process build scripts for. 484dep_info (DepInfo): The target Crate's dependency information. 485build_info (BuildInfo): The target Crate's build settings. 486stamp (bool, optional): Whether or not workspace status stamping is enabled. For more details see 487https://docs.bazel.build/versions/main/user-manual.html#flag--stamp 488 489Returns: 490tuple: A tuple: A tuple of the following items: 491- (list): A list of all build info `OUT_DIR` File objects 492- (str): The `OUT_DIR` of the current build info 493- (File): An optional path to a generated environment file from a `cargo_build_script` target 494- (depset[File]): All direct and transitive build flag files from the current build info 495- (list[File]): Linkstamp outputs 496- (dict[String, File]): Ambiguous libs, see `_disambiguate_libs`. 497""" 498linker_script = getattr ( file , "linker_script" ) if hasattr ( file , "linker_script" ) else None 499 500linker_depset = cc_toolchain . all_files 501 502use_pic = _should_use_pic ( cc_toolchain , feature_configuration , crate_info . type ) 503 504# Pass linker inputs only for linking-like actions, not for example where 505# the output is rlib. This avoids quadratic behavior where transitive noncrates are 506# flattened on each transitive rust_library dependency. 507additional_transitive_inputs = [] 508ambiguous_libs = {} 509if crate_info . type in ( "staticlib" , "proc-macro" ): 510additional_transitive_inputs = _collect_libs_from_linker_inputs ( 511dep_info . transitive_noncrates . to_list (), 512use_pic , 513) 514elif crate_info . type in ( "bin" , "dylib" , "cdylib" ): 515linker_inputs = dep_info . transitive_noncrates . to_list () 516ambiguous_libs = _disambiguate_libs ( ctx . actions , toolchain , crate_info , dep_info , use_pic ) 517additional_transitive_inputs = _collect_libs_from_linker_inputs ( linker_inputs , use_pic ) + [ 518additional_input 519for linker_input in linker_inputs 520for additional_input in linker_input . additional_inputs 521] + ambiguous_libs . values () 522 523# Compute linkstamps. Use the inputs of the binary as inputs to the 524# linkstamp action to ensure linkstamps are rebuilt whenever binary inputs 525# change. 526linkstamp_outs = [] 527 528nolinkstamp_compile_inputs = depset ( 529getattr ( files , "data" , []) + 530([ build_info . rustc_env , build_info . flags ] if build_info else []) + 531([ toolchain . target_json ] if toolchain . target_json else []) + 532([] if linker_script == None else [ linker_script ]), 533transitive = [ 534linker_depset , 535crate_info . srcs , 536dep_info . transitive_crate_outputs , 537depset ( additional_transitive_inputs ), 538crate_info . compile_data , 539toolchain . all_files , 540], 541) 542 543if crate_info . type in ( "bin" , "cdylib" ): 544# There is no other way to register an action for each member of a depset than 545# flattening the depset as of 2021-10-12. Luckily, usually there is only one linkstamp 546# in a build, and we only flatten the list on binary targets that perform transitive linking, 547# so it's extremely unlikely that this call to `to_list()` will ever be a performance 548# problem. 549for linkstamp in linkstamps . to_list (): 550# The linkstamp output path is based on the binary crate 551# name and the input linkstamp path. This is to disambiguate 552# the linkstamp outputs produced by multiple binary crates 553# that depend on the same linkstamp. We use the same pattern 554# for the output name as the one used by native cc rules. 555out_name = "_objs/" + crate_info . output . basename + "/" + linkstamp . file (). path [: - len ( linkstamp . file (). extension )] + "o" 556linkstamp_out = ctx . actions . declare_file ( out_name ) 557linkstamp_outs . append ( linkstamp_out ) 558cc_common . register_linkstamp_compile_action ( 559actions = ctx . actions , 560cc_toolchain = cc_toolchain , 561feature_configuration = feature_configuration , 562grep_includes = ctx . file . _grep_includes , 563source_file = linkstamp . file (), 564output_file = linkstamp_out , 565compilation_inputs = linkstamp . hdrs (), 566inputs_for_validation = nolinkstamp_compile_inputs , 567label_replacement = str ( ctx . label ), 568output_replacement = crate_info . output . path , 569) 570 571# If stamping is enabled include the volatile status info file 572stamp_info = [ ctx . version_file ] if stamp else [] 573 574compile_inputs = depset ( 575linkstamp_outs + stamp_info , 576transitive = [ 577nolinkstamp_compile_inputs , 578], 579) 580 581build_env_files = getattr ( files , "rustc_env_files" , []) 582compile_inputs , out_dir , build_env_file , build_flags_files = _process_build_scripts ( build_info , dep_info , compile_inputs ) 583if build_env_file : 584build_env_files = [ f for f in build_env_files ] + [ build_env_file ] 585compile_inputs = depset ( build_env_files , transitive = [ compile_inputs ]) 586 587return compile_inputs , out_dir , build_env_files , build_flags_files , linkstamp_outs , ambiguous_libs 588 589def construct_arguments ( 590ctx , 591attr , 592file , 593toolchain , 594tool_path , 595cc_toolchain , 596feature_configuration , 597crate_info , 598dep_info , 599linkstamp_outs , 600ambiguous_libs , 601output_hash , 602rust_flags , 603out_dir , 604build_env_files , 605build_flags_files , 606emit = [ "dep-info" , "link" ], 607force_all_deps_direct = False , 608force_link = False , 609stamp = False , 610remap_path_prefix = "." ): 611"""Builds an Args object containing common rustc flags 612 613Args: 614ctx (ctx): The rule's context object 615attr (struct): The attributes for the target. These may be different from ctx.attr in an aspect context. 616file (struct): A struct containing files defined in label type attributes marked as `allow_single_file`. 617toolchain (rust_toolchain): The current target's `rust_toolchain` 618tool_path (str): Path to rustc 619cc_toolchain (CcToolchain): The CcToolchain for the current target. 620feature_configuration (FeatureConfiguration): Class used to construct command lines from CROSSTOOL features. 621crate_info (CrateInfo): The CrateInfo provider of the target crate 622dep_info (DepInfo): The DepInfo provider of the target crate 623linkstamp_outs (list): Linkstamp outputs of native dependencies 624ambiguous_libs (dict): Ambiguous libs, see `_disambiguate_libs` 625output_hash (str): The hashed path of the crate root 626rust_flags (list): Additional flags to pass to rustc 627out_dir (str): The path to the output directory for the target Crate. 628build_env_files (list): Files containing rustc environment variables, for instance from `cargo_build_script` actions. 629build_flags_files (depset): The output files of a `cargo_build_script` actions containing rustc build flags 630emit (list): Values for the --emit flag to rustc. 631force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern 632to the commandline as opposed to -L. 633force_link (bool, optional): Whether to add link flags to the command regardless of `emit`. 634stamp (bool, optional): Whether or not workspace status stamping is enabled. For more details see 635https://docs.bazel.build/versions/main/user-manual.html#flag--stamp 636remap_path_prefix (str, optional): A value used to remap `${pwd}` to. If set to a falsey value, no prefix will be set. 637 638Returns: 639tuple: A tuple of the following items 640- (struct): A struct of arguments used to run the `Rustc` action 641- process_wrapper_flags (Args): Arguments for the process wrapper 642- rustc_path (Args): Arguments for invoking rustc via the process wrapper 643- rustc_flags (Args): Rust flags for the Rust compiler 644- all (list): A list of all `Args` objects in the order listed above. 645This is to be passed to the `arguments` parameter of actions 646- (dict): Common rustc environment variables 647""" 648output_dir = getattr ( crate_info . output , "dirname" , None ) 649linker_script = getattr ( file , "linker_script" , None ) 650 651env = _get_rustc_env ( attr , toolchain , crate_info . name ) 652 653# Wrapper args first 654process_wrapper_flags = ctx . actions . args () 655 656for build_env_file in build_env_files : 657process_wrapper_flags . add ( "--env-file" , build_env_file ) 658 659process_wrapper_flags . add_all ( build_flags_files , before_each = "--arg-file" ) 660 661# Certain rust build processes expect to find files from the environment 662# variable `$CARGO_MANIFEST_DIR`. Examples of this include pest, tera, 663# asakuma. 664# 665# The compiler and by extension proc-macros see the current working 666# directory as the Bazel exec root. This is what `$CARGO_MANIFEST_DIR` 667# would default to but is often the wrong value (e.g. if the source is in a 668# sub-package or if we are building something in an external repository). 669# Hence, we need to set `CARGO_MANIFEST_DIR` explicitly. 670# 671# Since we cannot get the `exec_root` from starlark, we cheat a little and 672# use `${pwd}` which resolves the `exec_root` at action execution time. 673process_wrapper_flags . add ( "--subst" , "pwd=${pwd}" ) 674 675# If stamping is enabled, enable the functionality in the process wrapper 676if stamp : 677process_wrapper_flags . add ( "--volatile-status-file" , ctx . version_file ) 678 679# Both ctx.label.workspace_root and ctx.label.package are relative paths 680# and either can be empty strings. Avoid trailing/double slashes in the path. 681components = "${{pwd}}/{}/{}" . format ( ctx . label . workspace_root , ctx . label . package ). split ( "/" ) 682env [ "CARGO_MANIFEST_DIR" ] = "/" . join ([ c for c in components if c ]) 683 684if out_dir != None : 685env [ "OUT_DIR" ] = "${pwd}/" + out_dir 686 687# Handle that the binary name and crate name may be different. 688# 689# If a target name contains a - then cargo (and rules_rust) will generate a 690# crate name with _ instead. Accordingly, rustc will generate a output 691# file (executable, or rlib, or whatever) with _ not -. But when cargo 692# puts a binary in the target/${config} directory, and sets environment 693# variables like `CARGO_BIN_EXE_${binary_name}` it will use the - version 694# not the _ version. So we rename the rustc-generated file (with _s) to 695# have -s if needed. 696emit_with_paths = emit 697if crate_info . type == "bin" and crate_info . output != None : 698generated_file = crate_info . name + toolchain . binary_ext 699src = "/" . join ([ crate_info . output . dirname , generated_file ]) 700dst = crate_info . output . path 701if src != dst : 702emit_with_paths = [( "link=" + dst if val == "link" else val ) for val in emit ] 703 704# Arguments for launching rustc from the process wrapper 705rustc_path = ctx . actions . args () 706rustc_path . add ( "--" ) 707rustc_path . add ( tool_path ) 708 709# Rustc arguments 710rustc_flags = ctx . actions . args () 711rustc_flags . set_param_file_format ( "multiline" ) 712rustc_flags . use_param_file ( "@%s" , use_always = False ) 713rustc_flags . add ( crate_info . root ) 714rustc_flags . add ( "--crate-name=" + crate_info . name ) 715rustc_flags . add ( "--crate-type=" + crate_info . type ) 716if hasattr ( attr , "_error_format" ): 717rustc_flags . add ( "--error-format=" + attr . _error_format [ ErrorFormatInfo ]. error_format ) 718 719# Mangle symbols to disambiguate crates with the same name. This could 720# happen only for non-final artifacts where we compute an output_hash, 721# e.g., rust_library. 722# 723# For "final" artifacts and ones intended for distribution outside of 724# Bazel, such as rust_binary, rust_static_library and rust_shared_library, 725# where output_hash is None we don't need to add these flags. 726if output_hash : 727extra_filename = "-" + output_hash 728rustc_flags . add ( "--codegen=metadata=" + extra_filename ) 729rustc_flags . add ( "--codegen=extra-filename=" + extra_filename ) 730 731if output_dir : 732rustc_flags . add ( "--out-dir=" + output_dir ) 733 734compilation_mode = get_compilation_mode_opts ( ctx , toolchain ) 735rustc_flags . add ( "--codegen=opt-level=" + compilation_mode . opt_level ) 736rustc_flags . add ( "--codegen=debuginfo=" + compilation_mode . debug_info ) 737 738# For determinism to help with build distribution and such 739if remap_path_prefix : 740rustc_flags . add ( "--remap-path-prefix=${{pwd}}={}" . format ( remap_path_prefix )) 741 742if emit : 743rustc_flags . add ( "--emit=" + "," . join ( emit_with_paths )) 744rustc_flags . add ( "--color=always" ) 745rustc_flags . add ( "--target=" + toolchain . target_flag_value ) 746if hasattr ( attr , "crate_features" ): 747rustc_flags . add_all ( getattr ( attr , "crate_features" ), before_each = "--cfg" , format_each = 'feature="%s"' ) 748if linker_script : 749rustc_flags . add ( linker_script . path , format = "--codegen=link-arg=-T%s" ) 750 751# Gets the paths to the folders containing the standard library (or libcore) 752rust_std_paths = toolchain . rust_std_paths . to_list () 753 754# Tell Rustc where to find the standard library 755rustc_flags . add_all ( rust_std_paths , before_each = "-L" , format_each = "%s" ) 756rustc_flags . add_all ( rust_flags ) 757 758# Deduplicate data paths due to https://github.com/bazelbuild/bazel/issues/14681 759data_paths = depset ( direct = getattr ( attr , "data" , []) + getattr ( attr , "compile_data" , [])). to_list () 760 761rustc_flags . add_all ( 762expand_list_element_locations ( 763ctx , 764getattr ( attr , "rustc_flags" , []), 765data_paths , 766), 767) 768add_edition_flags ( rustc_flags , crate_info ) 769 770# Link! 771if ( "link" in emit and crate_info . type not in [ "rlib" , "lib" ]) or force_link : 772# Rust's built-in linker can handle linking wasm files. We don't want to attempt to use the cc 773# linker since it won't understand. 774if toolchain . target_arch != "wasm32" : 775if output_dir : 776use_pic = _should_use_pic ( cc_toolchain , feature_configuration , crate_info . type ) 777rpaths = _compute_rpaths ( toolchain , output_dir , dep_info , use_pic ) 778else : 779rpaths = depset ([]) 780ld , link_args , link_env = get_linker_and_args ( ctx , attr , cc_toolchain , feature_configuration , rpaths ) 781env . update ( link_env ) 782rustc_flags . add ( "--codegen=linker=" + ld ) 783rustc_flags . add_joined ( "--codegen" , link_args , join_with = " " , format_joined = "link-args=%s" ) 784 785_add_native_link_flags ( rustc_flags , dep_info , linkstamp_outs , ambiguous_libs , crate_info . type , toolchain , cc_toolchain , feature_configuration ) 786 787# These always need to be added, even if not linking this crate. 788add_crate_link_flags ( rustc_flags , dep_info , force_all_deps_direct ) 789 790needs_extern_proc_macro_flag = "proc-macro" in [ crate_info . type , crate_info . wrapped_crate_type ] and \ 791crate_info . edition != "2015" 792if needs_extern_proc_macro_flag : 793rustc_flags . add ( "--extern" ) 794rustc_flags . add ( "proc_macro" ) 795 796# Make bin crate data deps available to tests. 797for data in getattr ( attr , "data" , []): 798if rust_common . crate_info in data : 799dep_crate_info = data [ rust_common . crate_info ] 800if dep_crate_info . type == "bin" : 801# Trying to make CARGO_BIN_EXE_{} canonical across platform by strip out extension if exists 802env_basename = dep_crate_info . output . basename [: - ( 1 + len ( dep_crate_info . output . extension ))] if len ( dep_crate_info . output . extension ) > 0 else dep_crate_info . output . basename 803env [ "CARGO_BIN_EXE_" + env_basename ] = dep_crate_info . output . short_path 804 805# Update environment with user provided variables. 806env . update ( expand_dict_value_locations ( 807ctx , 808crate_info . rustc_env , 809data_paths , 810)) 811 812# Ensure the sysroot is set for the target platform 813env [ "SYSROOT" ] = toolchain . sysroot 814 815if toolchain . _rename_first_party_crates : 816env [ "RULES_RUST_THIRD_PARTY_DIR" ] = toolchain . _third_party_dir 817 818# extra_rustc_flags apply to the target configuration, not the exec configuration. 819if hasattr ( ctx . attr , "_extra_rustc_flags" ) and not is_exec_configuration ( ctx ): 820rustc_flags . add_all ( ctx . attr . _extra_rustc_flags [ ExtraRustcFlagsInfo ]. extra_rustc_flags ) 821 822if hasattr ( ctx . attr , "_extra_exec_rustc_flags" ) and is_exec_configuration ( ctx ): 823rustc_flags . add_all ( ctx . attr . _extra_exec_rustc_flags [ ExtraExecRustcFlagsInfo ]. extra_exec_rustc_flags ) 824 825# Create a struct which keeps the arguments separate so each may be tuned or 826# replaced where necessary 827args = struct ( 828process_wrapper_flags = process_wrapper_flags , 829rustc_path = rustc_path , 830rustc_flags = rustc_flags , 831all = [ process_wrapper_flags , rustc_path , rustc_flags ], 832) 833 834return args , env 835 836def rustc_compile_action ( 837ctx , 838attr , 839toolchain , 840crate_info , 841output_hash = None , 842rust_flags = [], 843force_all_deps_direct = False ): 844"""Create and run a rustc compile action based on the current rule's attributes 845 846Args: 847ctx (ctx): The rule's context object 848attr (struct): Attributes to use for the rust compile action 849toolchain (rust_toolchain): The current `rust_toolchain` 850crate_info (CrateInfo): The CrateInfo provider for the current target. 851output_hash (str, optional): The hashed path of the crate root. Defaults to None. 852rust_flags (list, optional): Additional flags to pass to rustc. Defaults to []. 853force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern 854to the commandline as opposed to -L. 855 856Returns: 857list: A list of the following providers: 858- (CrateInfo): info for the crate we just built; same as `crate_info` parameter. 859- (DepInfo): The transitive dependencies of this crate. 860- (DefaultInfo): The output file for this crate, and its runfiles. 861""" 862cc_toolchain , feature_configuration = find_cc_toolchain ( ctx ) 863 864dep_info , build_info , linkstamps = collect_deps ( 865deps = crate_info . deps , 866proc_macro_deps = crate_info . proc_macro_deps , 867aliases = crate_info . aliases , 868are_linkstamps_supported = _are_linkstamps_supported ( 869feature_configuration = feature_configuration , 870has_grep_includes = hasattr ( ctx . attr , "_grep_includes" ), 871), 872) 873 874# Determine if the build is currently running with --stamp 875stamp = is_stamping_enabled ( attr ) 876 877compile_inputs , out_dir , build_env_files , build_flags_files , linkstamp_outs , ambiguous_libs = collect_inputs ( 878ctx = ctx , 879file = ctx . file , 880files = ctx . files , 881linkstamps = linkstamps , 882toolchain = toolchain , 883cc_toolchain = cc_toolchain , 884feature_configuration = feature_configuration , 885crate_info = crate_info , 886dep_info = dep_info , 887build_info = build_info , 888stamp = stamp , 889) 890 891args , env_from_args = construct_arguments ( 892ctx = ctx , 893attr = attr , 894file = ctx . file , 895toolchain = toolchain , 896tool_path = toolchain . rustc . path , 897cc_toolchain = cc_toolchain , 898feature_configuration = feature_configuration , 899crate_info = crate_info , 900dep_info = dep_info , 901linkstamp_outs = linkstamp_outs , 902ambiguous_libs = ambiguous_libs , 903output_hash = output_hash , 904rust_flags = rust_flags , 905out_dir = out_dir , 906build_env_files = build_env_files , 907build_flags_files = build_flags_files , 908force_all_deps_direct = force_all_deps_direct , 909stamp = stamp , 910) 911 912env = dict ( ctx . configuration . default_shell_env ) 913env . update ( env_from_args ) 914 915if hasattr ( attr , "version" ) and attr . version != "0.0.0" : 916formatted_version = " v{}" . format ( attr . version ) 917else : 918formatted_version = "" 919 920outputs = [ crate_info . output ] 921 922# For a cdylib that might be added as a dependency to a cc_* target on Windows, it is important to include the 923# interface library that rustc generates in the output files. 924interface_library = None 925if toolchain . os == "windows" and crate_info . type == "cdylib" : 926# Rustc generates the import library with a `.dll.lib` extension rather than the usual `.lib` one that msvc 927# expects (see https://github.com/rust-lang/rust/pull/29520 for more context). 928interface_library = ctx . actions . declare_file ( crate_info . output . basename + ".lib" , sibling = crate_info . output ) 929outputs . append ( interface_library ) 930 931# The action might generate extra output that we don't want to include in the `DefaultInfo` files. 932action_outputs = list ( outputs ) 933 934# Rustc generates a pdb file (on Windows) or a dsym folder (on macos) so provide it in an output group for crate 935# types that benefit from having debug information in a separate file. 936pdb_file = None 937dsym_folder = None 938if crate_info . type in ( "cdylib" , "bin" ) and not crate_info . is_test : 939if toolchain . os == "windows" : 940pdb_file = ctx . actions . declare_file ( crate_info . output . basename [: - len ( crate_info . output . extension )] + "pdb" , sibling = crate_info . output ) 941action_outputs . append ( pdb_file ) 942elif toolchain . os == "darwin" : 943dsym_folder = ctx . actions . declare_directory ( crate_info . output . basename + ".dSYM" , sibling = crate_info . output ) 944action_outputs . append ( dsym_folder ) 945 946if ctx . executable . _process_wrapper : 947# Run as normal 948ctx . actions . run ( 949executable = ctx . executable . _process_wrapper , 950inputs = compile_inputs , 951outputs = action_outputs , 952env = env , 953arguments = args . all , 954mnemonic = "Rustc" , 955progress_message = "Compiling Rust {} {}{} ({} files)" . format ( 956crate_info . type , 957ctx . label . name , 958formatted_version , 959len ( crate_info . srcs . to_list ()), 960), 961) 962else : 963# Run without process_wrapper 964if build_env_files or build_flags_files or stamp : 965fail ( "build_env_files, build_flags_files, stamp are not supported when building without process_wrapper" ) 966ctx . actions . run ( 967executable = toolchain . rustc , 968inputs = compile_inputs , 969outputs = action_outputs , 970env = env , 971arguments = [ args . rustc_flags ], 972mnemonic = "Rustc" , 973progress_message = "Compiling Rust (without process_wrapper) {} {}{} ({} files)" . format ( 974crate_info . type , 975ctx . label . name , 976formatted_version , 977len ( crate_info . srcs . to_list ()), 978), 979) 980 981runfiles = ctx . runfiles ( 982files = getattr ( ctx . files , "data" , []), 983collect_data = True , 984) 985 986# TODO: Remove after some resolution to 987# https://github.com/bazelbuild/rules_rust/issues/771 988out_binary = getattr ( attr , "out_binary" , False ) 989 990providers = [ 991DefaultInfo ( 992# nb. This field is required for cc_library to depend on our output. 993files = depset ( outputs ), 994runfiles = runfiles , 995executable = crate_info . output if crate_info . type == "bin" or crate_info . is_test or out_binary else None , 996), 997] 998 999if crate_info . type in [ "staticlib" , "cdylib" ]: 1000# These rules are not supposed to be depended on by other rust targets, and 1001# as such they shouldn't provide a CrateInfo. However, one may still want to 1002# write a rust_test for them, so we provide the CrateInfo wrapped in a provider 1003# that rust_test understands. 1004providers . extend ([ rust_common . test_crate_info ( crate = crate_info ), dep_info ]) 1005else : 1006providers . extend ([ crate_info , dep_info ]) 1007 1008if toolchain . target_arch != "wasm32" : 1009providers += establish_cc_info ( ctx , attr , crate_info , toolchain , cc_toolchain , feature_configuration , interface_library ) 1010if pdb_file : 1011providers . append ( OutputGroupInfo ( pdb_file = depset ([ pdb_file ]))) 1012if dsym_folder : 1013providers . append ( OutputGroupInfo ( dsym_folder = depset ([ dsym_folder ]))) 1014 1015return providers 1016 1017def _is_dylib ( dep ): 1018return not bool ( dep . static_library or dep . pic_static_library ) 1019 1020def _collect_nonstatic_linker_inputs ( cc_info ): 1021shared_linker_inputs = [] 1022for linker_input in cc_info . linking_context . linker_inputs . to_list (): 1023dylibs = [ 1024lib 1025for lib in linker_input . libraries 1026if _is_dylib ( lib ) 1027] 1028if dylibs : 1029shared_linker_inputs . append ( cc_common . create_linker_input ( 1030owner = linker_input . owner , 1031libraries = depset ( dylibs ), 1032)) 1033return shared_linker_inputs 1034 1035def establish_cc_info ( ctx , attr , crate_info , toolchain , cc_toolchain , feature_configuration , interface_library ): 1036"""If the produced crate is suitable yield a CcInfo to allow for interop with cc rules 1037 1038Args: 1039ctx (ctx): The rule's context object 1040attr (struct): Attributes to use in gathering CcInfo 1041crate_info (CrateInfo): The CrateInfo provider of the target crate 1042toolchain (rust_toolchain): The current `rust_toolchain` 1043cc_toolchain (CcToolchainInfo): The current `CcToolchainInfo` 1044feature_configuration (FeatureConfiguration): Feature configuration to be queried. 1045interface_library (File): Optional interface library for cdylib crates on Windows. 1046 1047Returns: 1048list: A list containing the CcInfo provider 1049""" 1050 1051# A test will not need to produce CcInfo as nothing can depend on test targets 1052if crate_info . is_test : 1053return [] 1054 1055# Only generate CcInfo for particular crate types 1056if crate_info . type not in ( "staticlib" , "cdylib" , "rlib" , "lib" ): 1057return [] 1058 1059# TODO: Remove after some resolution to 1060# https://github.com/bazelbuild/rules_rust/issues/771 1061if getattr ( attr , "out_binary" , False ): 1062return [] 1063 1064if crate_info . type == "staticlib" : 1065library_to_link = cc_common . create_library_to_link ( 1066actions = ctx . actions , 1067feature_configuration = feature_configuration , 1068cc_toolchain = cc_toolchain , 1069static_library = crate_info . output , 1070# TODO(hlopko): handle PIC/NOPIC correctly 1071pic_static_library = crate_info . output , 1072) 1073elif crate_info . type in ( "rlib" , "lib" ): 1074# bazel hard-codes a check for endswith((".a", ".pic.a", 1075# ".lib")) in create_library_to_link, so we work around that 1076# by creating a symlink to the .rlib with a .a extension. 1077dot_a = make_static_lib_symlink ( ctx . actions , crate_info . output ) 1078 1079# TODO(hlopko): handle PIC/NOPIC correctly 1080library_to_link = cc_common . create_library_to_link ( 1081actions = ctx . actions , 1082feature_configuration = feature_configuration , 1083cc_toolchain = cc_toolchain , 1084static_library = dot_a , 1085# TODO(hlopko): handle PIC/NOPIC correctly 1086pic_static_library = dot_a , 1087) 1088elif crate_info . type == "cdylib" : 1089library_to_link = cc_common . create_library_to_link ( 1090actions = ctx . actions , 1091feature_configuration = feature_configuration , 1092cc_toolchain = cc_toolchain , 1093dynamic_library = crate_info . output , 1094interface_library = interface_library , 1095) 1096else : 1097fail ( "Unexpected case" ) 1098 1099link_input = cc_common . create_linker_input ( 1100owner = ctx . label , 1101libraries = depset ([ library_to_link ]), 1102) 1103 1104linking_context = cc_common . create_linking_context ( 1105# TODO - What to do for no_std? 1106linker_inputs = depset ([ link_input ]), 1107) 1108 1109cc_infos = [ 1110CcInfo ( linking_context = linking_context ), 1111toolchain . stdlib_linkflags , 1112] 1113 1114for dep in getattr ( attr , "deps" , []): 1115if CcInfo in dep : 1116# A Rust staticlib or shared library doesn't need to propagate linker inputs 1117# of its dependencies, except for shared libraries. 1118if crate_info . type in [ "cdylib" , "staticlib" ]: 1119shared_linker_inputs = _collect_nonstatic_linker_inputs ( dep [ CcInfo ]) 1120if shared_linker_inputs : 1121linking_context = cc_common . create_linking_context ( 1122linker_inputs = depset ( shared_linker_inputs ), 1123) 1124cc_infos . append ( CcInfo ( linking_context = linking_context )) 1125else : 1126cc_infos . append ( dep [ CcInfo ]) 1127 1128if crate_info . type in ( "rlib" , "lib" ) and toolchain . libstd_and_allocator_ccinfo : 1129# TODO: if we already have an rlib in our deps, we could skip this 1130cc_infos . append ( toolchain . libstd_and_allocator_ccinfo ) 1131 1132return [ cc_common . merge_cc_infos ( cc_infos = cc_infos )] 1133 1134def add_edition_flags ( args , crate ): 1135"""Adds the Rust edition flag to an arguments object reference 1136 1137Args: 1138args (Args): A reference to an Args object 1139crate (CrateInfo): A CrateInfo provider 1140""" 1141if crate . edition != "2015" : 1142args . add ( "--edition={}" . format ( crate . edition )) 1143 1144def _create_extra_input_args ( build_info , dep_info ): 1145"""Gather additional input arguments from transitive dependencies 1146 1147Args: 1148build_info (BuildInfo): The BuildInfo provider from the target Crate's set of inputs. 1149dep_info (DepInfo): The Depinfo provider form the target Crate's set of inputs. 1150 1151Returns: 1152tuple: A tuple of the following items: 1153- (depset[File]): A list of all build info `OUT_DIR` File objects 1154- (str): The `OUT_DIR` of the current build info 1155- (File): An optional generated environment file from a `cargo_build_script` target 1156- (depset[File]): All direct and transitive build flag files from the current build info. 1157""" 1158input_files = [] 1159 1160# Arguments to the commandline line wrapper that are going to be used 1161# to create the final command line 1162out_dir = None 1163build_env_file = None 1164build_flags_files = [] 1165 1166if build_info : 1167out_dir = build_info . out_dir . path 1168build_env_file = build_info . rustc_env 1169build_flags_files . append ( build_info . flags ) 1170build_flags_files . append ( build_info . link_flags ) 1171input_files . append ( build_info . out_dir ) 1172input_files . append ( build_info . link_flags ) 1173 1174return ( 1175depset ( input_files , transitive = [ dep_info . link_search_path_files ]), 1176out_dir , 1177build_env_file , 1178depset ( build_flags_files , transitive = [ dep_info . link_search_path_files ]), 1179) 1180 1181def _compute_rpaths ( toolchain , output_dir , dep_info , use_pic ): 1182"""Determine the artifact's rpaths relative to the bazel root for runtime linking of shared libraries. 1183 1184Args: 1185toolchain (rust_toolchain): The current `rust_toolchain` 1186output_dir (str): The output directory of the current target 1187dep_info (DepInfo): The current target's dependency info 1188use_pic: If set, prefers pic_static_library over static_library. 1189 1190Returns: 1191depset: A set of relative paths from the output directory to each dependency 1192""" 1193 1194# Windows has no rpath equivalent, so always return an empty depset. 1195if toolchain . os == "windows" : 1196return depset ([]) 1197 1198dylibs = [ 1199get_preferred_artifact ( lib , use_pic ) 1200for linker_input in dep_info . transitive_noncrates . to_list () 1201for lib in linker_input . libraries 1202if _is_dylib ( lib ) 1203] 1204if not dylibs : 1205return depset ([]) 1206 1207# For darwin, dylibs compiled by Bazel will fail to be resolved at runtime 1208# without a version of Bazel that includes 1209# https://github.com/bazelbuild/bazel/pull/13427. This is known to not be 1210# included in Bazel 4.1 and below. 1211if toolchain . os != "linux" and toolchain . os != "darwin" : 1212fail ( "Runtime linking is not supported on {}, but found {}" . format ( 1213toolchain . os , 1214dep_info . transitive_noncrates , 1215)) 1216 1217# Multiple dylibs can be present in the same directory, so deduplicate them. 1218return depset ([ 1219relativize ( lib_dir , output_dir ) 1220for lib_dir in _get_dir_names ( dylibs ) 1221]) 1222 1223def _get_dir_names ( files ): 1224"""Returns a list of directory names from the given list of File objects 1225 1226Args: 1227files (list): A list of File objects 1228 1229Returns: 1230list: A list of directory names for all files 1231""" 1232dirs = {} 1233for f in files : 1234dirs [ f . dirname ] = None 1235return dirs . keys () 1236 1237def add_crate_link_flags ( args , dep_info , force_all_deps_direct = False ): 1238"""Adds link flags to an Args object reference 1239 1240Args: 1241args (Args): An arguments object reference 1242dep_info (DepInfo): The current target's dependency info 1243force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern 1244to the commandline as opposed to -L. 1245""" 1246 1247if force_all_deps_direct : 1248args . add_all ( 1249depset ( 1250transitive = [ 1251dep_info . direct_crates , 1252dep_info . transitive_crates , 1253], 1254), 1255uniquify = True , 1256map_each = _crate_to_link_flag , 1257) 1258else : 1259# nb. Direct crates are linked via --extern regardless of their crate_type 1260args . add_all ( dep_info . direct_crates , map_each = _crate_to_link_flag ) 1261args . add_all ( 1262dep_info . transitive_crates , 1263map_each = _get_crate_dirname , 1264uniquify = True , 1265format_each = "-Ldependency=%s" , 1266) 1267 1268def _crate_to_link_flag ( crate ): 1269"""A helper macro used by `add_crate_link_flags` for adding crate link flags to a Arg object 1270 1271Args: 1272crate (CrateInfo|AliasableDepInfo): A CrateInfo or an AliasableDepInfo provider 1273 1274Returns: 1275list: Link flags for the given provider 1276""" 1277 1278# This is AliasableDepInfo, we should use the alias as a crate name 1279if hasattr ( crate , "dep" ): 1280name = crate . name 1281crate_info = crate . dep 1282else : 1283name = crate . name 1284crate_info = crate 1285return [ "--extern={}={}" . format ( name , crate_info . output . path )] 1286 1287def _get_crate_dirname ( crate ): 1288"""A helper macro used by `add_crate_link_flags` for getting the directory name of the current crate's output path 1289 1290Args: 1291crate (CrateInfo): A CrateInfo provider from the current rule 1292 1293Returns: 1294str: The directory name of the the output File that will be produced. 1295""" 1296return crate . output . dirname 1297 1298def _portable_link_flags ( lib , use_pic , ambiguous_libs ): 1299artifact = get_preferred_artifact ( lib , use_pic ) 1300if ambiguous_libs and artifact . path in ambiguous_libs : 1301artifact = ambiguous_libs [ artifact . path ] 1302if lib . static_library or lib . pic_static_library : 1303# To ensure appropriate linker library argument order, in the presence 1304# of both native libraries that depend on rlibs and rlibs that depend 1305# on native libraries, we use an approach where we "sandwich" the 1306# rust libraries between two similar sections of all of native 1307# libraries: 1308# n1 n2 ... r1 r2 ... n1 n2 ... 1309# A B C 1310# This way any dependency from a native library to a rust library 1311# is resolved from A to B, and any dependency from a rust library to 1312# a native one is resolved from B to C. 1313# The question of resolving dependencies from a native library from A 1314# to any rust library is addressed in a different place, where we 1315# create symlinks to the rlibs, pretending they are native libraries, 1316# and adding references to these symlinks in the native section A. 1317# We rely in the behavior of -Clink-arg to put the linker args 1318# at the end of the linker invocation constructed by rustc. 1319return [ 1320"-lstatic=%s" % get_lib_name ( artifact ), 1321"-Clink-arg=-l%s" % get_lib_name ( artifact ), 1322] 1323elif _is_dylib ( lib ): 1324return [ 1325"-ldylib=%s" % get_lib_name ( artifact ), 1326] 1327 1328return [] 1329 1330def _make_link_flags_windows ( linker_input_and_use_pic_and_ambiguous_libs ): 1331linker_input , use_pic , ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs 1332ret = [] 1333for lib in linker_input . libraries : 1334if lib . alwayslink : 1335ret . extend ([ "-C" , "link-arg=/WHOLEARCHIVE:%s" % get_preferred_artifact ( lib , use_pic ). path ]) 1336else : 1337ret . extend ( _portable_link_flags ( lib , use_pic , ambiguous_libs )) 1338return ret 1339 1340def _make_link_flags_darwin ( linker_input_and_use_pic_and_ambiguous_libs ): 1341linker_input , use_pic , ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs 1342ret = [] 1343for lib in linker_input . libraries : 1344if lib . alwayslink : 1345ret . extend ([ 1346"-C" , 1347( "link-arg=-Wl,-force_load,%s" % get_preferred_artifact ( lib , use_pic ). path ), 1348]) 1349else : 1350ret . extend ( _portable_link_flags ( lib , use_pic , ambiguous_libs )) 1351return ret 1352 1353def _make_link_flags_default ( linker_input_and_use_pic_and_ambiguous_libs ): 1354linker_input , use_pic , ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs 1355ret = [] 1356for lib in linker_input . libraries : 1357if lib . alwayslink : 1358ret . extend ([ 1359"-C" , 1360"link-arg=-Wl,--whole-archive" , 1361"-C" , 1362( "link-arg=%s" % get_preferred_artifact ( lib , use_pic ). path ), 1363"-C" , 1364"link-arg=-Wl,--no-whole-archive" , 1365]) 1366else : 1367ret . extend ( _portable_link_flags ( lib , use_pic , ambiguous_libs )) 1368return ret 1369 1370def _libraries_dirnames ( linker_input_and_use_pic_and_ambiguous_libs ): 1371link_input , use_pic , _ = linker_input_and_use_pic_and_ambiguous_libs 1372 1373# De-duplicate names. 1374return depset ([ get_preferred_artifact ( lib , use_pic ). dirname for lib in link_input . libraries ]). to_list () 1375 1376def _add_native_link_flags ( args , dep_info , linkstamp_outs , ambiguous_libs , crate_type , toolchain , cc_toolchain , feature_configuration ): 1377"""Adds linker flags for all dependencies of the current target. 1378 1379Args: 1380args (Args): The Args struct for a ctx.action 1381dep_info (DepInfo): Dependency Info provider 1382linkstamp_outs (list): Linkstamp outputs of native dependencies 1383ambiguous_libs (dict): Ambiguous libs, see `_disambiguate_libs` 1384crate_type: Crate type of the current target 1385toolchain (rust_toolchain): The current `rust_toolchain` 1386cc_toolchain (CcToolchainInfo): The current `cc_toolchain` 1387feature_configuration (FeatureConfiguration): feature configuration to use with cc_toolchain 1388""" 1389if crate_type in [ "lib" , "rlib" ]: 1390return 1391 1392use_pic = _should_use_pic ( cc_toolchain , feature_configuration , crate_type ) 1393 1394if toolchain . os == "windows" : 1395make_link_flags = _make_link_flags_windows 1396elif toolchain . os . startswith ( "mac" ) or toolchain . os . startswith ( "darwin" ): 1397make_link_flags = _make_link_flags_darwin 1398else : 1399make_link_flags = _make_link_flags_default 1400 1401# TODO(hlopko): Remove depset flattening by using lambdas once we are on >=Bazel 5.0 1402args_and_pic_and_ambiguous_libs = [( arg , use_pic , ambiguous_libs ) for arg in dep_info . transitive_noncrates . to_list ()] 1403args . add_all ( args_and_pic_and_ambiguous_libs , map_each = _libraries_dirnames , uniquify = True , format_each = "-Lnative=%s" ) 1404if ambiguous_libs : 1405# If there are ambiguous libs, the disambiguation symlinks to them are 1406# all created in the same directory. Add it to the library search path. 1407ambiguous_libs_dirname = ambiguous_libs . values ()[ 0 ]. dirname 1408args . add ( "-Lnative={}" . format ( ambiguous_libs_dirname )) 1409 1410args . add_all ( args_and_pic_and_ambiguous_libs , map_each = make_link_flags ) 1411 1412for linkstamp_out in linkstamp_outs : 1413args . add_all ([ "-C" , "link-arg=%s" % linkstamp_out . path ]) 1414 1415if crate_type in [ "dylib" , "cdylib" ]: 1416# For shared libraries we want to link C++ runtime library dynamically 1417# (for example libstdc++.so or libc++.so). 1418args . add_all ( 1419cc_toolchain . dynamic_runtime_lib ( feature_configuration = feature_configuration ), 1420map_each = _get_dirname , 1421format_each = "-Lnative=%s" , 1422) 1423args . add_all ( 1424cc_toolchain . dynamic_runtime_lib ( feature_configuration = feature_configuration ), 1425map_each = get_lib_name , 1426format_each = "-ldylib=%s" , 1427) 1428else : 1429# For all other crate types we want to link C++ runtime library statically 1430# (for example libstdc++.a or libc++.a). 1431args . add_all ( 1432cc_toolchain . static_runtime_lib ( feature_configuration = feature_configuration ), 1433map_each = _get_dirname , 1434format_each = "-Lnative=%s" , 1435) 1436args . add_all ( 1437cc_toolchain . static_runtime_lib ( feature_configuration = feature_configuration ), 1438map_each = get_lib_name , 1439format_each = "-lstatic=%s" , 1440) 1441 1442def _get_dirname ( file ): 1443"""A helper function for `_add_native_link_flags`. 1444 1445Args: 1446file (File): The target file 1447 1448Returns: 1449str: Directory name of `file` 1450""" 1451return file . dirname 1452 1453def _error_format_impl ( ctx ): 1454"""Implementation of the `error_format` rule 1455 1456Args: 1457ctx (ctx): The rule's context object 1458 1459Returns: 1460list: A list containing the ErrorFormatInfo provider 1461""" 1462raw = ctx . build_setting_value 1463if raw not in _error_format_values : 1464fail ( "{} expected a value in `{}` but got `{}`" . format ( 1465ctx . label , 1466_error_format_values , 1467raw , 1468)) 1469return [ ErrorFormatInfo ( error_format = raw )] 1470 1471error_format = rule ( 1472doc = ( 1473"Change the [--error-format](https://doc.rust-lang.org/rustc/command-line-arguments.html#option-error-format) " + 1474"flag from the command line with `--@rules_rust//:error_format`. See rustc documentation for valid values." 1475), 1476implementation = _error_format_impl , 1477build_setting = config . string ( flag = True ), 1478) 1479 1480def _extra_rustc_flags_impl ( ctx ): 1481return ExtraRustcFlagsInfo ( extra_rustc_flags = ctx . build_setting_value ) 1482 1483extra_rustc_flags = rule ( 1484doc = ( 1485"Add additional rustc_flags from the command line with `--@rules_rust//:extra_rustc_flags`. " + 1486"This flag should only be used for flags that need to be applied across the entire build. For options that " + 1487"apply to individual crates, use the rustc_flags attribute on the individual crate's rule instead. NOTE: " + 1488"These flags not applied to the exec configuration (proc-macros, cargo_build_script, etc); " + 1489"use `--@rules_rust//:extra_exec_rustc_flags` to apply flags to the exec configuration." 1490), 1491implementation = _extra_rustc_flags_impl , 1492build_setting = config . string_list ( flag = True ), 1493) 1494 1495def _extra_exec_rustc_flags_impl ( ctx ): 1496return ExtraExecRustcFlagsInfo ( extra_exec_rustc_flags = ctx . build_setting_value ) 1497 1498extra_exec_rustc_flags = rule ( 1499doc = ( 1500"Add additional rustc_flags in the exec configuration from the command line with `--@rules_rust//:extra_exec_rustc_flags`. " + 1501"This flag should only be used for flags that need to be applied across the entire build. " + 1502"These flags only apply to the exec configuration (proc-macros, cargo_build_script, etc)." 1503), 1504implementation = _extra_exec_rustc_flags_impl , 1505build_setting = config . string_list ( flag = True ), 1506)