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