fork/rules_rust

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

scentiniStamp only binaries by default (#1452)daff327e

0.8.1
66.2 KiB1600 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
64IsProcMacroDepInfo = provider(
65    doc = "Records if this is a transitive dependency of a proc-macro.",
66    fields = {"is_proc_macro_dep": "Boolean"},
67)
68
69def _is_proc_macro_dep_impl(ctx):
70    return IsProcMacroDepInfo(is_proc_macro_dep = ctx.build_setting_value)
71
72is_proc_macro_dep = rule(
73    doc = "Records if this is a transitive dependency of a proc-macro.",
74    implementation = _is_proc_macro_dep_impl,
75    build_setting = config.bool(flag = True),
76)
77
78IsProcMacroDepEnabledInfo = provider(
79    doc = "Enables the feature to record if a library is a transitive dependency of a proc-macro.",
80    fields = {"enabled": "Boolean"},
81)
82
83def _is_proc_macro_dep_enabled_impl(ctx):
84    return IsProcMacroDepEnabledInfo(enabled = ctx.build_setting_value)
85
86is_proc_macro_dep_enabled = rule(
87    doc = "Enables the feature to record if a library is a transitive dependency of a proc-macro.",
88    implementation = _is_proc_macro_dep_enabled_impl,
89    build_setting = config.bool(flag = True),
90)
91
92def _get_rustc_env(attr, toolchain, crate_name):
93    """Gathers rustc environment variables
94
95    Args:
96        attr (struct): The current target's attributes
97        toolchain (rust_toolchain): The current target's rust toolchain context
98        crate_name (str): The name of the crate to be compiled
99
100    Returns:
101        dict: Rustc environment variables
102    """
103    version = attr.version if hasattr(attr, "version") else "0.0.0"
104    major, minor, patch = version.split(".", 2)
105    if "-" in patch:
106        patch, pre = patch.split("-", 1)
107    else:
108        pre = ""
109    result = {
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    }
123    if hasattr(attr, "_is_proc_macro_dep_enabled") and attr._is_proc_macro_dep_enabled[IsProcMacroDepEnabledInfo].enabled:
124        is_proc_macro_dep = "0"
125        if hasattr(attr, "_is_proc_macro_dep") and attr._is_proc_macro_dep[IsProcMacroDepInfo].is_proc_macro_dep:
126            is_proc_macro_dep = "1"
127        result["BAZEL_RULES_RUST_IS_PROC_MACRO_DEP"] = is_proc_macro_dep
128    return result
129
130def get_compilation_mode_opts(ctx, toolchain):
131    """Gathers rustc flags for the current compilation mode (opt/debug)
132
133    Args:
134        ctx (ctx): The current rule's context object
135        toolchain (rust_toolchain): The current rule's `rust_toolchain`
136
137    Returns:
138        struct: See `_rust_toolchain_impl` for more details
139    """
140    comp_mode = ctx.var["COMPILATION_MODE"]
141    if not comp_mode in toolchain.compilation_mode_opts:
142        fail("Unrecognized compilation mode {} for toolchain.".format(comp_mode))
143
144    return toolchain.compilation_mode_opts[comp_mode]
145
146def _are_linkstamps_supported(feature_configuration, has_grep_includes):
147    # Are linkstamps supported by the C++ toolchain?
148    return (cc_common.is_enabled(feature_configuration = feature_configuration, feature_name = "linkstamps") and
149            # Is Bazel recent enough to support Starlark linkstamps?
150            hasattr(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.
153            has_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
160    Args:
161        cc_toolchain (CcToolchainInfo): The current `cc_toolchain`.
162        feature_configuration (FeatureConfiguration): Feature configuration to be queried.
163        crate_type (str): A Rust target's crate type.
164
165    Returns:
166        bool: Whether or not [PIC][pic] should be enabled.
167    """
168    if crate_type in ("cdylib", "dylib"):
169        return cc_toolchain.needs_pic_for_dynamic_libraries(feature_configuration = feature_configuration)
170    return False
171
172def collect_deps(
173        deps,
174        proc_macro_deps,
175        aliases,
176        are_linkstamps_supported = False):
177    """Walks through dependencies and collects the transitive dependencies.
178
179    Args:
180        deps (list): The deps from ctx.attr.deps.
181        proc_macro_deps (list): The proc_macro deps from ctx.attr.proc_macro_deps.
182        aliases (dict): A dict mapping aliased targets to their actual Crate information.
183        are_linkstamps_supported (bool): Whether the current rule and the toolchain support building linkstamps..
184
185    Returns:
186        tuple: Returns a tuple of:
187            DepInfo,
188            BuildInfo,
189            linkstamps (depset[CcLinkstamp]): A depset of CcLinkstamps that need to be compiled and linked into all linked binaries.
190
191    """
192    direct_crates = []
193    transitive_crates = []
194    transitive_noncrates = []
195    transitive_build_infos = []
196    transitive_link_search_paths = []
197    build_info = None
198    linkstamps = []
199    transitive_crate_outputs = []
200
201    aliases = {k.label: v for k, v in aliases.items()}
202    for dep in depset(transitive = [deps, proc_macro_deps]).to_list():
203        (crate_info, dep_info) = _get_crate_and_dep_info(dep)
204        cc_info = _get_cc_info(dep)
205        dep_build_info = _get_build_info(dep)
206
207        if cc_info and are_linkstamps_supported:
208            linkstamps.append(cc_info.linking_context.linkstamps())
209
210        if 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
215            owner = getattr(crate_info, "owner", dep.label if type(dep) == "Target" else None)
216
217            direct_crates.append(AliasableDepInfo(
218                name = aliases.get(owner, crate_info.name),
219                dep = crate_info,
220            ))
221
222            transitive_crates.append(
223                depset(
224                    [crate_info],
225                    transitive = [] if "proc-macro" in [
226                        crate_info.type,
227                        crate_info.wrapped_crate_type,
228                    ] else [dep_info.transitive_crates],
229                ),
230            )
231            transitive_crate_outputs.append(
232                depset(
233                    [crate_info.output],
234                    transitive = [] if "proc-macro" in [
235                        crate_info.type,
236                        crate_info.wrapped_crate_type,
237                    ] else [dep_info.transitive_crate_outputs],
238                ),
239            )
240
241            if "proc-macro" not in [crate_info.type, crate_info.wrapped_crate_type]:
242                transitive_noncrates.append(dep_info.transitive_noncrates)
243                transitive_link_search_paths.append(dep_info.link_search_path_files)
244
245            transitive_build_infos.append(dep_info.transitive_build_infos)
246
247        elif cc_info:
248            # This dependency is a cc_library
249            transitive_noncrates.append(cc_info.linking_context.linker_inputs)
250        elif dep_build_info:
251            if build_info:
252                fail("Several deps are providing build information, " +
253                     "only one is allowed in the dependencies")
254            build_info = dep_build_info
255            transitive_build_infos.append(depset([build_info]))
256            transitive_link_search_paths.append(depset([build_info.link_search_paths]))
257        else:
258            fail("rust targets can only depend on rust_library, rust_*_library or cc_library " +
259                 "targets.")
260
261    transitive_crates_depset = depset(transitive = transitive_crates)
262
263    return (
264        rust_common.dep_info(
265            direct_crates = depset(direct_crates),
266            transitive_crates = transitive_crates_depset,
267            transitive_noncrates = depset(
268                transitive = transitive_noncrates,
269                order = "topological",  # dylib link flag ordering matters.
270            ),
271            transitive_crate_outputs = depset(transitive = transitive_crate_outputs),
272            transitive_build_infos = depset(transitive = transitive_build_infos),
273            link_search_path_files = depset(transitive = transitive_link_search_paths),
274            dep_env = build_info.dep_env if build_info else None,
275        ),
276        build_info,
277        depset(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.
282    return [
283        get_preferred_artifact(lib, use_pic)
284        for li in linker_inputs
285        for lib in li.libraries
286    ]
287
288def _get_crate_and_dep_info(dep):
289    if type(dep) == "Target" and rust_common.crate_info in dep:
290        return (dep[rust_common.crate_info], dep[rust_common.dep_info])
291    elif type(dep) == "struct" and hasattr(dep, "crate_info"):
292        return (dep.crate_info, dep.dep_info)
293    return (None, None)
294
295def _get_cc_info(dep):
296    if type(dep) == "Target" and CcInfo in dep:
297        return dep[CcInfo]
298    elif type(dep) == "struct" and hasattr(dep, "cc_info"):
299        return dep.cc_info
300    return None
301
302def _get_build_info(dep):
303    if type(dep) == "Target" and BuildInfo in dep:
304        return dep[BuildInfo]
305    elif type(dep) == "struct" and hasattr(dep, "build_info"):
306        return dep.build_info
307    return None
308
309def get_cc_user_link_flags(ctx):
310    """Get the current target's linkopt flags
311
312    Args:
313        ctx (ctx): The current rule's context object
314
315    Returns:
316        depset: The flags passed to Bazel by --linkopt option.
317    """
318    return ctx.fragments.cpp.linkopts
319
320def get_linker_and_args(ctx, attr, cc_toolchain, feature_configuration, rpaths):
321    """Gathers cc_common linker information
322
323    Args:
324        ctx (ctx): The current target's context object
325        attr (struct): Attributes to use in gathering linker args
326        cc_toolchain (CcToolchain): cc_toolchain for which we are creating build variables.
327        feature_configuration (FeatureConfiguration): Feature configuration to be queried.
328        rpaths (depset): Depset of directories where loader will look for libraries at runtime.
329
330
331    Returns:
332        tuple: 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    """
337    user_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.
341    for dep in getattr(attr, "deps", []):
342        if CcInfo in dep and dep[CcInfo].linking_context:
343            for linker_input in dep[CcInfo].linking_context.linker_inputs.to_list():
344                for flag in linker_input.user_link_flags:
345                    user_link_flags.append(flag)
346    link_variables = cc_common.create_link_variables(
347        feature_configuration = feature_configuration,
348        cc_toolchain = cc_toolchain,
349        is_linking_dynamic_library = False,
350        runtime_library_search_directories = rpaths,
351        user_link_flags = user_link_flags,
352    )
353    link_args = cc_common.get_memory_inefficient_command_line(
354        feature_configuration = feature_configuration,
355        action_name = CPP_LINK_EXECUTABLE_ACTION_NAME,
356        variables = link_variables,
357    )
358    link_env = cc_common.get_environment_variables(
359        feature_configuration = feature_configuration,
360        action_name = CPP_LINK_EXECUTABLE_ACTION_NAME,
361        variables = link_variables,
362    )
363    ld = cc_common.get_tool_for_action(
364        feature_configuration = feature_configuration,
365        action_name = CPP_LINK_EXECUTABLE_ACTION_NAME,
366    )
367
368    return ld, link_args, link_env
369
370def _process_build_scripts(
371        build_info,
372        dep_info,
373        compile_inputs):
374    """Gathers the outputs from a target's `cargo_build_script` action.
375
376    Args:
377        build_info (BuildInfo): The target Build's dependency info.
378        dep_info (DepInfo): The Depinfo provider form the target Crate's set of inputs.
379        compile_inputs (depset): A set of all files that will participate in the build.
380
381    Returns:
382        tuple: 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    """
388    extra_inputs, out_dir, build_env_file, build_flags_files = _create_extra_input_args(build_info, dep_info)
389    compile_inputs = depset(transitive = [extra_inputs, compile_inputs])
390    return 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
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      lib (File): The library to symlink to.
400
401    Returns:
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.
410    path_hash = abs(hash(lib.path))
411    lib_name = get_lib_name(lib)
412
413    prefix = "lib"
414    extension = ".a"
415    if toolchain.os.startswith("windows"):
416        prefix = ""
417        extension = ".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.
422    symlink_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.
427    symlink = actions.declare_file("_ambiguous_libs/" + crate_info.output.basename + "/" + symlink_name)
428    actions.symlink(
429        output = symlink,
430        target_file = lib,
431        progress_message = "Creating symlink to ambiguous lib: {}".format(lib.path),
432    )
433    return symlink
434
435def _disambiguate_libs(actions, toolchain, crate_info, dep_info, use_pic):
436    """Constructs disambiguating symlinks for ambiguous library dependencies.
437
438    The symlinks are all created in a _ambiguous_libs/ subfolder specific to
439    the target crate to avoid possible collisions with sibling crates that may
440    depend on the same ambiguous libraries.
441
442    Args:
443      actions (Actions): The rule's context actions object.
444      toolchain: The Rust toolchain object.
445      crate_info (CrateInfo): The target crate's info.
446      dep_info: (DepInfo): The target crate's dependency info.
447      use_pic: (boolean): Whether the build should use PIC.
448
449    Returns:
450      dict[String, File]: A mapping from ambiguous library paths to their
451        disambiguating 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.
460    ambiguous_libs = {}
461
462    # A dictionary maintaining a mapping from preferred library name to the
463    # last visited artifact with that name.
464    visited_libs = {}
465    for link_input in dep_info.transitive_noncrates.to_list():
466        for 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.
471            if _is_dylib(lib):
472                continue
473            artifact = get_preferred_artifact(lib, use_pic)
474            name = 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.
483            needs_symlink_to_standardize_name = (
484                (toolchain.os.startswith("linux") or toolchain.os.startswith("mac") or toolchain.os.startswith("darwin")) and
485                artifact.basename.endswith(".a") and not artifact.basename.startswith("lib")
486            ) or (
487                toolchain.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.
492            if (
493                needs_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.
499                if name in visited_libs:
500                    old_path = visited_libs[name].path
501                    if old_path not in ambiguous_libs:
502                        ambiguous_libs[old_path] = _symlink_for_ambiguous_lib(actions, toolchain, crate_info, visited_libs[name])
503                ambiguous_libs[artifact.path] = _symlink_for_ambiguous_lib(actions, toolchain, crate_info, artifact)
504
505            visited_libs[name] = artifact
506    return ambiguous_libs
507
508def collect_inputs(
509        ctx,
510        file,
511        files,
512        linkstamps,
513        toolchain,
514        cc_toolchain,
515        feature_configuration,
516        crate_info,
517        dep_info,
518        build_info,
519        stamp = False):
520    """Gather's the inputs and required input information for a rustc action
521
522    Args:
523        ctx (ctx): The rule's context object.
524        file (struct): A struct containing files defined in label type attributes marked as `allow_single_file`.
525        files (list): A list of all inputs (`ctx.files`).
526        linkstamps (depset): A depset of CcLinkstamps that need to be compiled and linked into all linked binaries.
527        toolchain (rust_toolchain): The current `rust_toolchain`.
528        cc_toolchain (CcToolchainInfo): The current `cc_toolchain`.
529        feature_configuration (FeatureConfiguration): Feature configuration to be queried.
530        crate_info (CrateInfo): The Crate information of the crate to process build scripts for.
531        dep_info (DepInfo): The target Crate's dependency information.
532        build_info (BuildInfo): The target Crate's build settings.
533        stamp (bool, optional): Whether or not workspace status stamping is enabled. For more details see
534            https://docs.bazel.build/versions/main/user-manual.html#flag--stamp
535
536    Returns:
537        tuple: 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    """
545    linker_script = getattr(file, "linker_script") if hasattr(file, "linker_script") else None
546
547    linker_depset = cc_toolchain.all_files
548
549    use_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.
554    additional_transitive_inputs = []
555    ambiguous_libs = {}
556    if crate_info.type in ("staticlib", "proc-macro"):
557        additional_transitive_inputs = _collect_libs_from_linker_inputs(
558            dep_info.transitive_noncrates.to_list(),
559            use_pic,
560        )
561    elif crate_info.type in ("bin", "dylib", "cdylib"):
562        linker_inputs = dep_info.transitive_noncrates.to_list()
563        ambiguous_libs = _disambiguate_libs(ctx.actions, toolchain, crate_info, dep_info, use_pic)
564        additional_transitive_inputs = _collect_libs_from_linker_inputs(linker_inputs, use_pic) + [
565            additional_input
566            for linker_input in linker_inputs
567            for 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.
573    linkstamp_outs = []
574
575    nolinkstamp_compile_inputs = depset(
576        getattr(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]),
580        transitive = [
581            linker_depset,
582            crate_info.srcs,
583            dep_info.transitive_crate_outputs,
584            depset(additional_transitive_inputs),
585            crate_info.compile_data,
586            toolchain.all_files,
587        ],
588    )
589
590    if 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.
596        for 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.
602            out_name = "_objs/" + crate_info.output.basename + "/" + linkstamp.file().path[:-len(linkstamp.file().extension)] + "o"
603            linkstamp_out = ctx.actions.declare_file(out_name)
604            linkstamp_outs.append(linkstamp_out)
605            cc_common.register_linkstamp_compile_action(
606                actions = ctx.actions,
607                cc_toolchain = cc_toolchain,
608                feature_configuration = feature_configuration,
609                grep_includes = ctx.file._grep_includes,
610                source_file = linkstamp.file(),
611                output_file = linkstamp_out,
612                compilation_inputs = linkstamp.hdrs(),
613                inputs_for_validation = nolinkstamp_compile_inputs,
614                label_replacement = str(ctx.label),
615                output_replacement = crate_info.output.path,
616            )
617
618    # If stamping is enabled include the volatile and stable status info file
619    stamp_info = [ctx.version_file, ctx.info_file] if stamp else []
620
621    compile_inputs = depset(
622        linkstamp_outs + stamp_info,
623        transitive = [
624            nolinkstamp_compile_inputs,
625        ],
626    )
627
628    build_env_files = getattr(files, "rustc_env_files", [])
629    compile_inputs, out_dir, build_env_file, build_flags_files = _process_build_scripts(build_info, dep_info, compile_inputs)
630    if build_env_file:
631        build_env_files = [f for f in build_env_files] + [build_env_file]
632    compile_inputs = depset(build_env_files, transitive = [compile_inputs])
633
634    return compile_inputs, out_dir, build_env_files, build_flags_files, linkstamp_outs, ambiguous_libs
635
636def construct_arguments(
637        ctx,
638        attr,
639        file,
640        toolchain,
641        tool_path,
642        cc_toolchain,
643        feature_configuration,
644        crate_info,
645        dep_info,
646        linkstamp_outs,
647        ambiguous_libs,
648        output_hash,
649        rust_flags,
650        out_dir,
651        build_env_files,
652        build_flags_files,
653        emit = ["dep-info", "link"],
654        force_all_deps_direct = False,
655        force_link = False,
656        stamp = False,
657        remap_path_prefix = "."):
658    """Builds an Args object containing common rustc flags
659
660    Args:
661        ctx (ctx): The rule's context object
662        attr (struct): The attributes for the target. These may be different from ctx.attr in an aspect context.
663        file (struct): A struct containing files defined in label type attributes marked as `allow_single_file`.
664        toolchain (rust_toolchain): The current target's `rust_toolchain`
665        tool_path (str): Path to rustc
666        cc_toolchain (CcToolchain): The CcToolchain for the current target.
667        feature_configuration (FeatureConfiguration): Class used to construct command lines from CROSSTOOL features.
668        crate_info (CrateInfo): The CrateInfo provider of the target crate
669        dep_info (DepInfo): The DepInfo provider of the target crate
670        linkstamp_outs (list): Linkstamp outputs of native dependencies
671        ambiguous_libs (dict): Ambiguous libs, see `_disambiguate_libs`
672        output_hash (str): The hashed path of the crate root
673        rust_flags (list): Additional flags to pass to rustc
674        out_dir (str): The path to the output directory for the target Crate.
675        build_env_files (list): Files containing rustc environment variables, for instance from `cargo_build_script` actions.
676        build_flags_files (depset): The output files of a `cargo_build_script` actions containing rustc build flags
677        emit (list): Values for the --emit flag to rustc.
678        force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern
679            to the commandline as opposed to -L.
680        force_link (bool, optional): Whether to add link flags to the command regardless of `emit`.
681        stamp (bool, optional): Whether or not workspace status stamping is enabled. For more details see
682            https://docs.bazel.build/versions/main/user-manual.html#flag--stamp
683        remap_path_prefix (str, optional): A value used to remap `${pwd}` to. If set to a falsey value, no prefix will be set.
684
685    Returns:
686        tuple: 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.
692                    This is to be passed to the `arguments` parameter of actions
693            - (dict): Common rustc environment variables
694    """
695    output_dir = getattr(crate_info.output, "dirname", None)
696    linker_script = getattr(file, "linker_script", None)
697
698    env = _get_rustc_env(attr, toolchain, crate_info.name)
699
700    # Wrapper args first
701    process_wrapper_flags = ctx.actions.args()
702
703    for build_env_file in build_env_files:
704        process_wrapper_flags.add("--env-file", build_env_file)
705
706    process_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.
720    process_wrapper_flags.add("--subst", "pwd=${pwd}")
721
722    # If stamping is enabled, enable the functionality in the process wrapper
723    if stamp:
724        process_wrapper_flags.add("--volatile-status-file", ctx.version_file)
725        process_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.
729    components = "${{pwd}}/{}/{}".format(ctx.label.workspace_root, ctx.label.package).split("/")
730    env["CARGO_MANIFEST_DIR"] = "/".join([c for c in components if c])
731
732    if out_dir != None:
733        env["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.
744    emit_with_paths = emit
745    if crate_info.type == "bin" and crate_info.output != None:
746        generated_file = crate_info.name + toolchain.binary_ext
747        src = "/".join([crate_info.output.dirname, generated_file])
748        dst = crate_info.output.path
749        if src != dst:
750            emit_with_paths = [("link=" + dst if val == "link" else val) for val in emit]
751
752    # Arguments for launching rustc from the process wrapper
753    rustc_path = ctx.actions.args()
754    rustc_path.add("--")
755    rustc_path.add(tool_path)
756
757    # Rustc arguments
758    rustc_flags = ctx.actions.args()
759    rustc_flags.set_param_file_format("multiline")
760    rustc_flags.use_param_file("@%s", use_always = False)
761    rustc_flags.add(crate_info.root)
762    rustc_flags.add("--crate-name=" + crate_info.name)
763    rustc_flags.add("--crate-type=" + crate_info.type)
764    if hasattr(attr, "_error_format"):
765        rustc_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.
774    if output_hash:
775        extra_filename = "-" + output_hash
776        rustc_flags.add("--codegen=metadata=" + extra_filename)
777        rustc_flags.add("--codegen=extra-filename=" + extra_filename)
778
779    if output_dir:
780        rustc_flags.add("--out-dir=" + output_dir)
781
782    compilation_mode = get_compilation_mode_opts(ctx, toolchain)
783    rustc_flags.add("--codegen=opt-level=" + compilation_mode.opt_level)
784    rustc_flags.add("--codegen=debuginfo=" + compilation_mode.debug_info)
785
786    # For determinism to help with build distribution and such
787    if remap_path_prefix:
788        rustc_flags.add("--remap-path-prefix=${{pwd}}={}".format(remap_path_prefix))
789
790    if emit:
791        rustc_flags.add("--emit=" + ",".join(emit_with_paths))
792    rustc_flags.add("--color=always")
793    rustc_flags.add("--target=" + toolchain.target_flag_value)
794    if hasattr(attr, "crate_features"):
795        rustc_flags.add_all(getattr(attr, "crate_features"), before_each = "--cfg", format_each = 'feature="%s"')
796    if linker_script:
797        rustc_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)
800    rust_std_paths = toolchain.rust_std_paths.to_list()
801
802    # Tell Rustc where to find the standard library
803    rustc_flags.add_all(rust_std_paths, before_each = "-L", format_each = "%s")
804    rustc_flags.add_all(rust_flags)
805
806    # Deduplicate data paths due to https://github.com/bazelbuild/bazel/issues/14681
807    data_paths = depset(direct = getattr(attr, "data", []) + getattr(attr, "compile_data", [])).to_list()
808
809    rustc_flags.add_all(
810        expand_list_element_locations(
811            ctx,
812            getattr(attr, "rustc_flags", []),
813            data_paths,
814        ),
815    )
816    add_edition_flags(rustc_flags, crate_info)
817
818    # Link!
819    if ("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.
822        if toolchain.target_arch != "wasm32":
823            if output_dir:
824                use_pic = _should_use_pic(cc_toolchain, feature_configuration, crate_info.type)
825                rpaths = _compute_rpaths(toolchain, output_dir, dep_info, use_pic)
826            else:
827                rpaths = depset([])
828            ld, link_args, link_env = get_linker_and_args(ctx, attr, cc_toolchain, feature_configuration, rpaths)
829            env.update(link_env)
830            rustc_flags.add("--codegen=linker=" + ld)
831            rustc_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.
836    add_crate_link_flags(rustc_flags, dep_info, force_all_deps_direct)
837
838    needs_extern_proc_macro_flag = "proc-macro" in [crate_info.type, crate_info.wrapped_crate_type] and \
839                                   crate_info.edition != "2015"
840    if needs_extern_proc_macro_flag:
841        rustc_flags.add("--extern")
842        rustc_flags.add("proc_macro")
843
844    if toolchain.llvm_cov and ctx.configuration.coverage_enabled:
845        rustc_flags.add("--codegen=instrument-coverage")
846
847    # Make bin crate data deps available to tests.
848    for data in getattr(attr, "data", []):
849        if rust_common.crate_info in data:
850            dep_crate_info = data[rust_common.crate_info]
851            if dep_crate_info.type == "bin":
852                # Trying to make CARGO_BIN_EXE_{} canonical across platform by strip out extension if exists
853                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
854                env["CARGO_BIN_EXE_" + env_basename] = dep_crate_info.output.short_path
855
856    # Add environment variables from the Rust toolchain.
857    env.update(toolchain.env)
858
859    # Update environment with user provided variables.
860    env.update(expand_dict_value_locations(
861        ctx,
862        crate_info.rustc_env,
863        data_paths,
864    ))
865
866    # Ensure the sysroot is set for the target platform
867    env["SYSROOT"] = toolchain.sysroot
868
869    if toolchain._rename_first_party_crates:
870        env["RULES_RUST_THIRD_PARTY_DIR"] = toolchain._third_party_dir
871
872    # extra_rustc_flags apply to the target configuration, not the exec configuration.
873    if hasattr(ctx.attr, "_extra_rustc_flags") and not is_exec_configuration(ctx):
874        rustc_flags.add_all(ctx.attr._extra_rustc_flags[ExtraRustcFlagsInfo].extra_rustc_flags)
875
876    if hasattr(ctx.attr, "_extra_rustc_flag") and not is_exec_configuration(ctx):
877        rustc_flags.add_all(ctx.attr._extra_rustc_flag[ExtraRustcFlagsInfo].extra_rustc_flags)
878
879    if hasattr(ctx.attr, "_extra_exec_rustc_flags") and is_exec_configuration(ctx):
880        rustc_flags.add_all(ctx.attr._extra_exec_rustc_flags[ExtraExecRustcFlagsInfo].extra_exec_rustc_flags)
881
882    if hasattr(ctx.attr, "_extra_exec_rustc_flag") and is_exec_configuration(ctx):
883        rustc_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
887    args = struct(
888        process_wrapper_flags = process_wrapper_flags,
889        rustc_path = rustc_path,
890        rustc_flags = rustc_flags,
891        all = [process_wrapper_flags, rustc_path, rustc_flags],
892    )
893
894    return args, env
895
896def rustc_compile_action(
897        ctx,
898        attr,
899        toolchain,
900        crate_info,
901        output_hash = None,
902        rust_flags = [],
903        force_all_deps_direct = False):
904    """Create and run a rustc compile action based on the current rule's attributes
905
906    Args:
907        ctx (ctx): The rule's context object
908        attr (struct): Attributes to use for the rust compile action
909        toolchain (rust_toolchain): The current `rust_toolchain`
910        crate_info (CrateInfo): The CrateInfo provider for the current target.
911        output_hash (str, optional): The hashed path of the crate root. Defaults to None.
912        rust_flags (list, optional): Additional flags to pass to rustc. Defaults to [].
913        force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern
914            to the commandline as opposed to -L.
915
916    Returns:
917        list: 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    """
922    cc_toolchain, feature_configuration = find_cc_toolchain(ctx)
923
924    dep_info, build_info, linkstamps = collect_deps(
925        deps = crate_info.deps,
926        proc_macro_deps = crate_info.proc_macro_deps,
927        aliases = crate_info.aliases,
928        are_linkstamps_supported = _are_linkstamps_supported(
929            feature_configuration = feature_configuration,
930            has_grep_includes = hasattr(ctx.attr, "_grep_includes"),
931        ),
932    )
933
934    # Determine if the build is currently running with --stamp
935    stamp = is_stamping_enabled(attr)
936
937    compile_inputs, out_dir, build_env_files, build_flags_files, linkstamp_outs, ambiguous_libs = collect_inputs(
938        ctx = ctx,
939        file = ctx.file,
940        files = ctx.files,
941        linkstamps = linkstamps,
942        toolchain = toolchain,
943        cc_toolchain = cc_toolchain,
944        feature_configuration = feature_configuration,
945        crate_info = crate_info,
946        dep_info = dep_info,
947        build_info = build_info,
948        stamp = stamp,
949    )
950
951    args, env_from_args = construct_arguments(
952        ctx = ctx,
953        attr = attr,
954        file = ctx.file,
955        toolchain = toolchain,
956        tool_path = toolchain.rustc.path,
957        cc_toolchain = cc_toolchain,
958        feature_configuration = feature_configuration,
959        crate_info = crate_info,
960        dep_info = dep_info,
961        linkstamp_outs = linkstamp_outs,
962        ambiguous_libs = ambiguous_libs,
963        output_hash = output_hash,
964        rust_flags = rust_flags,
965        out_dir = out_dir,
966        build_env_files = build_env_files,
967        build_flags_files = build_flags_files,
968        force_all_deps_direct = force_all_deps_direct,
969        stamp = stamp,
970    )
971
972    env = dict(ctx.configuration.default_shell_env)
973    env.update(env_from_args)
974
975    if hasattr(attr, "version") and attr.version != "0.0.0":
976        formatted_version = " v{}".format(attr.version)
977    else:
978        formatted_version = ""
979
980    outputs = [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.
984    interface_library = None
985    if 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).
988        interface_library = ctx.actions.declare_file(crate_info.output.basename + ".lib", sibling = crate_info.output)
989        outputs.append(interface_library)
990
991    # The action might generate extra output that we don't want to include in the `DefaultInfo` files.
992    action_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.
996    pdb_file = None
997    dsym_folder = None
998    if crate_info.type in ("cdylib", "bin") and not crate_info.is_test:
999        if toolchain.os == "windows":
1000            pdb_file = ctx.actions.declare_file(crate_info.output.basename[:-len(crate_info.output.extension)] + "pdb", sibling = crate_info.output)
1001            action_outputs.append(pdb_file)
1002        elif toolchain.os == "darwin":
1003            dsym_folder = ctx.actions.declare_directory(crate_info.output.basename + ".dSYM", sibling = crate_info.output)
1004            action_outputs.append(dsym_folder)
1005
1006    if ctx.executable._process_wrapper:
1007        # Run as normal
1008        ctx.actions.run(
1009            executable = ctx.executable._process_wrapper,
1010            inputs = compile_inputs,
1011            outputs = action_outputs,
1012            env = env,
1013            arguments = args.all,
1014            mnemonic = "Rustc",
1015            progress_message = "Compiling Rust {} {}{} ({} files)".format(
1016                crate_info.type,
1017                ctx.label.name,
1018                formatted_version,
1019                len(crate_info.srcs.to_list()),
1020            ),
1021        )
1022    else:
1023        # Run without process_wrapper
1024        if build_env_files or build_flags_files or stamp:
1025            fail("build_env_files, build_flags_files, stamp are not supported when building without process_wrapper")
1026        ctx.actions.run(
1027            executable = toolchain.rustc,
1028            inputs = compile_inputs,
1029            outputs = action_outputs,
1030            env = env,
1031            arguments = [args.rustc_flags],
1032            mnemonic = "Rustc",
1033            progress_message = "Compiling Rust (without process_wrapper) {} {}{} ({} files)".format(
1034                crate_info.type,
1035                ctx.label.name,
1036                formatted_version,
1037                len(crate_info.srcs.to_list()),
1038            ),
1039        )
1040
1041    coverage_runfiles = []
1042    if toolchain.llvm_cov and ctx.configuration.coverage_enabled and crate_info.is_test:
1043        coverage_runfiles = [toolchain.llvm_cov, toolchain.llvm_profdata]
1044
1045    runfiles = ctx.runfiles(
1046        files = getattr(ctx.files, "data", []) + coverage_runfiles,
1047        collect_data = True,
1048    )
1049
1050    # TODO: Remove after some resolution to
1051    # https://github.com/bazelbuild/rules_rust/issues/771
1052    out_binary = getattr(attr, "out_binary", False)
1053
1054    providers = [
1055        DefaultInfo(
1056            # nb. This field is required for cc_library to depend on our output.
1057            files = depset(outputs),
1058            runfiles = runfiles,
1059            executable = crate_info.output if crate_info.type == "bin" or crate_info.is_test or out_binary else None,
1060        ),
1061        coverage_common.instrumented_files_info(
1062            ctx,
1063            dependency_attributes = ["deps", "crate"],
1064            extensions = ["rs"],
1065            source_attributes = ["srcs"],
1066        ),
1067    ]
1068
1069    if 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.
1074        providers.extend([rust_common.test_crate_info(crate = crate_info), dep_info])
1075    else:
1076        providers.extend([crate_info, dep_info])
1077
1078    if toolchain.target_arch != "wasm32":
1079        providers += establish_cc_info(ctx, attr, crate_info, toolchain, cc_toolchain, feature_configuration, interface_library)
1080    if pdb_file:
1081        providers.append(OutputGroupInfo(pdb_file = depset([pdb_file])))
1082    if dsym_folder:
1083        providers.append(OutputGroupInfo(dsym_folder = depset([dsym_folder])))
1084
1085    return providers
1086
1087def _is_dylib(dep):
1088    return not bool(dep.static_library or dep.pic_static_library)
1089
1090def _collect_nonstatic_linker_inputs(cc_info):
1091    shared_linker_inputs = []
1092    for linker_input in cc_info.linking_context.linker_inputs.to_list():
1093        dylibs = [
1094            lib
1095            for lib in linker_input.libraries
1096            if _is_dylib(lib)
1097        ]
1098        if dylibs:
1099            shared_linker_inputs.append(cc_common.create_linker_input(
1100                owner = linker_input.owner,
1101                libraries = depset(dylibs),
1102            ))
1103    return 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
1108    Args:
1109        ctx (ctx): The rule's context object
1110        attr (struct): Attributes to use in gathering CcInfo
1111        crate_info (CrateInfo): The CrateInfo provider of the target crate
1112        toolchain (rust_toolchain): The current `rust_toolchain`
1113        cc_toolchain (CcToolchainInfo): The current `CcToolchainInfo`
1114        feature_configuration (FeatureConfiguration): Feature configuration to be queried.
1115        interface_library (File): Optional interface library for cdylib crates on Windows.
1116
1117    Returns:
1118        list: A list containing the CcInfo provider
1119    """
1120
1121    # A test will not need to produce CcInfo as nothing can depend on test targets
1122    if crate_info.is_test:
1123        return []
1124
1125    # Only generate CcInfo for particular crate types
1126    if crate_info.type not in ("staticlib", "cdylib", "rlib", "lib"):
1127        return []
1128
1129    # TODO: Remove after some resolution to
1130    # https://github.com/bazelbuild/rules_rust/issues/771
1131    if getattr(attr, "out_binary", False):
1132        return []
1133
1134    if crate_info.type == "staticlib":
1135        library_to_link = cc_common.create_library_to_link(
1136            actions = ctx.actions,
1137            feature_configuration = feature_configuration,
1138            cc_toolchain = cc_toolchain,
1139            static_library = crate_info.output,
1140            # TODO(hlopko): handle PIC/NOPIC correctly
1141            pic_static_library = crate_info.output,
1142        )
1143    elif 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.
1147        dot_a = make_static_lib_symlink(ctx.actions, crate_info.output)
1148
1149        # TODO(hlopko): handle PIC/NOPIC correctly
1150        library_to_link = cc_common.create_library_to_link(
1151            actions = ctx.actions,
1152            feature_configuration = feature_configuration,
1153            cc_toolchain = cc_toolchain,
1154            static_library = dot_a,
1155            # TODO(hlopko): handle PIC/NOPIC correctly
1156            pic_static_library = dot_a,
1157        )
1158    elif crate_info.type == "cdylib":
1159        library_to_link = cc_common.create_library_to_link(
1160            actions = ctx.actions,
1161            feature_configuration = feature_configuration,
1162            cc_toolchain = cc_toolchain,
1163            dynamic_library = crate_info.output,
1164            interface_library = interface_library,
1165        )
1166    else:
1167        fail("Unexpected case")
1168
1169    link_input = cc_common.create_linker_input(
1170        owner = ctx.label,
1171        libraries = depset([library_to_link]),
1172    )
1173
1174    linking_context = cc_common.create_linking_context(
1175        # TODO - What to do for no_std?
1176        linker_inputs = depset([link_input]),
1177    )
1178
1179    cc_infos = [
1180        CcInfo(linking_context = linking_context),
1181        toolchain.stdlib_linkflags,
1182    ]
1183
1184    for dep in getattr(attr, "deps", []):
1185        if 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.
1188            if crate_info.type in ["cdylib", "staticlib"]:
1189                shared_linker_inputs = _collect_nonstatic_linker_inputs(dep[CcInfo])
1190                if shared_linker_inputs:
1191                    linking_context = cc_common.create_linking_context(
1192                        linker_inputs = depset(shared_linker_inputs),
1193                    )
1194                    cc_infos.append(CcInfo(linking_context = linking_context))
1195            else:
1196                cc_infos.append(dep[CcInfo])
1197
1198    if 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
1200        cc_infos.append(toolchain.libstd_and_allocator_ccinfo)
1201
1202    return [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
1207    Args:
1208        args (Args): A reference to an Args object
1209        crate (CrateInfo): A CrateInfo provider
1210    """
1211    if crate.edition != "2015":
1212        args.add("--edition={}".format(crate.edition))
1213
1214def _create_extra_input_args(build_info, dep_info):
1215    """Gather additional input arguments from transitive dependencies
1216
1217    Args:
1218        build_info (BuildInfo): The BuildInfo provider from the target Crate's set of inputs.
1219        dep_info (DepInfo): The Depinfo provider form the target Crate's set of inputs.
1220
1221    Returns:
1222        tuple: 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    """
1228    input_files = []
1229
1230    # Arguments to the commandline line wrapper that are going to be used
1231    # to create the final command line
1232    out_dir = None
1233    build_env_file = None
1234    build_flags_files = []
1235
1236    if build_info:
1237        out_dir = build_info.out_dir.path
1238        build_env_file = build_info.rustc_env
1239        build_flags_files.append(build_info.flags)
1240        build_flags_files.append(build_info.link_flags)
1241        input_files.append(build_info.out_dir)
1242        input_files.append(build_info.link_flags)
1243
1244    return (
1245        depset(input_files, transitive = [dep_info.link_search_path_files]),
1246        out_dir,
1247        build_env_file,
1248        depset(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
1254    Args:
1255        toolchain (rust_toolchain): The current `rust_toolchain`
1256        output_dir (str): The output directory of the current target
1257        dep_info (DepInfo): The current target's dependency info
1258        use_pic: If set, prefers pic_static_library over static_library.
1259
1260    Returns:
1261        depset: 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.
1265    if toolchain.os == "windows":
1266        return depset([])
1267
1268    dylibs = [
1269        get_preferred_artifact(lib, use_pic)
1270        for linker_input in dep_info.transitive_noncrates.to_list()
1271        for lib in linker_input.libraries
1272        if _is_dylib(lib)
1273    ]
1274    if not dylibs:
1275        return 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.
1281    if toolchain.os != "linux" and toolchain.os != "darwin":
1282        fail("Runtime linking is not supported on {}, but found {}".format(
1283            toolchain.os,
1284            dep_info.transitive_noncrates,
1285        ))
1286
1287    # Multiple dylibs can be present in the same directory, so deduplicate them.
1288    return depset([
1289        relativize(lib_dir, output_dir)
1290        for 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
1296    Args:
1297        files (list): A list of File objects
1298
1299    Returns:
1300        list: A list of directory names for all files
1301    """
1302    dirs = {}
1303    for f in files:
1304        dirs[f.dirname] = None
1305    return 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
1310    Args:
1311        args (Args): An arguments object reference
1312        dep_info (DepInfo): The current target's dependency info
1313        force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern
1314            to the commandline as opposed to -L.
1315    """
1316
1317    if force_all_deps_direct:
1318        args.add_all(
1319            depset(
1320                transitive = [
1321                    dep_info.direct_crates,
1322                    dep_info.transitive_crates,
1323                ],
1324            ),
1325            uniquify = True,
1326            map_each = _crate_to_link_flag,
1327        )
1328    else:
1329        # nb. Direct crates are linked via --extern regardless of their crate_type
1330        args.add_all(dep_info.direct_crates, map_each = _crate_to_link_flag)
1331    args.add_all(
1332        dep_info.transitive_crates,
1333        map_each = _get_crate_dirname,
1334        uniquify = True,
1335        format_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
1341    Args:
1342        crate (CrateInfo|AliasableDepInfo): A CrateInfo or an AliasableDepInfo provider
1343
1344    Returns:
1345        list: Link flags for the given provider
1346    """
1347
1348    # This is AliasableDepInfo, we should use the alias as a crate name
1349    if hasattr(crate, "dep"):
1350        name = crate.name
1351        crate_info = crate.dep
1352    else:
1353        name = crate.name
1354        crate_info = crate
1355    return ["--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
1360    Args:
1361        crate (CrateInfo): A CrateInfo provider from the current rule
1362
1363    Returns:
1364        str: The directory name of the the output File that will be produced.
1365    """
1366    return crate.output.dirname
1367
1368def _portable_link_flags(lib, use_pic, ambiguous_libs):
1369    artifact = get_preferred_artifact(lib, use_pic)
1370    if ambiguous_libs and artifact.path in ambiguous_libs:
1371        artifact = ambiguous_libs[artifact.path]
1372    if 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.
1389        return [
1390            "-lstatic=%s" % get_lib_name(artifact),
1391            "-Clink-arg=-l%s" % get_lib_name(artifact),
1392        ]
1393    elif _is_dylib(lib):
1394        return [
1395            "-ldylib=%s" % get_lib_name(artifact),
1396        ]
1397
1398    return []
1399
1400def _make_link_flags_windows(linker_input_and_use_pic_and_ambiguous_libs):
1401    linker_input, use_pic, ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs
1402    ret = []
1403    for lib in linker_input.libraries:
1404        if lib.alwayslink:
1405            ret.extend(["-C", "link-arg=/WHOLEARCHIVE:%s" % get_preferred_artifact(lib, use_pic).path])
1406        else:
1407            ret.extend(_portable_link_flags(lib, use_pic, ambiguous_libs))
1408    return ret
1409
1410def _make_link_flags_darwin(linker_input_and_use_pic_and_ambiguous_libs):
1411    linker_input, use_pic, ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs
1412    ret = []
1413    for lib in linker_input.libraries:
1414        if lib.alwayslink:
1415            ret.extend([
1416                "-C",
1417                ("link-arg=-Wl,-force_load,%s" % get_preferred_artifact(lib, use_pic).path),
1418            ])
1419        else:
1420            ret.extend(_portable_link_flags(lib, use_pic, ambiguous_libs))
1421    return ret
1422
1423def _make_link_flags_default(linker_input_and_use_pic_and_ambiguous_libs):
1424    linker_input, use_pic, ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs
1425    ret = []
1426    for lib in linker_input.libraries:
1427        if lib.alwayslink:
1428            ret.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            ])
1436        else:
1437            ret.extend(_portable_link_flags(lib, use_pic, ambiguous_libs))
1438    return ret
1439
1440def _libraries_dirnames(linker_input_and_use_pic_and_ambiguous_libs):
1441    link_input, use_pic, _ = linker_input_and_use_pic_and_ambiguous_libs
1442
1443    # De-duplicate names.
1444    return 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
1449    Args:
1450        args (Args): The Args struct for a ctx.action
1451        dep_info (DepInfo): Dependency Info provider
1452        linkstamp_outs (list): Linkstamp outputs of native dependencies
1453        ambiguous_libs (dict): Ambiguous libs, see `_disambiguate_libs`
1454        crate_type: Crate type of the current target
1455        toolchain (rust_toolchain): The current `rust_toolchain`
1456        cc_toolchain (CcToolchainInfo): The current `cc_toolchain`
1457        feature_configuration (FeatureConfiguration): feature configuration to use with cc_toolchain
1458    """
1459    if crate_type in ["lib", "rlib"]:
1460        return
1461
1462    use_pic = _should_use_pic(cc_toolchain, feature_configuration, crate_type)
1463
1464    if toolchain.os == "windows":
1465        make_link_flags = _make_link_flags_windows
1466    elif toolchain.os.startswith("mac") or toolchain.os.startswith("darwin"):
1467        make_link_flags = _make_link_flags_darwin
1468    else:
1469        make_link_flags = _make_link_flags_default
1470
1471    # TODO(hlopko): Remove depset flattening by using lambdas once we are on >=Bazel 5.0
1472    args_and_pic_and_ambiguous_libs = [(arg, use_pic, ambiguous_libs) for arg in dep_info.transitive_noncrates.to_list()]
1473    args.add_all(args_and_pic_and_ambiguous_libs, map_each = _libraries_dirnames, uniquify = True, format_each = "-Lnative=%s")
1474    if 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.
1477        ambiguous_libs_dirname = ambiguous_libs.values()[0].dirname
1478        args.add("-Lnative={}".format(ambiguous_libs_dirname))
1479
1480    args.add_all(args_and_pic_and_ambiguous_libs, map_each = make_link_flags)
1481
1482    for linkstamp_out in linkstamp_outs:
1483        args.add_all(["-C", "link-arg=%s" % linkstamp_out.path])
1484
1485    if 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).
1488        args.add_all(
1489            cc_toolchain.dynamic_runtime_lib(feature_configuration = feature_configuration),
1490            map_each = _get_dirname,
1491            format_each = "-Lnative=%s",
1492        )
1493        args.add_all(
1494            cc_toolchain.dynamic_runtime_lib(feature_configuration = feature_configuration),
1495            map_each = get_lib_name,
1496            format_each = "-ldylib=%s",
1497        )
1498    else:
1499        # For all other crate types we want to link C++ runtime library statically
1500        # (for example libstdc++.a or libc++.a).
1501        args.add_all(
1502            cc_toolchain.static_runtime_lib(feature_configuration = feature_configuration),
1503            map_each = _get_dirname,
1504            format_each = "-Lnative=%s",
1505        )
1506        args.add_all(
1507            cc_toolchain.static_runtime_lib(feature_configuration = feature_configuration),
1508            map_each = get_lib_name,
1509            format_each = "-lstatic=%s",
1510        )
1511
1512def _get_dirname(file):
1513    """A helper function for `_add_native_link_flags`.
1514
1515    Args:
1516        file (File): The target file
1517
1518    Returns:
1519        str: Directory name of `file`
1520    """
1521    return file.dirname
1522
1523def _error_format_impl(ctx):
1524    """Implementation of the `error_format` rule
1525
1526    Args:
1527        ctx (ctx): The rule's context object
1528
1529    Returns:
1530        list: A list containing the ErrorFormatInfo provider
1531    """
1532    raw = ctx.build_setting_value
1533    if raw not in _error_format_values:
1534        fail("{} expected a value in `{}` but got `{}`".format(
1535            ctx.label,
1536            _error_format_values,
1537            raw,
1538        ))
1539    return [ErrorFormatInfo(error_format = raw)]
1540
1541error_format = rule(
1542    doc = (
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    ),
1546    implementation = _error_format_impl,
1547    build_setting = config.string(flag = True),
1548)
1549
1550def _extra_rustc_flags_impl(ctx):
1551    return ExtraRustcFlagsInfo(extra_rustc_flags = ctx.build_setting_value)
1552
1553extra_rustc_flags = rule(
1554    doc = (
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    ),
1561    implementation = _extra_rustc_flags_impl,
1562    build_setting = config.string_list(flag = True),
1563)
1564
1565def _extra_rustc_flag_impl(ctx):
1566    return ExtraRustcFlagsInfo(extra_rustc_flags = [f for f in ctx.build_setting_value if f != ""])
1567
1568extra_rustc_flag = rule(
1569    doc = (
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    ),
1573    implementation = _extra_rustc_flag_impl,
1574    build_setting = config.string(flag = True, allow_multiple = True),
1575)
1576
1577def _extra_exec_rustc_flags_impl(ctx):
1578    return ExtraExecRustcFlagsInfo(extra_exec_rustc_flags = ctx.build_setting_value)
1579
1580extra_exec_rustc_flags = rule(
1581    doc = (
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    ),
1586    implementation = _extra_exec_rustc_flags_impl,
1587    build_setting = config.string_list(flag = True),
1588)
1589
1590def _extra_exec_rustc_flag_impl(ctx):
1591    return ExtraExecRustcFlagsInfo(extra_exec_rustc_flags = [f for f in ctx.build_setting_value if f != ""])
1592
1593extra_exec_rustc_flag = rule(
1594    doc = (
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    ),
1598    implementation = _extra_exec_rustc_flag_impl,
1599    build_setting = config.string(flag = True, allow_multiple = True),
1600)