fork/rules_rust

git clone https://git.julia.blue/fork/rules_rust

scentiniDon't leak native dependencies of proc_macro (#1359)69ca2611

0.5.0
62.3 KiB1506 linesraw
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(
40    doc = "A provider mapping an alias name to a Crate's information.",
41    fields = {
42        "dep": "CrateInfo",
43        "name": "str",
44    },
45)
46
47_error_format_values = ["human", "json", "short"]
48
49ErrorFormatInfo = provider(
50    doc = "Set the --error-format flag for all rustc invocations",
51    fields = {"error_format": "(string) [" + ", ".join(_error_format_values) + "]"},
52)
53
54ExtraRustcFlagsInfo = provider(
55    doc = "Pass each value as an additional flag to non-exec rustc invocations",
56    fields = {"extra_rustc_flags": "List[string] Extra flags to pass to rustc in non-exec configuration"},
57)
58
59ExtraExecRustcFlagsInfo = provider(
60    doc = "Pass each value as an additional flag to exec rustc invocations",
61    fields = {"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
67    Args:
68        attr (struct): The current target's attributes
69        toolchain (rust_toolchain): The current target's rust toolchain context
70        crate_name (str): The name of the crate to be compiled
71
72    Returns:
73        dict: Rustc environment variables
74    """
75    version = attr.version if hasattr(attr, "version") else "0.0.0"
76    major, minor, patch = version.split(".", 2)
77    if "-" in patch:
78        patch, pre = patch.split("-", 1)
79    else:
80        pre = ""
81    return {
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
99    Args:
100        ctx (ctx): The current rule's context object
101        toolchain (rust_toolchain): The current rule's `rust_toolchain`
102
103    Returns:
104        struct: See `_rust_toolchain_impl` for more details
105    """
106    comp_mode = ctx.var["COMPILATION_MODE"]
107    if not comp_mode in toolchain.compilation_mode_opts:
108        fail("Unrecognized compilation mode {} for toolchain.".format(comp_mode))
109
110    return toolchain.compilation_mode_opts[comp_mode]
111
112def _are_linkstamps_supported(feature_configuration, has_grep_includes):
113    # Are linkstamps supported by the C++ toolchain?
114    return (cc_common.is_enabled(feature_configuration = feature_configuration, feature_name = "linkstamps") and
115            # Is Bazel recent enough to support Starlark linkstamps?
116            hasattr(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.
119            has_grep_includes)
120
121def _should_use_pic(cc_toolchain, feature_configuration, crate_type):
122    if crate_type in ("cdylib", "dylib"):
123        return cc_toolchain.needs_pic_for_dynamic_libraries(feature_configuration = feature_configuration)
124    return False
125
126def collect_deps(
127        deps,
128        proc_macro_deps,
129        aliases,
130        are_linkstamps_supported = False):
131    """Walks through dependencies and collects the transitive dependencies.
132
133    Args:
134        deps (list): The deps from ctx.attr.deps.
135        proc_macro_deps (list): The proc_macro deps from ctx.attr.proc_macro_deps.
136        aliases (dict): A dict mapping aliased targets to their actual Crate information.
137        are_linkstamps_supported (bool): Whether the current rule and the toolchain support building linkstamps..
138
139    Returns:
140        tuple: Returns a tuple of:
141            DepInfo,
142            BuildInfo,
143            linkstamps (depset[CcLinkstamp]): A depset of CcLinkstamps that need to be compiled and linked into all linked binaries.
144
145    """
146    direct_crates = []
147    transitive_crates = []
148    transitive_noncrates = []
149    transitive_build_infos = []
150    transitive_link_search_paths = []
151    build_info = None
152    linkstamps = []
153    transitive_crate_outputs = []
154
155    aliases = {k.label: v for k, v in aliases.items()}
156    for dep in depset(transitive = [deps, proc_macro_deps]).to_list():
157        (crate_info, dep_info) = _get_crate_and_dep_info(dep)
158        cc_info = _get_cc_info(dep)
159        dep_build_info = _get_build_info(dep)
160
161        if cc_info and are_linkstamps_supported:
162            linkstamps.append(cc_info.linking_context.linkstamps())
163
164        if 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
169            owner = getattr(crate_info, "owner", dep.label if type(dep) == "Target" else None)
170
171            direct_crates.append(AliasableDepInfo(
172                name = aliases.get(owner, crate_info.name),
173                dep = crate_info,
174            ))
175
176            transitive_crates.append(
177                depset(
178                    [crate_info],
179                    transitive = [] if "proc-macro" in [
180                        crate_info.type,
181                        crate_info.wrapped_crate_type,
182                    ] else [dep_info.transitive_crates],
183                ),
184            )
185            transitive_crate_outputs.append(
186                depset(
187                    [crate_info.output],
188                    transitive = [] if "proc-macro" in [
189                        crate_info.type,
190                        crate_info.wrapped_crate_type,
191                    ] else [dep_info.transitive_crate_outputs],
192                ),
193            )
194
195            if "proc-macro" not in [crate_info.type, crate_info.wrapped_crate_type]:
196                transitive_noncrates.append(dep_info.transitive_noncrates)
197            transitive_build_infos.append(dep_info.transitive_build_infos)
198            transitive_link_search_paths.append(dep_info.link_search_path_files)
199
200        elif cc_info:
201            # This dependency is a cc_library
202            transitive_noncrates.append(cc_info.linking_context.linker_inputs)
203        elif dep_build_info:
204            if build_info:
205                fail("Several deps are providing build information, " +
206                     "only one is allowed in the dependencies")
207            build_info = dep_build_info
208            transitive_build_infos.append(depset([build_info]))
209            transitive_link_search_paths.append(depset([build_info.link_search_paths]))
210        else:
211            fail("rust targets can only depend on rust_library, rust_*_library or cc_library " +
212                 "targets.")
213
214    transitive_crates_depset = depset(transitive = transitive_crates)
215
216    return (
217        rust_common.dep_info(
218            direct_crates = depset(direct_crates),
219            transitive_crates = transitive_crates_depset,
220            transitive_noncrates = depset(
221                transitive = transitive_noncrates,
222                order = "topological",  # dylib link flag ordering matters.
223            ),
224            transitive_crate_outputs = depset(transitive = transitive_crate_outputs),
225            transitive_build_infos = depset(transitive = transitive_build_infos),
226            link_search_path_files = depset(transitive = transitive_link_search_paths),
227            dep_env = build_info.dep_env if build_info else None,
228        ),
229        build_info,
230        depset(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.
235    return [
236        get_preferred_artifact(lib, use_pic)
237        for li in linker_inputs
238        for lib in li.libraries
239    ]
240
241def _get_crate_and_dep_info(dep):
242    if type(dep) == "Target" and rust_common.crate_info in dep:
243        return (dep[rust_common.crate_info], dep[rust_common.dep_info])
244    elif type(dep) == "struct" and hasattr(dep, "crate_info"):
245        return (dep.crate_info, dep.dep_info)
246    return (None, None)
247
248def _get_cc_info(dep):
249    if type(dep) == "Target" and CcInfo in dep:
250        return dep[CcInfo]
251    elif type(dep) == "struct" and hasattr(dep, "cc_info"):
252        return dep.cc_info
253    return None
254
255def _get_build_info(dep):
256    if type(dep) == "Target" and BuildInfo in dep:
257        return dep[BuildInfo]
258    elif type(dep) == "struct" and hasattr(dep, "build_info"):
259        return dep.build_info
260    return None
261
262def get_cc_user_link_flags(ctx):
263    """Get the current target's linkopt flags
264
265    Args:
266        ctx (ctx): The current rule's context object
267
268    Returns:
269        depset: The flags passed to Bazel by --linkopt option.
270    """
271    return ctx.fragments.cpp.linkopts
272
273def get_linker_and_args(ctx, attr, cc_toolchain, feature_configuration, rpaths):
274    """Gathers cc_common linker information
275
276    Args:
277        ctx (ctx): The current target's context object
278        attr (struct): Attributes to use in gathering linker args
279        cc_toolchain (CcToolchain): cc_toolchain for which we are creating build variables.
280        feature_configuration (FeatureConfiguration): Feature configuration to be queried.
281        rpaths (depset): Depset of directories where loader will look for libraries at runtime.
282
283
284    Returns:
285        tuple: 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    """
290    user_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.
294    for dep in getattr(attr, "deps", []):
295        if CcInfo in dep and dep[CcInfo].linking_context:
296            for linker_input in dep[CcInfo].linking_context.linker_inputs.to_list():
297                for flag in linker_input.user_link_flags:
298                    user_link_flags.append(flag)
299    link_variables = cc_common.create_link_variables(
300        feature_configuration = feature_configuration,
301        cc_toolchain = cc_toolchain,
302        is_linking_dynamic_library = False,
303        runtime_library_search_directories = rpaths,
304        user_link_flags = user_link_flags,
305    )
306    link_args = cc_common.get_memory_inefficient_command_line(
307        feature_configuration = feature_configuration,
308        action_name = CPP_LINK_EXECUTABLE_ACTION_NAME,
309        variables = link_variables,
310    )
311    link_env = cc_common.get_environment_variables(
312        feature_configuration = feature_configuration,
313        action_name = CPP_LINK_EXECUTABLE_ACTION_NAME,
314        variables = link_variables,
315    )
316    ld = cc_common.get_tool_for_action(
317        feature_configuration = feature_configuration,
318        action_name = CPP_LINK_EXECUTABLE_ACTION_NAME,
319    )
320
321    return ld, link_args, link_env
322
323def _process_build_scripts(
324        build_info,
325        dep_info,
326        compile_inputs):
327    """Gathers the outputs from a target's `cargo_build_script` action.
328
329    Args:
330        build_info (BuildInfo): The target Build's dependency info.
331        dep_info (DepInfo): The Depinfo provider form the target Crate's set of inputs.
332        compile_inputs (depset): A set of all files that will participate in the build.
333
334    Returns:
335        tuple: 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    """
341    extra_inputs, out_dir, build_env_file, build_flags_files = _create_extra_input_args(build_info, dep_info)
342    compile_inputs = depset(transitive = [extra_inputs, compile_inputs])
343    return 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
348    Args:
349      actions (Actions): The rule's context actions object.
350      toolchain: The Rust toolchain object.
351      crate_info (CrateInfo): The target crate's info.
352      lib (File): The library to symlink to.
353
354    Returns:
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.
363    path_hash = abs(hash(lib.path))
364    lib_name = get_lib_name(lib)
365
366    prefix = "lib"
367    extension = ".a"
368    if toolchain.os.startswith("windows"):
369        prefix = ""
370        extension = ".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.
375    symlink_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.
380    symlink = actions.declare_file("_ambiguous_libs/" + crate_info.output.basename + "/" + symlink_name)
381    actions.symlink(
382        output = symlink,
383        target_file = lib,
384        progress_message = "Creating symlink to ambiguous lib: {}".format(lib.path),
385    )
386    return symlink
387
388def _disambiguate_libs(actions, toolchain, crate_info, dep_info, use_pic):
389    """Constructs disambiguating symlinks for ambiguous library dependencies.
390
391    The symlinks are all created in a _ambiguous_libs/ subfolder specific to
392    the target crate to avoid possible collisions with sibling crates that may
393    depend on the same ambiguous libraries.
394
395    Args:
396      actions (Actions): The rule's context actions object.
397      toolchain: The Rust toolchain object.
398      crate_info (CrateInfo): The target crate's info.
399      dep_info: (DepInfo): The target crate's dependency info.
400      use_pic: (boolean): Whether the build should use PIC.
401
402    Returns:
403      dict[String, File]: A mapping from ambiguous library paths to their
404        disambiguating 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.
413    ambiguous_libs = {}
414
415    # A dictionary maintaining a mapping from preferred library name to the
416    # last visited artifact with that name.
417    visited_libs = {}
418    for link_input in dep_info.transitive_noncrates.to_list():
419        for 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.
424            if _is_dylib(lib):
425                continue
426            artifact = get_preferred_artifact(lib, use_pic)
427            name = 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.
436            needs_symlink_to_standardize_name = (
437                (toolchain.os.startswith("linux") or toolchain.os.startswith("mac") or toolchain.os.startswith("darwin")) and
438                artifact.basename.endswith(".a") and not artifact.basename.startswith("lib")
439            ) or (
440                toolchain.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.
445            if (
446                needs_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.
452                if name in visited_libs:
453                    old_path = visited_libs[name].path
454                    if old_path not in ambiguous_libs:
455                        ambiguous_libs[old_path] = _symlink_for_ambiguous_lib(actions, toolchain, crate_info, visited_libs[name])
456                ambiguous_libs[artifact.path] = _symlink_for_ambiguous_lib(actions, toolchain, crate_info, artifact)
457
458            visited_libs[name] = artifact
459    return ambiguous_libs
460
461def collect_inputs(
462        ctx,
463        file,
464        files,
465        linkstamps,
466        toolchain,
467        cc_toolchain,
468        feature_configuration,
469        crate_info,
470        dep_info,
471        build_info,
472        stamp = False):
473    """Gather's the inputs and required input information for a rustc action
474
475    Args:
476        ctx (ctx): The rule's context object.
477        file (struct): A struct containing files defined in label type attributes marked as `allow_single_file`.
478        files (list): A list of all inputs (`ctx.files`).
479        linkstamps (depset): A depset of CcLinkstamps that need to be compiled and linked into all linked binaries.
480        toolchain (rust_toolchain): The current `rust_toolchain`.
481        cc_toolchain (CcToolchainInfo): The current `cc_toolchain`.
482        feature_configuration (FeatureConfiguration): Feature configuration to be queried.
483        crate_info (CrateInfo): The Crate information of the crate to process build scripts for.
484        dep_info (DepInfo): The target Crate's dependency information.
485        build_info (BuildInfo): The target Crate's build settings.
486        stamp (bool, optional): Whether or not workspace status stamping is enabled. For more details see
487            https://docs.bazel.build/versions/main/user-manual.html#flag--stamp
488
489    Returns:
490        tuple: 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    """
498    linker_script = getattr(file, "linker_script") if hasattr(file, "linker_script") else None
499
500    linker_depset = cc_toolchain.all_files
501
502    use_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.
507    additional_transitive_inputs = []
508    ambiguous_libs = {}
509    if crate_info.type in ("staticlib", "proc-macro"):
510        additional_transitive_inputs = _collect_libs_from_linker_inputs(
511            dep_info.transitive_noncrates.to_list(),
512            use_pic,
513        )
514    elif crate_info.type in ("bin", "dylib", "cdylib"):
515        linker_inputs = dep_info.transitive_noncrates.to_list()
516        ambiguous_libs = _disambiguate_libs(ctx.actions, toolchain, crate_info, dep_info, use_pic)
517        additional_transitive_inputs = _collect_libs_from_linker_inputs(linker_inputs, use_pic) + [
518            additional_input
519            for linker_input in linker_inputs
520            for 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.
526    linkstamp_outs = []
527
528    nolinkstamp_compile_inputs = depset(
529        getattr(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]),
533        transitive = [
534            linker_depset,
535            crate_info.srcs,
536            dep_info.transitive_crate_outputs,
537            depset(additional_transitive_inputs),
538            crate_info.compile_data,
539            toolchain.all_files,
540        ],
541    )
542
543    if 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.
549        for 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.
555            out_name = "_objs/" + crate_info.output.basename + "/" + linkstamp.file().path[:-len(linkstamp.file().extension)] + "o"
556            linkstamp_out = ctx.actions.declare_file(out_name)
557            linkstamp_outs.append(linkstamp_out)
558            cc_common.register_linkstamp_compile_action(
559                actions = ctx.actions,
560                cc_toolchain = cc_toolchain,
561                feature_configuration = feature_configuration,
562                grep_includes = ctx.file._grep_includes,
563                source_file = linkstamp.file(),
564                output_file = linkstamp_out,
565                compilation_inputs = linkstamp.hdrs(),
566                inputs_for_validation = nolinkstamp_compile_inputs,
567                label_replacement = str(ctx.label),
568                output_replacement = crate_info.output.path,
569            )
570
571    # If stamping is enabled include the volatile status info file
572    stamp_info = [ctx.version_file] if stamp else []
573
574    compile_inputs = depset(
575        linkstamp_outs + stamp_info,
576        transitive = [
577            nolinkstamp_compile_inputs,
578        ],
579    )
580
581    build_env_files = getattr(files, "rustc_env_files", [])
582    compile_inputs, out_dir, build_env_file, build_flags_files = _process_build_scripts(build_info, dep_info, compile_inputs)
583    if build_env_file:
584        build_env_files = [f for f in build_env_files] + [build_env_file]
585    compile_inputs = depset(build_env_files, transitive = [compile_inputs])
586
587    return compile_inputs, out_dir, build_env_files, build_flags_files, linkstamp_outs, ambiguous_libs
588
589def construct_arguments(
590        ctx,
591        attr,
592        file,
593        toolchain,
594        tool_path,
595        cc_toolchain,
596        feature_configuration,
597        crate_info,
598        dep_info,
599        linkstamp_outs,
600        ambiguous_libs,
601        output_hash,
602        rust_flags,
603        out_dir,
604        build_env_files,
605        build_flags_files,
606        emit = ["dep-info", "link"],
607        force_all_deps_direct = False,
608        force_link = False,
609        stamp = False,
610        remap_path_prefix = "."):
611    """Builds an Args object containing common rustc flags
612
613    Args:
614        ctx (ctx): The rule's context object
615        attr (struct): The attributes for the target. These may be different from ctx.attr in an aspect context.
616        file (struct): A struct containing files defined in label type attributes marked as `allow_single_file`.
617        toolchain (rust_toolchain): The current target's `rust_toolchain`
618        tool_path (str): Path to rustc
619        cc_toolchain (CcToolchain): The CcToolchain for the current target.
620        feature_configuration (FeatureConfiguration): Class used to construct command lines from CROSSTOOL features.
621        crate_info (CrateInfo): The CrateInfo provider of the target crate
622        dep_info (DepInfo): The DepInfo provider of the target crate
623        linkstamp_outs (list): Linkstamp outputs of native dependencies
624        ambiguous_libs (dict): Ambiguous libs, see `_disambiguate_libs`
625        output_hash (str): The hashed path of the crate root
626        rust_flags (list): Additional flags to pass to rustc
627        out_dir (str): The path to the output directory for the target Crate.
628        build_env_files (list): Files containing rustc environment variables, for instance from `cargo_build_script` actions.
629        build_flags_files (depset): The output files of a `cargo_build_script` actions containing rustc build flags
630        emit (list): Values for the --emit flag to rustc.
631        force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern
632            to the commandline as opposed to -L.
633        force_link (bool, optional): Whether to add link flags to the command regardless of `emit`.
634        stamp (bool, optional): Whether or not workspace status stamping is enabled. For more details see
635            https://docs.bazel.build/versions/main/user-manual.html#flag--stamp
636        remap_path_prefix (str, optional): A value used to remap `${pwd}` to. If set to a falsey value, no prefix will be set.
637
638    Returns:
639        tuple: 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.
645                    This is to be passed to the `arguments` parameter of actions
646            - (dict): Common rustc environment variables
647    """
648    output_dir = getattr(crate_info.output, "dirname", None)
649    linker_script = getattr(file, "linker_script", None)
650
651    env = _get_rustc_env(attr, toolchain, crate_info.name)
652
653    # Wrapper args first
654    process_wrapper_flags = ctx.actions.args()
655
656    for build_env_file in build_env_files:
657        process_wrapper_flags.add("--env-file", build_env_file)
658
659    process_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.
673    process_wrapper_flags.add("--subst", "pwd=${pwd}")
674
675    # If stamping is enabled, enable the functionality in the process wrapper
676    if stamp:
677        process_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.
681    components = "${{pwd}}/{}/{}".format(ctx.label.workspace_root, ctx.label.package).split("/")
682    env["CARGO_MANIFEST_DIR"] = "/".join([c for c in components if c])
683
684    if out_dir != None:
685        env["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.
696    emit_with_paths = emit
697    if crate_info.type == "bin" and crate_info.output != None:
698        generated_file = crate_info.name + toolchain.binary_ext
699        src = "/".join([crate_info.output.dirname, generated_file])
700        dst = crate_info.output.path
701        if src != dst:
702            emit_with_paths = [("link=" + dst if val == "link" else val) for val in emit]
703
704    # Arguments for launching rustc from the process wrapper
705    rustc_path = ctx.actions.args()
706    rustc_path.add("--")
707    rustc_path.add(tool_path)
708
709    # Rustc arguments
710    rustc_flags = ctx.actions.args()
711    rustc_flags.set_param_file_format("multiline")
712    rustc_flags.use_param_file("@%s", use_always = False)
713    rustc_flags.add(crate_info.root)
714    rustc_flags.add("--crate-name=" + crate_info.name)
715    rustc_flags.add("--crate-type=" + crate_info.type)
716    if hasattr(attr, "_error_format"):
717        rustc_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.
726    if output_hash:
727        extra_filename = "-" + output_hash
728        rustc_flags.add("--codegen=metadata=" + extra_filename)
729        rustc_flags.add("--codegen=extra-filename=" + extra_filename)
730
731    if output_dir:
732        rustc_flags.add("--out-dir=" + output_dir)
733
734    compilation_mode = get_compilation_mode_opts(ctx, toolchain)
735    rustc_flags.add("--codegen=opt-level=" + compilation_mode.opt_level)
736    rustc_flags.add("--codegen=debuginfo=" + compilation_mode.debug_info)
737
738    # For determinism to help with build distribution and such
739    if remap_path_prefix:
740        rustc_flags.add("--remap-path-prefix=${{pwd}}={}".format(remap_path_prefix))
741
742    if emit:
743        rustc_flags.add("--emit=" + ",".join(emit_with_paths))
744    rustc_flags.add("--color=always")
745    rustc_flags.add("--target=" + toolchain.target_flag_value)
746    if hasattr(attr, "crate_features"):
747        rustc_flags.add_all(getattr(attr, "crate_features"), before_each = "--cfg", format_each = 'feature="%s"')
748    if linker_script:
749        rustc_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)
752    rust_std_paths = toolchain.rust_std_paths.to_list()
753
754    # Tell Rustc where to find the standard library
755    rustc_flags.add_all(rust_std_paths, before_each = "-L", format_each = "%s")
756    rustc_flags.add_all(rust_flags)
757
758    # Deduplicate data paths due to https://github.com/bazelbuild/bazel/issues/14681
759    data_paths = depset(direct = getattr(attr, "data", []) + getattr(attr, "compile_data", [])).to_list()
760
761    rustc_flags.add_all(
762        expand_list_element_locations(
763            ctx,
764            getattr(attr, "rustc_flags", []),
765            data_paths,
766        ),
767    )
768    add_edition_flags(rustc_flags, crate_info)
769
770    # Link!
771    if ("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.
774        if toolchain.target_arch != "wasm32":
775            if output_dir:
776                use_pic = _should_use_pic(cc_toolchain, feature_configuration, crate_info.type)
777                rpaths = _compute_rpaths(toolchain, output_dir, dep_info, use_pic)
778            else:
779                rpaths = depset([])
780            ld, link_args, link_env = get_linker_and_args(ctx, attr, cc_toolchain, feature_configuration, rpaths)
781            env.update(link_env)
782            rustc_flags.add("--codegen=linker=" + ld)
783            rustc_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.
788    add_crate_link_flags(rustc_flags, dep_info, force_all_deps_direct)
789
790    needs_extern_proc_macro_flag = "proc-macro" in [crate_info.type, crate_info.wrapped_crate_type] and \
791                                   crate_info.edition != "2015"
792    if needs_extern_proc_macro_flag:
793        rustc_flags.add("--extern")
794        rustc_flags.add("proc_macro")
795
796    # Make bin crate data deps available to tests.
797    for data in getattr(attr, "data", []):
798        if rust_common.crate_info in data:
799            dep_crate_info = data[rust_common.crate_info]
800            if dep_crate_info.type == "bin":
801                # Trying to make CARGO_BIN_EXE_{} canonical across platform by strip out extension if exists
802                env_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
803                env["CARGO_BIN_EXE_" + env_basename] = dep_crate_info.output.short_path
804
805    # Update environment with user provided variables.
806    env.update(expand_dict_value_locations(
807        ctx,
808        crate_info.rustc_env,
809        data_paths,
810    ))
811
812    # Ensure the sysroot is set for the target platform
813    env["SYSROOT"] = toolchain.sysroot
814
815    if toolchain._rename_first_party_crates:
816        env["RULES_RUST_THIRD_PARTY_DIR"] = toolchain._third_party_dir
817
818    # extra_rustc_flags apply to the target configuration, not the exec configuration.
819    if hasattr(ctx.attr, "_extra_rustc_flags") and not is_exec_configuration(ctx):
820        rustc_flags.add_all(ctx.attr._extra_rustc_flags[ExtraRustcFlagsInfo].extra_rustc_flags)
821
822    if hasattr(ctx.attr, "_extra_exec_rustc_flags") and is_exec_configuration(ctx):
823        rustc_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
827    args = struct(
828        process_wrapper_flags = process_wrapper_flags,
829        rustc_path = rustc_path,
830        rustc_flags = rustc_flags,
831        all = [process_wrapper_flags, rustc_path, rustc_flags],
832    )
833
834    return args, env
835
836def rustc_compile_action(
837        ctx,
838        attr,
839        toolchain,
840        crate_info,
841        output_hash = None,
842        rust_flags = [],
843        force_all_deps_direct = False):
844    """Create and run a rustc compile action based on the current rule's attributes
845
846    Args:
847        ctx (ctx): The rule's context object
848        attr (struct): Attributes to use for the rust compile action
849        toolchain (rust_toolchain): The current `rust_toolchain`
850        crate_info (CrateInfo): The CrateInfo provider for the current target.
851        output_hash (str, optional): The hashed path of the crate root. Defaults to None.
852        rust_flags (list, optional): Additional flags to pass to rustc. Defaults to [].
853        force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern
854            to the commandline as opposed to -L.
855
856    Returns:
857        list: 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    """
862    cc_toolchain, feature_configuration = find_cc_toolchain(ctx)
863
864    dep_info, build_info, linkstamps = collect_deps(
865        deps = crate_info.deps,
866        proc_macro_deps = crate_info.proc_macro_deps,
867        aliases = crate_info.aliases,
868        are_linkstamps_supported = _are_linkstamps_supported(
869            feature_configuration = feature_configuration,
870            has_grep_includes = hasattr(ctx.attr, "_grep_includes"),
871        ),
872    )
873
874    # Determine if the build is currently running with --stamp
875    stamp = is_stamping_enabled(attr)
876
877    compile_inputs, out_dir, build_env_files, build_flags_files, linkstamp_outs, ambiguous_libs = collect_inputs(
878        ctx = ctx,
879        file = ctx.file,
880        files = ctx.files,
881        linkstamps = linkstamps,
882        toolchain = toolchain,
883        cc_toolchain = cc_toolchain,
884        feature_configuration = feature_configuration,
885        crate_info = crate_info,
886        dep_info = dep_info,
887        build_info = build_info,
888        stamp = stamp,
889    )
890
891    args, env_from_args = construct_arguments(
892        ctx = ctx,
893        attr = attr,
894        file = ctx.file,
895        toolchain = toolchain,
896        tool_path = toolchain.rustc.path,
897        cc_toolchain = cc_toolchain,
898        feature_configuration = feature_configuration,
899        crate_info = crate_info,
900        dep_info = dep_info,
901        linkstamp_outs = linkstamp_outs,
902        ambiguous_libs = ambiguous_libs,
903        output_hash = output_hash,
904        rust_flags = rust_flags,
905        out_dir = out_dir,
906        build_env_files = build_env_files,
907        build_flags_files = build_flags_files,
908        force_all_deps_direct = force_all_deps_direct,
909        stamp = stamp,
910    )
911
912    env = dict(ctx.configuration.default_shell_env)
913    env.update(env_from_args)
914
915    if hasattr(attr, "version") and attr.version != "0.0.0":
916        formatted_version = " v{}".format(attr.version)
917    else:
918        formatted_version = ""
919
920    outputs = [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.
924    interface_library = None
925    if 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).
928        interface_library = ctx.actions.declare_file(crate_info.output.basename + ".lib", sibling = crate_info.output)
929        outputs.append(interface_library)
930
931    # The action might generate extra output that we don't want to include in the `DefaultInfo` files.
932    action_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.
936    pdb_file = None
937    dsym_folder = None
938    if crate_info.type in ("cdylib", "bin") and not crate_info.is_test:
939        if toolchain.os == "windows":
940            pdb_file = ctx.actions.declare_file(crate_info.output.basename[:-len(crate_info.output.extension)] + "pdb", sibling = crate_info.output)
941            action_outputs.append(pdb_file)
942        elif toolchain.os == "darwin":
943            dsym_folder = ctx.actions.declare_directory(crate_info.output.basename + ".dSYM", sibling = crate_info.output)
944            action_outputs.append(dsym_folder)
945
946    if ctx.executable._process_wrapper:
947        # Run as normal
948        ctx.actions.run(
949            executable = ctx.executable._process_wrapper,
950            inputs = compile_inputs,
951            outputs = action_outputs,
952            env = env,
953            arguments = args.all,
954            mnemonic = "Rustc",
955            progress_message = "Compiling Rust {} {}{} ({} files)".format(
956                crate_info.type,
957                ctx.label.name,
958                formatted_version,
959                len(crate_info.srcs.to_list()),
960            ),
961        )
962    else:
963        # Run without process_wrapper
964        if build_env_files or build_flags_files or stamp:
965            fail("build_env_files, build_flags_files, stamp are not supported when building without process_wrapper")
966        ctx.actions.run(
967            executable = toolchain.rustc,
968            inputs = compile_inputs,
969            outputs = action_outputs,
970            env = env,
971            arguments = [args.rustc_flags],
972            mnemonic = "Rustc",
973            progress_message = "Compiling Rust (without process_wrapper) {} {}{} ({} files)".format(
974                crate_info.type,
975                ctx.label.name,
976                formatted_version,
977                len(crate_info.srcs.to_list()),
978            ),
979        )
980
981    runfiles = ctx.runfiles(
982        files = getattr(ctx.files, "data", []),
983        collect_data = True,
984    )
985
986    # TODO: Remove after some resolution to
987    # https://github.com/bazelbuild/rules_rust/issues/771
988    out_binary = getattr(attr, "out_binary", False)
989
990    providers = [
991        DefaultInfo(
992            # nb. This field is required for cc_library to depend on our output.
993            files = depset(outputs),
994            runfiles = runfiles,
995            executable = crate_info.output if crate_info.type == "bin" or crate_info.is_test or out_binary else None,
996        ),
997    ]
998
999    if 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.
1004        providers.extend([rust_common.test_crate_info(crate = crate_info), dep_info])
1005    else:
1006        providers.extend([crate_info, dep_info])
1007
1008    if toolchain.target_arch != "wasm32":
1009        providers += establish_cc_info(ctx, attr, crate_info, toolchain, cc_toolchain, feature_configuration, interface_library)
1010    if pdb_file:
1011        providers.append(OutputGroupInfo(pdb_file = depset([pdb_file])))
1012    if dsym_folder:
1013        providers.append(OutputGroupInfo(dsym_folder = depset([dsym_folder])))
1014
1015    return providers
1016
1017def _is_dylib(dep):
1018    return not bool(dep.static_library or dep.pic_static_library)
1019
1020def _collect_nonstatic_linker_inputs(cc_info):
1021    shared_linker_inputs = []
1022    for linker_input in cc_info.linking_context.linker_inputs.to_list():
1023        dylibs = [
1024            lib
1025            for lib in linker_input.libraries
1026            if _is_dylib(lib)
1027        ]
1028        if dylibs:
1029            shared_linker_inputs.append(cc_common.create_linker_input(
1030                owner = linker_input.owner,
1031                libraries = depset(dylibs),
1032            ))
1033    return 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
1038    Args:
1039        ctx (ctx): The rule's context object
1040        attr (struct): Attributes to use in gathering CcInfo
1041        crate_info (CrateInfo): The CrateInfo provider of the target crate
1042        toolchain (rust_toolchain): The current `rust_toolchain`
1043        cc_toolchain (CcToolchainInfo): The current `CcToolchainInfo`
1044        feature_configuration (FeatureConfiguration): Feature configuration to be queried.
1045        interface_library (File): Optional interface library for cdylib crates on Windows.
1046
1047    Returns:
1048        list: A list containing the CcInfo provider
1049    """
1050
1051    # A test will not need to produce CcInfo as nothing can depend on test targets
1052    if crate_info.is_test:
1053        return []
1054
1055    # Only generate CcInfo for particular crate types
1056    if crate_info.type not in ("staticlib", "cdylib", "rlib", "lib"):
1057        return []
1058
1059    # TODO: Remove after some resolution to
1060    # https://github.com/bazelbuild/rules_rust/issues/771
1061    if getattr(attr, "out_binary", False):
1062        return []
1063
1064    if crate_info.type == "staticlib":
1065        library_to_link = cc_common.create_library_to_link(
1066            actions = ctx.actions,
1067            feature_configuration = feature_configuration,
1068            cc_toolchain = cc_toolchain,
1069            static_library = crate_info.output,
1070            # TODO(hlopko): handle PIC/NOPIC correctly
1071            pic_static_library = crate_info.output,
1072        )
1073    elif 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.
1077        dot_a = make_static_lib_symlink(ctx.actions, crate_info.output)
1078
1079        # TODO(hlopko): handle PIC/NOPIC correctly
1080        library_to_link = cc_common.create_library_to_link(
1081            actions = ctx.actions,
1082            feature_configuration = feature_configuration,
1083            cc_toolchain = cc_toolchain,
1084            static_library = dot_a,
1085            # TODO(hlopko): handle PIC/NOPIC correctly
1086            pic_static_library = dot_a,
1087        )
1088    elif crate_info.type == "cdylib":
1089        library_to_link = cc_common.create_library_to_link(
1090            actions = ctx.actions,
1091            feature_configuration = feature_configuration,
1092            cc_toolchain = cc_toolchain,
1093            dynamic_library = crate_info.output,
1094            interface_library = interface_library,
1095        )
1096    else:
1097        fail("Unexpected case")
1098
1099    link_input = cc_common.create_linker_input(
1100        owner = ctx.label,
1101        libraries = depset([library_to_link]),
1102    )
1103
1104    linking_context = cc_common.create_linking_context(
1105        # TODO - What to do for no_std?
1106        linker_inputs = depset([link_input]),
1107    )
1108
1109    cc_infos = [
1110        CcInfo(linking_context = linking_context),
1111        toolchain.stdlib_linkflags,
1112    ]
1113
1114    for dep in getattr(attr, "deps", []):
1115        if 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.
1118            if crate_info.type in ["cdylib", "staticlib"]:
1119                shared_linker_inputs = _collect_nonstatic_linker_inputs(dep[CcInfo])
1120                if shared_linker_inputs:
1121                    linking_context = cc_common.create_linking_context(
1122                        linker_inputs = depset(shared_linker_inputs),
1123                    )
1124                    cc_infos.append(CcInfo(linking_context = linking_context))
1125            else:
1126                cc_infos.append(dep[CcInfo])
1127
1128    if 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
1130        cc_infos.append(toolchain.libstd_and_allocator_ccinfo)
1131
1132    return [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
1137    Args:
1138        args (Args): A reference to an Args object
1139        crate (CrateInfo): A CrateInfo provider
1140    """
1141    if crate.edition != "2015":
1142        args.add("--edition={}".format(crate.edition))
1143
1144def _create_extra_input_args(build_info, dep_info):
1145    """Gather additional input arguments from transitive dependencies
1146
1147    Args:
1148        build_info (BuildInfo): The BuildInfo provider from the target Crate's set of inputs.
1149        dep_info (DepInfo): The Depinfo provider form the target Crate's set of inputs.
1150
1151    Returns:
1152        tuple: 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    """
1158    input_files = []
1159
1160    # Arguments to the commandline line wrapper that are going to be used
1161    # to create the final command line
1162    out_dir = None
1163    build_env_file = None
1164    build_flags_files = []
1165
1166    if build_info:
1167        out_dir = build_info.out_dir.path
1168        build_env_file = build_info.rustc_env
1169        build_flags_files.append(build_info.flags)
1170        build_flags_files.append(build_info.link_flags)
1171        input_files.append(build_info.out_dir)
1172        input_files.append(build_info.link_flags)
1173
1174    return (
1175        depset(input_files, transitive = [dep_info.link_search_path_files]),
1176        out_dir,
1177        build_env_file,
1178        depset(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
1184    Args:
1185        toolchain (rust_toolchain): The current `rust_toolchain`
1186        output_dir (str): The output directory of the current target
1187        dep_info (DepInfo): The current target's dependency info
1188        use_pic: If set, prefers pic_static_library over static_library.
1189
1190    Returns:
1191        depset: 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.
1195    if toolchain.os == "windows":
1196        return depset([])
1197
1198    dylibs = [
1199        get_preferred_artifact(lib, use_pic)
1200        for linker_input in dep_info.transitive_noncrates.to_list()
1201        for lib in linker_input.libraries
1202        if _is_dylib(lib)
1203    ]
1204    if not dylibs:
1205        return 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.
1211    if toolchain.os != "linux" and toolchain.os != "darwin":
1212        fail("Runtime linking is not supported on {}, but found {}".format(
1213            toolchain.os,
1214            dep_info.transitive_noncrates,
1215        ))
1216
1217    # Multiple dylibs can be present in the same directory, so deduplicate them.
1218    return depset([
1219        relativize(lib_dir, output_dir)
1220        for 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
1226    Args:
1227        files (list): A list of File objects
1228
1229    Returns:
1230        list: A list of directory names for all files
1231    """
1232    dirs = {}
1233    for f in files:
1234        dirs[f.dirname] = None
1235    return 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
1240    Args:
1241        args (Args): An arguments object reference
1242        dep_info (DepInfo): The current target's dependency info
1243        force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern
1244            to the commandline as opposed to -L.
1245    """
1246
1247    if force_all_deps_direct:
1248        args.add_all(
1249            depset(
1250                transitive = [
1251                    dep_info.direct_crates,
1252                    dep_info.transitive_crates,
1253                ],
1254            ),
1255            uniquify = True,
1256            map_each = _crate_to_link_flag,
1257        )
1258    else:
1259        # nb. Direct crates are linked via --extern regardless of their crate_type
1260        args.add_all(dep_info.direct_crates, map_each = _crate_to_link_flag)
1261    args.add_all(
1262        dep_info.transitive_crates,
1263        map_each = _get_crate_dirname,
1264        uniquify = True,
1265        format_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
1271    Args:
1272        crate (CrateInfo|AliasableDepInfo): A CrateInfo or an AliasableDepInfo provider
1273
1274    Returns:
1275        list: Link flags for the given provider
1276    """
1277
1278    # This is AliasableDepInfo, we should use the alias as a crate name
1279    if hasattr(crate, "dep"):
1280        name = crate.name
1281        crate_info = crate.dep
1282    else:
1283        name = crate.name
1284        crate_info = crate
1285    return ["--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
1290    Args:
1291        crate (CrateInfo): A CrateInfo provider from the current rule
1292
1293    Returns:
1294        str: The directory name of the the output File that will be produced.
1295    """
1296    return crate.output.dirname
1297
1298def _portable_link_flags(lib, use_pic, ambiguous_libs):
1299    artifact = get_preferred_artifact(lib, use_pic)
1300    if ambiguous_libs and artifact.path in ambiguous_libs:
1301        artifact = ambiguous_libs[artifact.path]
1302    if 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.
1319        return [
1320            "-lstatic=%s" % get_lib_name(artifact),
1321            "-Clink-arg=-l%s" % get_lib_name(artifact),
1322        ]
1323    elif _is_dylib(lib):
1324        return [
1325            "-ldylib=%s" % get_lib_name(artifact),
1326        ]
1327
1328    return []
1329
1330def _make_link_flags_windows(linker_input_and_use_pic_and_ambiguous_libs):
1331    linker_input, use_pic, ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs
1332    ret = []
1333    for lib in linker_input.libraries:
1334        if lib.alwayslink:
1335            ret.extend(["-C", "link-arg=/WHOLEARCHIVE:%s" % get_preferred_artifact(lib, use_pic).path])
1336        else:
1337            ret.extend(_portable_link_flags(lib, use_pic, ambiguous_libs))
1338    return ret
1339
1340def _make_link_flags_darwin(linker_input_and_use_pic_and_ambiguous_libs):
1341    linker_input, use_pic, ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs
1342    ret = []
1343    for lib in linker_input.libraries:
1344        if lib.alwayslink:
1345            ret.extend([
1346                "-C",
1347                ("link-arg=-Wl,-force_load,%s" % get_preferred_artifact(lib, use_pic).path),
1348            ])
1349        else:
1350            ret.extend(_portable_link_flags(lib, use_pic, ambiguous_libs))
1351    return ret
1352
1353def _make_link_flags_default(linker_input_and_use_pic_and_ambiguous_libs):
1354    linker_input, use_pic, ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs
1355    ret = []
1356    for lib in linker_input.libraries:
1357        if lib.alwayslink:
1358            ret.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            ])
1366        else:
1367            ret.extend(_portable_link_flags(lib, use_pic, ambiguous_libs))
1368    return ret
1369
1370def _libraries_dirnames(linker_input_and_use_pic_and_ambiguous_libs):
1371    link_input, use_pic, _ = linker_input_and_use_pic_and_ambiguous_libs
1372
1373    # De-duplicate names.
1374    return 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
1379    Args:
1380        args (Args): The Args struct for a ctx.action
1381        dep_info (DepInfo): Dependency Info provider
1382        linkstamp_outs (list): Linkstamp outputs of native dependencies
1383        ambiguous_libs (dict): Ambiguous libs, see `_disambiguate_libs`
1384        crate_type: Crate type of the current target
1385        toolchain (rust_toolchain): The current `rust_toolchain`
1386        cc_toolchain (CcToolchainInfo): The current `cc_toolchain`
1387        feature_configuration (FeatureConfiguration): feature configuration to use with cc_toolchain
1388    """
1389    if crate_type in ["lib", "rlib"]:
1390        return
1391
1392    use_pic = _should_use_pic(cc_toolchain, feature_configuration, crate_type)
1393
1394    if toolchain.os == "windows":
1395        make_link_flags = _make_link_flags_windows
1396    elif toolchain.os.startswith("mac") or toolchain.os.startswith("darwin"):
1397        make_link_flags = _make_link_flags_darwin
1398    else:
1399        make_link_flags = _make_link_flags_default
1400
1401    # TODO(hlopko): Remove depset flattening by using lambdas once we are on >=Bazel 5.0
1402    args_and_pic_and_ambiguous_libs = [(arg, use_pic, ambiguous_libs) for arg in dep_info.transitive_noncrates.to_list()]
1403    args.add_all(args_and_pic_and_ambiguous_libs, map_each = _libraries_dirnames, uniquify = True, format_each = "-Lnative=%s")
1404    if 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.
1407        ambiguous_libs_dirname = ambiguous_libs.values()[0].dirname
1408        args.add("-Lnative={}".format(ambiguous_libs_dirname))
1409
1410    args.add_all(args_and_pic_and_ambiguous_libs, map_each = make_link_flags)
1411
1412    for linkstamp_out in linkstamp_outs:
1413        args.add_all(["-C", "link-arg=%s" % linkstamp_out.path])
1414
1415    if 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).
1418        args.add_all(
1419            cc_toolchain.dynamic_runtime_lib(feature_configuration = feature_configuration),
1420            map_each = _get_dirname,
1421            format_each = "-Lnative=%s",
1422        )
1423        args.add_all(
1424            cc_toolchain.dynamic_runtime_lib(feature_configuration = feature_configuration),
1425            map_each = get_lib_name,
1426            format_each = "-ldylib=%s",
1427        )
1428    else:
1429        # For all other crate types we want to link C++ runtime library statically
1430        # (for example libstdc++.a or libc++.a).
1431        args.add_all(
1432            cc_toolchain.static_runtime_lib(feature_configuration = feature_configuration),
1433            map_each = _get_dirname,
1434            format_each = "-Lnative=%s",
1435        )
1436        args.add_all(
1437            cc_toolchain.static_runtime_lib(feature_configuration = feature_configuration),
1438            map_each = get_lib_name,
1439            format_each = "-lstatic=%s",
1440        )
1441
1442def _get_dirname(file):
1443    """A helper function for `_add_native_link_flags`.
1444
1445    Args:
1446        file (File): The target file
1447
1448    Returns:
1449        str: Directory name of `file`
1450    """
1451    return file.dirname
1452
1453def _error_format_impl(ctx):
1454    """Implementation of the `error_format` rule
1455
1456    Args:
1457        ctx (ctx): The rule's context object
1458
1459    Returns:
1460        list: A list containing the ErrorFormatInfo provider
1461    """
1462    raw = ctx.build_setting_value
1463    if raw not in _error_format_values:
1464        fail("{} expected a value in `{}` but got `{}`".format(
1465            ctx.label,
1466            _error_format_values,
1467            raw,
1468        ))
1469    return [ErrorFormatInfo(error_format = raw)]
1470
1471error_format = rule(
1472    doc = (
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    ),
1476    implementation = _error_format_impl,
1477    build_setting = config.string(flag = True),
1478)
1479
1480def _extra_rustc_flags_impl(ctx):
1481    return ExtraRustcFlagsInfo(extra_rustc_flags = ctx.build_setting_value)
1482
1483extra_rustc_flags = rule(
1484    doc = (
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    ),
1491    implementation = _extra_rustc_flags_impl,
1492    build_setting = config.string_list(flag = True),
1493)
1494
1495def _extra_exec_rustc_flags_impl(ctx):
1496    return ExtraExecRustcFlagsInfo(extra_exec_rustc_flags = ctx.build_setting_value)
1497
1498extra_exec_rustc_flags = rule(
1499    doc = (
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    ),
1504    implementation = _extra_exec_rustc_flags_impl,
1505    build_setting = config.string_list(flag = True),
1506)