-
Notifications
You must be signed in to change notification settings - Fork 440
/
rustc.bzl
1865 lines (1604 loc) · 78.8 KB
/
rustc.bzl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Functionality for constructing actions that invoke the Rust compiler"""
load(
"@bazel_tools//tools/build_defs/cc:action_names.bzl",
"CPP_LINK_EXECUTABLE_ACTION_NAME",
)
load("//rust/private:common.bzl", "rust_common")
load("//rust/private:providers.bzl", _BuildInfo = "BuildInfo")
load("//rust/private:stamp.bzl", "is_stamping_enabled")
load(
"//rust/private:utils.bzl",
"abs",
"expand_dict_value_locations",
"expand_list_element_locations",
"find_cc_toolchain",
"get_lib_name_default",
"get_lib_name_for_windows",
"get_preferred_artifact",
"is_exec_configuration",
"make_static_lib_symlink",
"relativize",
)
BuildInfo = _BuildInfo
AliasableDepInfo = provider(
doc = "A provider mapping an alias name to a Crate's information.",
fields = {
"dep": "CrateInfo",
"name": "str",
},
)
_error_format_values = ["human", "json", "short"]
ErrorFormatInfo = provider(
doc = "Set the --error-format flag for all rustc invocations",
fields = {"error_format": "(string) [" + ", ".join(_error_format_values) + "]"},
)
ExtraRustcFlagsInfo = provider(
doc = "Pass each value as an additional flag to non-exec rustc invocations",
fields = {"extra_rustc_flags": "List[string] Extra flags to pass to rustc in non-exec configuration"},
)
ExtraExecRustcFlagsInfo = provider(
doc = "Pass each value as an additional flag to exec rustc invocations",
fields = {"extra_exec_rustc_flags": "List[string] Extra flags to pass to rustc in exec configuration"},
)
IsProcMacroDepInfo = provider(
doc = "Records if this is a transitive dependency of a proc-macro.",
fields = {"is_proc_macro_dep": "Boolean"},
)
def _is_proc_macro_dep_impl(ctx):
return IsProcMacroDepInfo(is_proc_macro_dep = ctx.build_setting_value)
is_proc_macro_dep = rule(
doc = "Records if this is a transitive dependency of a proc-macro.",
implementation = _is_proc_macro_dep_impl,
build_setting = config.bool(flag = True),
)
IsProcMacroDepEnabledInfo = provider(
doc = "Enables the feature to record if a library is a transitive dependency of a proc-macro.",
fields = {"enabled": "Boolean"},
)
def _is_proc_macro_dep_enabled_impl(ctx):
return IsProcMacroDepEnabledInfo(enabled = ctx.build_setting_value)
is_proc_macro_dep_enabled = rule(
doc = "Enables the feature to record if a library is a transitive dependency of a proc-macro.",
implementation = _is_proc_macro_dep_enabled_impl,
build_setting = config.bool(flag = True),
)
def _get_rustc_env(attr, toolchain, crate_name):
"""Gathers rustc environment variables
Args:
attr (struct): The current target's attributes
toolchain (rust_toolchain): The current target's rust toolchain context
crate_name (str): The name of the crate to be compiled
Returns:
dict: Rustc environment variables
"""
version = attr.version if hasattr(attr, "version") else "0.0.0"
major, minor, patch = version.split(".", 2)
if "-" in patch:
patch, pre = patch.split("-", 1)
else:
pre = ""
result = {
"CARGO_CFG_TARGET_ARCH": toolchain.target_arch,
"CARGO_CFG_TARGET_OS": toolchain.os,
"CARGO_CRATE_NAME": crate_name,
"CARGO_PKG_AUTHORS": "",
"CARGO_PKG_DESCRIPTION": "",
"CARGO_PKG_HOMEPAGE": "",
"CARGO_PKG_NAME": attr.name,
"CARGO_PKG_VERSION": version,
"CARGO_PKG_VERSION_MAJOR": major,
"CARGO_PKG_VERSION_MINOR": minor,
"CARGO_PKG_VERSION_PATCH": patch,
"CARGO_PKG_VERSION_PRE": pre,
}
if hasattr(attr, "_is_proc_macro_dep_enabled") and attr._is_proc_macro_dep_enabled[IsProcMacroDepEnabledInfo].enabled:
is_proc_macro_dep = "0"
if hasattr(attr, "_is_proc_macro_dep") and attr._is_proc_macro_dep[IsProcMacroDepInfo].is_proc_macro_dep:
is_proc_macro_dep = "1"
result["BAZEL_RULES_RUST_IS_PROC_MACRO_DEP"] = is_proc_macro_dep
return result
def get_compilation_mode_opts(ctx, toolchain):
"""Gathers rustc flags for the current compilation mode (opt/debug)
Args:
ctx (ctx): The current rule's context object
toolchain (rust_toolchain): The current rule's `rust_toolchain`
Returns:
struct: See `_rust_toolchain_impl` for more details
"""
comp_mode = ctx.var["COMPILATION_MODE"]
if not comp_mode in toolchain.compilation_mode_opts:
fail("Unrecognized compilation mode {} for toolchain.".format(comp_mode))
return toolchain.compilation_mode_opts[comp_mode]
def _are_linkstamps_supported(feature_configuration, has_grep_includes):
# Are linkstamps supported by the C++ toolchain?
return (cc_common.is_enabled(feature_configuration = feature_configuration, feature_name = "linkstamps") and
# Is Bazel recent enough to support Starlark linkstamps?
hasattr(cc_common, "register_linkstamp_compile_action") and
# The current rule doesn't define _grep_includes attribute; this
# attribute is required for compiling linkstamps.
has_grep_includes)
def _should_use_pic(cc_toolchain, feature_configuration, crate_type):
"""Whether or not [PIC][pic] should be enabled
[pic]: https://en.wikipedia.org/wiki/Position-independent_code
Args:
cc_toolchain (CcToolchainInfo): The current `cc_toolchain`.
feature_configuration (FeatureConfiguration): Feature configuration to be queried.
crate_type (str): A Rust target's crate type.
Returns:
bool: Whether or not [PIC][pic] should be enabled.
"""
if crate_type in ("cdylib", "dylib"):
return cc_toolchain.needs_pic_for_dynamic_libraries(feature_configuration = feature_configuration)
return False
def _is_proc_macro(crate_info):
return "proc-macro" in (crate_info.type, crate_info.wrapped_crate_type)
def collect_deps(
deps,
proc_macro_deps,
aliases,
are_linkstamps_supported = False):
"""Walks through dependencies and collects the transitive dependencies.
Args:
deps (list): The deps from ctx.attr.deps.
proc_macro_deps (list): The proc_macro deps from ctx.attr.proc_macro_deps.
aliases (dict): A dict mapping aliased targets to their actual Crate information.
are_linkstamps_supported (bool): Whether the current rule and the toolchain support building linkstamps..
Returns:
tuple: Returns a tuple of:
DepInfo,
BuildInfo,
linkstamps (depset[CcLinkstamp]): A depset of CcLinkstamps that need to be compiled and linked into all linked binaries.
"""
direct_crates = []
transitive_crates = []
transitive_noncrates = []
transitive_build_infos = []
transitive_link_search_paths = []
build_info = None
linkstamps = []
transitive_crate_outputs = []
transitive_metadata_outputs = []
aliases = {k.label: v for k, v in aliases.items()}
for dep in depset(transitive = [deps, proc_macro_deps]).to_list():
(crate_info, dep_info) = _get_crate_and_dep_info(dep)
cc_info = _get_cc_info(dep)
dep_build_info = _get_build_info(dep)
if cc_info and are_linkstamps_supported:
linkstamps.append(cc_info.linking_context.linkstamps())
if crate_info:
# This dependency is a rust_library
# When crate_info.owner is set, we use it. When the dep type is Target we get the
# label from dep.label
owner = getattr(crate_info, "owner", dep.label if type(dep) == "Target" else None)
direct_crates.append(AliasableDepInfo(
name = aliases.get(owner, crate_info.name),
dep = crate_info,
))
transitive_crates.append(
depset(
[crate_info],
transitive = [] if _is_proc_macro(crate_info) else [dep_info.transitive_crates],
),
)
# If this dependency produces metadata, add it to the metadata outputs.
# If it doesn't (for example a custom library that exports crate_info),
# we depend on crate_info.output.
depend_on = crate_info.metadata
if not crate_info.metadata:
depend_on = crate_info.output
# If this dependency is a proc_macro, it still can be used for lib crates
# that produce metadata.
# In that case, we don't depend on its metadata dependencies.
transitive_metadata_outputs.append(
depset(
[depend_on],
transitive = [] if _is_proc_macro(crate_info) else [dep_info.transitive_metadata_outputs],
),
)
transitive_crate_outputs.append(
depset(
[crate_info.output],
transitive = [] if _is_proc_macro(crate_info) else [dep_info.transitive_crate_outputs],
),
)
if "proc-macro" not in [crate_info.type, crate_info.wrapped_crate_type]:
transitive_noncrates.append(dep_info.transitive_noncrates)
transitive_link_search_paths.append(dep_info.link_search_path_files)
transitive_build_infos.append(dep_info.transitive_build_infos)
elif cc_info:
# This dependency is a cc_library
transitive_noncrates.append(cc_info.linking_context.linker_inputs)
elif dep_build_info:
if build_info:
fail("Several deps are providing build information, " +
"only one is allowed in the dependencies")
build_info = dep_build_info
transitive_build_infos.append(depset([build_info]))
transitive_link_search_paths.append(depset([build_info.link_search_paths]))
else:
fail("rust targets can only depend on rust_library, rust_*_library or cc_library " +
"targets.")
transitive_crates_depset = depset(transitive = transitive_crates)
return (
rust_common.dep_info(
direct_crates = depset(direct_crates),
transitive_crates = transitive_crates_depset,
transitive_noncrates = depset(
transitive = transitive_noncrates,
order = "topological", # dylib link flag ordering matters.
),
transitive_crate_outputs = depset(transitive = transitive_crate_outputs),
transitive_metadata_outputs = depset(transitive = transitive_metadata_outputs),
transitive_build_infos = depset(transitive = transitive_build_infos),
link_search_path_files = depset(transitive = transitive_link_search_paths),
dep_env = build_info.dep_env if build_info else None,
),
build_info,
depset(transitive = linkstamps),
)
def _collect_libs_from_linker_inputs(linker_inputs, use_pic):
# TODO: We could let the user choose how to link, instead of always preferring to link static libraries.
return [
get_preferred_artifact(lib, use_pic)
for li in linker_inputs
for lib in li.libraries
]
def _get_crate_and_dep_info(dep):
if type(dep) == "Target" and rust_common.crate_info in dep:
return (dep[rust_common.crate_info], dep[rust_common.dep_info])
elif type(dep) == "struct" and hasattr(dep, "crate_info"):
return (dep.crate_info, dep.dep_info)
return (None, None)
def _get_cc_info(dep):
if type(dep) == "Target" and CcInfo in dep:
return dep[CcInfo]
elif type(dep) == "struct" and hasattr(dep, "cc_info"):
return dep.cc_info
return None
def _get_build_info(dep):
if type(dep) == "Target" and BuildInfo in dep:
return dep[BuildInfo]
elif type(dep) == "struct" and hasattr(dep, "build_info"):
return dep.build_info
return None
def get_cc_user_link_flags(ctx):
"""Get the current target's linkopt flags
Args:
ctx (ctx): The current rule's context object
Returns:
depset: The flags passed to Bazel by --linkopt option.
"""
return ctx.fragments.cpp.linkopts
def get_linker_and_args(ctx, attr, cc_toolchain, feature_configuration, rpaths):
"""Gathers cc_common linker information
Args:
ctx (ctx): The current target's context object
attr (struct): Attributes to use in gathering linker args
cc_toolchain (CcToolchain): cc_toolchain for which we are creating build variables.
feature_configuration (FeatureConfiguration): Feature configuration to be queried.
rpaths (depset): Depset of directories where loader will look for libraries at runtime.
Returns:
tuple: A tuple of the following items:
- (str): The tool path for given action.
- (sequence): A flattened command line flags for given action.
- (dict): Environment variables to be set for given action.
"""
user_link_flags = get_cc_user_link_flags(ctx)
# Add linkopt's from dependencies. This includes linkopts from transitive
# dependencies since they get merged up.
for dep in getattr(attr, "deps", []):
if CcInfo in dep and dep[CcInfo].linking_context:
for linker_input in dep[CcInfo].linking_context.linker_inputs.to_list():
for flag in linker_input.user_link_flags:
user_link_flags.append(flag)
link_variables = cc_common.create_link_variables(
feature_configuration = feature_configuration,
cc_toolchain = cc_toolchain,
is_linking_dynamic_library = False,
runtime_library_search_directories = rpaths,
user_link_flags = user_link_flags,
)
link_args = cc_common.get_memory_inefficient_command_line(
feature_configuration = feature_configuration,
action_name = CPP_LINK_EXECUTABLE_ACTION_NAME,
variables = link_variables,
)
link_env = cc_common.get_environment_variables(
feature_configuration = feature_configuration,
action_name = CPP_LINK_EXECUTABLE_ACTION_NAME,
variables = link_variables,
)
ld = cc_common.get_tool_for_action(
feature_configuration = feature_configuration,
action_name = CPP_LINK_EXECUTABLE_ACTION_NAME,
)
return ld, link_args, link_env
def _process_build_scripts(
build_info,
dep_info,
compile_inputs):
"""Gathers the outputs from a target's `cargo_build_script` action.
Args:
build_info (BuildInfo): The target Build's dependency info.
dep_info (DepInfo): The Depinfo provider form the target Crate's set of inputs.
compile_inputs (depset): A set of all files that will participate in the build.
Returns:
tuple: A tuple: A tuple of the following items:
- (depset[File]): A list of all build info `OUT_DIR` File objects
- (str): The `OUT_DIR` of the current build info
- (File): An optional path to a generated environment file from a `cargo_build_script` target
- (depset[File]): All direct and transitive build flags from the current build info.
"""
extra_inputs, out_dir, build_env_file, build_flags_files = _create_extra_input_args(build_info, dep_info)
compile_inputs = depset(transitive = [extra_inputs, compile_inputs])
return compile_inputs, out_dir, build_env_file, build_flags_files
def _symlink_for_ambiguous_lib(actions, toolchain, crate_info, lib):
"""Constructs a disambiguating symlink for a library dependency.
Args:
actions (Actions): The rule's context actions object.
toolchain: The Rust toolchain object.
crate_info (CrateInfo): The target crate's info.
lib (File): The library to symlink to.
Returns:
(File): The disambiguating symlink for the library.
"""
# FIXME: Once the relative order part of the native-link-modifiers rustc
# feature is stable, we should be able to eliminate the need to construct
# symlinks by passing the full paths to the libraries.
# https://github.com/rust-lang/rust/issues/81490.
# Take the absolute value of hash() since it could be negative.
path_hash = abs(hash(lib.path))
lib_name = get_lib_name_for_windows(lib) if toolchain.os.startswith("windows") else get_lib_name_default(lib)
prefix = "lib"
extension = ".a"
if toolchain.os.startswith("windows"):
prefix = ""
extension = ".lib"
# Ensure the symlink follows the lib<name>.a pattern on Unix-like platforms
# or <name>.lib on Windows.
# Add a hash of the original library path to disambiguate libraries with the same basename.
symlink_name = "{}{}-{}{}".format(prefix, lib_name, path_hash, extension)
# Add the symlink to a target crate-specific _ambiguous_libs/ subfolder,
# to avoid possible collisions with sibling crates that may depend on the
# same ambiguous libraries.
symlink = actions.declare_file("_ambiguous_libs/" + crate_info.output.basename + "/" + symlink_name)
actions.symlink(
output = symlink,
target_file = lib,
progress_message = "Creating symlink to ambiguous lib: {}".format(lib.path),
)
return symlink
def _disambiguate_libs(actions, toolchain, crate_info, dep_info, use_pic):
"""Constructs disambiguating symlinks for ambiguous library dependencies.
The symlinks are all created in a _ambiguous_libs/ subfolder specific to
the target crate to avoid possible collisions with sibling crates that may
depend on the same ambiguous libraries.
Args:
actions (Actions): The rule's context actions object.
toolchain: The Rust toolchain object.
crate_info (CrateInfo): The target crate's info.
dep_info: (DepInfo): The target crate's dependency info.
use_pic: (boolean): Whether the build should use PIC.
Returns:
dict[String, File]: A mapping from ambiguous library paths to their
disambiguating symlink.
"""
# FIXME: Once the relative order part of the native-link-modifiers rustc
# feature is stable, we should be able to eliminate the need to construct
# symlinks by passing the full paths to the libraries.
# https://github.com/rust-lang/rust/issues/81490.
# A dictionary from file paths of ambiguous libraries to the corresponding
# symlink.
ambiguous_libs = {}
# A dictionary maintaining a mapping from preferred library name to the
# last visited artifact with that name.
visited_libs = {}
for link_input in dep_info.transitive_noncrates.to_list():
for lib in link_input.libraries:
# FIXME: Dynamic libs are not disambiguated right now, there are
# cases where those have a non-standard name with version (e.g.,
# //test/unit/versioned_libs). We hope that the link modifiers
# stabilization will come before we need to make this work.
if _is_dylib(lib):
continue
artifact = get_preferred_artifact(lib, use_pic)
name = get_lib_name_for_windows(artifact) if toolchain.os.startswith("windows") else get_lib_name_default(artifact)
# On Linux-like platforms, normally library base names start with
# `lib`, following the pattern `lib[name].(a|lo)` and we pass
# -lstatic=name.
# On Windows, the base name looks like `name.lib` and we pass
# -lstatic=name.
# FIXME: Under the native-link-modifiers unstable rustc feature,
# we could use -lstatic:+verbatim instead.
needs_symlink_to_standardize_name = (
(toolchain.os.startswith("linux") or toolchain.os.startswith("mac") or toolchain.os.startswith("darwin")) and
artifact.basename.endswith(".a") and not artifact.basename.startswith("lib")
) or (
toolchain.os.startswith("windows") and not artifact.basename.endswith(".lib")
)
# Detect cases where we need to disambiguate library dependencies
# by constructing symlinks.
if (
needs_symlink_to_standardize_name or
# We have multiple libraries with the same name.
(name in visited_libs and visited_libs[name].path != artifact.path)
):
# Disambiguate the previously visited library (if we just detected
# that it is ambiguous) and the current library.
if name in visited_libs:
old_path = visited_libs[name].path
if old_path not in ambiguous_libs:
ambiguous_libs[old_path] = _symlink_for_ambiguous_lib(actions, toolchain, crate_info, visited_libs[name])
ambiguous_libs[artifact.path] = _symlink_for_ambiguous_lib(actions, toolchain, crate_info, artifact)
visited_libs[name] = artifact
return ambiguous_libs
def _depend_on_metadata(crate_info, force_depend_on_objects):
"""Determines if we can depend on metadata for this crate.
By default (when pipelining is disabled or when the crate type needs to link against
objects) we depend on the set of object files (.rlib).
When pipelining is enabled and the crate type supports depending on metadata,
we depend on metadata files only (.rmeta).
In some rare cases, even if both of those conditions are true, we still want to
depend on objects. This is what force_depend_on_objects is.
Args:
crate_info (CrateInfo): The Crate to determine this for.
force_depend_on_objects (bool): if set we will not depend on metadata.
Returns:
Whether we can depend on metadata for this crate.
"""
if force_depend_on_objects:
return False
return crate_info.type in ("rlib", "lib")
def collect_inputs(
ctx,
file,
files,
linkstamps,
toolchain,
cc_toolchain,
feature_configuration,
crate_info,
dep_info,
build_info,
stamp = False,
force_depend_on_objects = False,
experimental_use_cc_common_link = False):
"""Gather's the inputs and required input information for a rustc action
Args:
ctx (ctx): The rule's context object.
file (struct): A struct containing files defined in label type attributes marked as `allow_single_file`.
files (list): A list of all inputs (`ctx.files`).
linkstamps (depset): A depset of CcLinkstamps that need to be compiled and linked into all linked binaries.
toolchain (rust_toolchain): The current `rust_toolchain`.
cc_toolchain (CcToolchainInfo): The current `cc_toolchain`.
feature_configuration (FeatureConfiguration): Feature configuration to be queried.
crate_info (CrateInfo): The Crate information of the crate to process build scripts for.
dep_info (DepInfo): The target Crate's dependency information.
build_info (BuildInfo): The target Crate's build settings.
stamp (bool, optional): Whether or not workspace status stamping is enabled. For more details see
https://docs.bazel.build/versions/main/user-manual.html#flag--stamp
force_depend_on_objects (bool, optional): Forces dependencies of this rule to be objects rather than
metadata, even for libraries. This is used in rustdoc tests.
experimental_use_cc_common_link (bool, optional): Whether rules_rust uses cc_common.link to link
rust binaries.
Returns:
tuple: A tuple: A tuple of the following items:
- (list): A list of all build info `OUT_DIR` File objects
- (str): The `OUT_DIR` of the current build info
- (File): An optional path to a generated environment file from a `cargo_build_script` target
- (depset[File]): All direct and transitive build flag files from the current build info
- (list[File]): Linkstamp outputs
- (dict[String, File]): Ambiguous libs, see `_disambiguate_libs`.
"""
linker_script = getattr(file, "linker_script") if hasattr(file, "linker_script") else None
linker_depset = cc_toolchain.all_files
use_pic = _should_use_pic(cc_toolchain, feature_configuration, crate_info.type)
# Pass linker inputs only for linking-like actions, not for example where
# the output is rlib. This avoids quadratic behavior where transitive noncrates are
# flattened on each transitive rust_library dependency.
additional_transitive_inputs = []
ambiguous_libs = {}
if crate_info.type in ("staticlib", "proc-macro"):
additional_transitive_inputs = _collect_libs_from_linker_inputs(
dep_info.transitive_noncrates.to_list(),
use_pic,
)
elif crate_info.type in ("bin", "dylib", "cdylib"):
linker_inputs = dep_info.transitive_noncrates.to_list()
ambiguous_libs = _disambiguate_libs(ctx.actions, toolchain, crate_info, dep_info, use_pic)
additional_transitive_inputs = _collect_libs_from_linker_inputs(linker_inputs, use_pic) + [
additional_input
for linker_input in linker_inputs
for additional_input in linker_input.additional_inputs
] + ambiguous_libs.values()
# Compute linkstamps. Use the inputs of the binary as inputs to the
# linkstamp action to ensure linkstamps are rebuilt whenever binary inputs
# change.
linkstamp_outs = []
transitive_crate_outputs = dep_info.transitive_crate_outputs
if _depend_on_metadata(crate_info, force_depend_on_objects):
transitive_crate_outputs = dep_info.transitive_metadata_outputs
nolinkstamp_compile_inputs = depset(
getattr(files, "data", []) +
([build_info.rustc_env, build_info.flags] if build_info else []) +
([toolchain.target_json] if toolchain.target_json else []) +
([] if linker_script == None else [linker_script]),
transitive = [
linker_depset,
crate_info.srcs,
transitive_crate_outputs,
depset(additional_transitive_inputs),
crate_info.compile_data,
toolchain.all_files,
],
)
# Register linkstamps when linking with rustc (when linking with
# cc_common.link linkstamps are handled by cc_common.link itself).
if not experimental_use_cc_common_link and crate_info.type in ("bin", "cdylib"):
# There is no other way to register an action for each member of a depset than
# flattening the depset as of 2021-10-12. Luckily, usually there is only one linkstamp
# in a build, and we only flatten the list on binary targets that perform transitive linking,
# so it's extremely unlikely that this call to `to_list()` will ever be a performance
# problem.
for linkstamp in linkstamps.to_list():
# The linkstamp output path is based on the binary crate
# name and the input linkstamp path. This is to disambiguate
# the linkstamp outputs produced by multiple binary crates
# that depend on the same linkstamp. We use the same pattern
# for the output name as the one used by native cc rules.
out_name = "_objs/" + crate_info.output.basename + "/" + linkstamp.file().path[:-len(linkstamp.file().extension)] + "o"
linkstamp_out = ctx.actions.declare_file(out_name)
linkstamp_outs.append(linkstamp_out)
cc_common.register_linkstamp_compile_action(
actions = ctx.actions,
cc_toolchain = cc_toolchain,
feature_configuration = feature_configuration,
grep_includes = ctx.file._grep_includes,
source_file = linkstamp.file(),
output_file = linkstamp_out,
compilation_inputs = linkstamp.hdrs(),
inputs_for_validation = nolinkstamp_compile_inputs,
label_replacement = str(ctx.label),
output_replacement = crate_info.output.path,
)
# If stamping is enabled include the volatile and stable status info file
stamp_info = [ctx.version_file, ctx.info_file] if stamp else []
compile_inputs = depset(
linkstamp_outs + stamp_info,
transitive = [
nolinkstamp_compile_inputs,
],
)
# For backwards compatibility, we also check the value of the `rustc_env_files` attribute when
# `crate_info.rustc_env_files` is not populated.
build_env_files = crate_info.rustc_env_files if crate_info.rustc_env_files else getattr(files, "rustc_env_files", [])
compile_inputs, out_dir, build_env_file, build_flags_files = _process_build_scripts(build_info, dep_info, compile_inputs)
if build_env_file:
build_env_files = [f for f in build_env_files] + [build_env_file]
compile_inputs = depset(build_env_files, transitive = [compile_inputs])
return compile_inputs, out_dir, build_env_files, build_flags_files, linkstamp_outs, ambiguous_libs
def construct_arguments(
ctx,
attr,
file,
toolchain,
tool_path,
cc_toolchain,
feature_configuration,
crate_info,
dep_info,
linkstamp_outs,
ambiguous_libs,
output_hash,
rust_flags,
out_dir,
build_env_files,
build_flags_files,
emit = ["dep-info", "link"],
force_all_deps_direct = False,
force_link = False,
stamp = False,
remap_path_prefix = "",
use_json_output = False,
build_metadata = False,
force_depend_on_objects = False):
"""Builds an Args object containing common rustc flags
Args:
ctx (ctx): The rule's context object
attr (struct): The attributes for the target. These may be different from ctx.attr in an aspect context.
file (struct): A struct containing files defined in label type attributes marked as `allow_single_file`.
toolchain (rust_toolchain): The current target's `rust_toolchain`
tool_path (str): Path to rustc
cc_toolchain (CcToolchain): The CcToolchain for the current target.
feature_configuration (FeatureConfiguration): Class used to construct command lines from CROSSTOOL features.
crate_info (CrateInfo): The CrateInfo provider of the target crate
dep_info (DepInfo): The DepInfo provider of the target crate
linkstamp_outs (list): Linkstamp outputs of native dependencies
ambiguous_libs (dict): Ambiguous libs, see `_disambiguate_libs`
output_hash (str): The hashed path of the crate root
rust_flags (list): Additional flags to pass to rustc
out_dir (str): The path to the output directory for the target Crate.
build_env_files (list): Files containing rustc environment variables, for instance from `cargo_build_script` actions.
build_flags_files (depset): The output files of a `cargo_build_script` actions containing rustc build flags
emit (list): Values for the --emit flag to rustc.
force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern
to the commandline as opposed to -L.
force_link (bool, optional): Whether to add link flags to the command regardless of `emit`.
stamp (bool, optional): Whether or not workspace status stamping is enabled. For more details see
https://docs.bazel.build/versions/main/user-manual.html#flag--stamp
remap_path_prefix (str, optional): A value used to remap `${pwd}` to. If set to None, no prefix will be set.
use_json_output (bool): Have rustc emit json and process_wrapper parse json messages to output rendered output.
build_metadata (bool): Generate CLI arguments for building *only* .rmeta files. This requires use_json_output.
force_depend_on_objects (bool): Force using `.rlib` object files instead of metadata (`.rmeta`) files even if they are available.
Returns:
tuple: A tuple of the following items
- (struct): A struct of arguments used to run the `Rustc` action
- process_wrapper_flags (Args): Arguments for the process wrapper
- rustc_path (Args): Arguments for invoking rustc via the process wrapper
- rustc_flags (Args): Rust flags for the Rust compiler
- all (list): A list of all `Args` objects in the order listed above.
This is to be passed to the `arguments` parameter of actions
- (dict): Common rustc environment variables
"""
if build_metadata and not use_json_output:
fail("build_metadata requires parse_json_output")
output_dir = getattr(crate_info.output, "dirname", None)
linker_script = getattr(file, "linker_script", None)
env = _get_rustc_env(attr, toolchain, crate_info.name)
# Wrapper args first
process_wrapper_flags = ctx.actions.args()
for build_env_file in build_env_files:
process_wrapper_flags.add("--env-file", build_env_file)
process_wrapper_flags.add_all(build_flags_files, before_each = "--arg-file")
# Certain rust build processes expect to find files from the environment
# variable `$CARGO_MANIFEST_DIR`. Examples of this include pest, tera,
# asakuma.
#
# The compiler and by extension proc-macros see the current working
# directory as the Bazel exec root. This is what `$CARGO_MANIFEST_DIR`
# would default to but is often the wrong value (e.g. if the source is in a
# sub-package or if we are building something in an external repository).
# Hence, we need to set `CARGO_MANIFEST_DIR` explicitly.
#
# Since we cannot get the `exec_root` from starlark, we cheat a little and
# use `${pwd}` which resolves the `exec_root` at action execution time.
process_wrapper_flags.add("--subst", "pwd=${pwd}")
# If stamping is enabled, enable the functionality in the process wrapper
if stamp:
process_wrapper_flags.add("--volatile-status-file", ctx.version_file)
process_wrapper_flags.add("--stable-status-file", ctx.info_file)
# Both ctx.label.workspace_root and ctx.label.package are relative paths
# and either can be empty strings. Avoid trailing/double slashes in the path.
components = "${{pwd}}/{}/{}".format(ctx.label.workspace_root, ctx.label.package).split("/")
env["CARGO_MANIFEST_DIR"] = "/".join([c for c in components if c])
if out_dir != None:
env["OUT_DIR"] = "${pwd}/" + out_dir
# Handle that the binary name and crate name may be different.
#
# If a target name contains a - then cargo (and rules_rust) will generate a
# crate name with _ instead. Accordingly, rustc will generate a output
# file (executable, or rlib, or whatever) with _ not -. But when cargo
# puts a binary in the target/${config} directory, and sets environment
# variables like `CARGO_BIN_EXE_${binary_name}` it will use the - version
# not the _ version. So we rename the rustc-generated file (with _s) to
# have -s if needed.
emit_with_paths = emit
if crate_info.type == "bin" and crate_info.output != None:
generated_file = crate_info.name + toolchain.binary_ext
src = "/".join([crate_info.output.dirname, generated_file])
dst = crate_info.output.path
if src != dst:
emit_with_paths = [("link=" + dst if val == "link" else val) for val in emit]
# Arguments for launching rustc from the process wrapper
rustc_path = ctx.actions.args()
rustc_path.add("--")
rustc_path.add(tool_path)
# Rustc arguments
rustc_flags = ctx.actions.args()
rustc_flags.set_param_file_format("multiline")
rustc_flags.use_param_file("@%s", use_always = False)
rustc_flags.add(crate_info.root)
rustc_flags.add("--crate-name=" + crate_info.name)
rustc_flags.add("--crate-type=" + crate_info.type)
error_format = "human"
if hasattr(attr, "_error_format"):
error_format = attr._error_format[ErrorFormatInfo].error_format
if use_json_output:
# If --error-format was set to json, we just pass the output through
# Otherwise process_wrapper uses the "rendered" field.
process_wrapper_flags.add("--rustc-output-format", "json" if error_format == "json" else "rendered")
# Configure rustc json output by adding artifact notifications.
# These will always be filtered out by process_wrapper and will be use to terminate
# rustc when appropriate.
json = ["artifacts"]
if error_format == "short":
json.append("diagnostic-short")
elif error_format == "human" and toolchain.os != "windows":
# If the os is not windows, we can get colorized output.
json.append("diagnostic-rendered-ansi")
rustc_flags.add("--json=" + ",".join(json))
error_format = "json"
if build_metadata:
# Configure process_wrapper to terminate rustc when metadata are emitted
process_wrapper_flags.add("--rustc-quit-on-rmeta", "true")
rustc_flags.add("--error-format=" + error_format)
# Mangle symbols to disambiguate crates with the same name. This could
# happen only for non-final artifacts where we compute an output_hash,
# e.g., rust_library.
#
# For "final" artifacts and ones intended for distribution outside of
# Bazel, such as rust_binary, rust_static_library and rust_shared_library,
# where output_hash is None we don't need to add these flags.
if output_hash:
extra_filename = "-" + output_hash
rustc_flags.add("--codegen=metadata=" + extra_filename)
rustc_flags.add("--codegen=extra-filename=" + extra_filename)
if output_dir:
rustc_flags.add("--out-dir=" + output_dir)
compilation_mode = get_compilation_mode_opts(ctx, toolchain)
rustc_flags.add("--codegen=opt-level=" + compilation_mode.opt_level)
rustc_flags.add("--codegen=debuginfo=" + compilation_mode.debug_info)
# For determinism to help with build distribution and such
if remap_path_prefix != None:
rustc_flags.add("--remap-path-prefix=${{pwd}}={}".format(remap_path_prefix))
if emit:
rustc_flags.add("--emit=" + ",".join(emit_with_paths))
if error_format != "json":
# Color is not compatible with json output.
rustc_flags.add("--color=always")
rustc_flags.add("--target=" + toolchain.target_flag_value)
if hasattr(attr, "crate_features"):
rustc_flags.add_all(getattr(attr, "crate_features"), before_each = "--cfg", format_each = 'feature="%s"')
if linker_script:
rustc_flags.add(linker_script.path, format = "--codegen=link-arg=-T%s")
# Gets the paths to the folders containing the standard library (or libcore)
rust_std_paths = toolchain.rust_std_paths.to_list()
# Tell Rustc where to find the standard library
rustc_flags.add_all(rust_std_paths, before_each = "-L", format_each = "%s")
rustc_flags.add_all(rust_flags)
# Deduplicate data paths due to https://github.com/bazelbuild/bazel/issues/14681
data_paths = depset(direct = getattr(attr, "data", []) + getattr(attr, "compile_data", [])).to_list()
rustc_flags.add_all(
expand_list_element_locations(
ctx,
getattr(attr, "rustc_flags", []),
data_paths,
),
)
add_edition_flags(rustc_flags, crate_info)
# Link!
if ("link" in emit and crate_info.type not in ["rlib", "lib"]) or force_link:
# Rust's built-in linker can handle linking wasm files. We don't want to attempt to use the cc
# linker since it won't understand.
if toolchain.target_arch != "wasm32":
if output_dir:
use_pic = _should_use_pic(cc_toolchain, feature_configuration, crate_info.type)
rpaths = _compute_rpaths(toolchain, output_dir, dep_info, use_pic)
else:
rpaths = depset([])
ld, link_args, link_env = get_linker_and_args(ctx, attr, cc_toolchain, feature_configuration, rpaths)
env.update(link_env)
rustc_flags.add("--codegen=linker=" + ld)
rustc_flags.add_joined("--codegen", link_args, join_with = " ", format_joined = "link-args=%s")
_add_native_link_flags(rustc_flags, dep_info, linkstamp_outs, ambiguous_libs, crate_info.type, toolchain, cc_toolchain, feature_configuration)
use_metadata = _depend_on_metadata(crate_info, force_depend_on_objects)
# These always need to be added, even if not linking this crate.
add_crate_link_flags(rustc_flags, dep_info, force_all_deps_direct, use_metadata)
needs_extern_proc_macro_flag = _is_proc_macro(crate_info) and crate_info.edition != "2015"
if needs_extern_proc_macro_flag:
rustc_flags.add("--extern")
rustc_flags.add("proc_macro")
if toolchain.llvm_cov and ctx.configuration.coverage_enabled:
rustc_flags.add("--codegen=instrument-coverage")
# Make bin crate data deps available to tests.
for data in getattr(attr, "data", []):
if rust_common.crate_info in data:
dep_crate_info = data[rust_common.crate_info]
if dep_crate_info.type == "bin":
# Trying to make CARGO_BIN_EXE_{} canonical across platform by strip out extension if exists
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
env["CARGO_BIN_EXE_" + env_basename] = dep_crate_info.output.short_path
# Add environment variables from the Rust toolchain.
env.update(toolchain.env)
# Update environment with user provided variables.
env.update(expand_dict_value_locations(
ctx,
crate_info.rustc_env,
data_paths,
))
# Ensure the sysroot is set for the target platform
env["SYSROOT"] = toolchain.sysroot
if toolchain._rename_first_party_crates:
env["RULES_RUST_THIRD_PARTY_DIR"] = toolchain._third_party_dir
# extra_rustc_flags apply to the target configuration, not the exec configuration.
if hasattr(ctx.attr, "_extra_rustc_flags") and not is_exec_configuration(ctx):
rustc_flags.add_all(ctx.attr._extra_rustc_flags[ExtraRustcFlagsInfo].extra_rustc_flags)
if hasattr(ctx.attr, "_extra_rustc_flag") and not is_exec_configuration(ctx):
rustc_flags.add_all(ctx.attr._extra_rustc_flag[ExtraRustcFlagsInfo].extra_rustc_flags)
if hasattr(ctx.attr, "_extra_exec_rustc_flags") and is_exec_configuration(ctx):
rustc_flags.add_all(ctx.attr._extra_exec_rustc_flags[ExtraExecRustcFlagsInfo].extra_exec_rustc_flags)
if hasattr(ctx.attr, "_extra_exec_rustc_flag") and is_exec_configuration(ctx):
rustc_flags.add_all(ctx.attr._extra_exec_rustc_flag[ExtraExecRustcFlagsInfo].extra_exec_rustc_flags)
# Create a struct which keeps the arguments separate so each may be tuned or
# replaced where necessary
args = struct(
process_wrapper_flags = process_wrapper_flags,
rustc_path = rustc_path,
rustc_flags = rustc_flags,
all = [process_wrapper_flags, rustc_path, rustc_flags],
)
return args, env
def rustc_compile_action(
ctx,
attr,
toolchain,
crate_info,
output_hash = None,
rust_flags = [],
force_all_deps_direct = False):
"""Create and run a rustc compile action based on the current rule's attributes
Args:
ctx (ctx): The rule's context object