-
Notifications
You must be signed in to change notification settings - Fork 565
Expand file tree
/
Copy pathrustc.bzl
More file actions
2820 lines (2416 loc) · 123 KB
/
rustc.bzl
File metadata and controls
2820 lines (2416 loc) · 123 KB
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_skylib//rules:common_settings.bzl", "BuildSettingInfo")
load(
"@bazel_tools//tools/build_defs/cc:action_names.bzl",
"CPP_LINK_DYNAMIC_LIBRARY_ACTION_NAME",
"CPP_LINK_EXECUTABLE_ACTION_NAME",
"CPP_LINK_NODEPS_DYNAMIC_LIBRARY_ACTION_NAME",
"CPP_LINK_STATIC_LIBRARY_ACTION_NAME",
)
load("@rules_cc//cc/common:cc_common.bzl", "cc_common")
load("@rules_cc//cc/common:cc_info.bzl", "CcInfo")
load(":common.bzl", "rust_common")
load(":compat.bzl", "abs")
load(":lto.bzl", "construct_lto_arguments")
load(
":providers.bzl",
"AllocatorLibrariesImplInfo",
"AllocatorLibrariesInfo",
"AlwaysEnableMetadataOutputGroupsInfo",
"LintsInfo",
"RustcOutputDiagnosticsInfo",
_BuildInfo = "BuildInfo",
)
load(":rustc_resource_set.bzl", "get_rustc_resource_set", "is_codegen_units_enabled")
load(":stamp.bzl", "is_stamping_enabled")
load(
":utils.bzl",
"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",
"is_std_dylib",
"make_static_lib_symlink",
"parse_env_strings",
"relativize",
)
# This feature is disabled unless one of the dependencies is a cc_library.
# Authors of C++ toolchains can place linker flags that should only be applied
# when linking with C objects in a feature with this name, or require this
# feature from other features which needs to be disabled together.
RUST_LINK_CC_FEATURE = "rules_rust_link_cc"
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) + "]"},
)
ExtraRustcEnvInfo = provider(
doc = "Pass each value as an environment variable to non-exec rustc invocations",
fields = {"extra_rustc_env": "List[string] Extra env to pass to rustc in non-exec configuration"},
)
ExtraExecRustcEnvInfo = provider(
doc = "Pass each value as an environment variable to exec rustc invocations",
fields = {"extra_exec_rustc_env": "List[string] Extra env to pass to rustc in exec configuration"},
)
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"},
)
PerCrateRustcFlagsInfo = provider(
doc = "Pass each value as an additional flag to non-exec rustc invocations for crates matching the provided filter",
fields = {"per_crate_rustc_flags": "List[string] Extra flags to pass to rustc in non-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": "" if toolchain.target_arch == None else toolchain.target_arch,
"CARGO_CFG_TARGET_OS": "" if toolchain.target_os == None else toolchain.target_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):
# 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"))
def _should_use_pic(cc_toolchain, feature_configuration, crate_type, compilation_mode):
"""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.
compilation_mode: The compilation mode.
Returns:
bool: Whether or not [PIC][pic] should be enabled.
"""
# We use the same logic to select between `pic` and `nopic` outputs as the C++ rules:
# - For shared libraries - we use `pic`. This covers `dylib`, `cdylib` and `proc-macro` crate types.
# - In `fastbuild` and `dbg` mode we use `pic` by default.
# - In `opt` mode we use `nopic` outputs to build binaries.
if cc_toolchain and crate_type in ("cdylib", "dylib", "proc-macro"):
return cc_toolchain.needs_pic_for_dynamic_libraries(feature_configuration = feature_configuration)
elif compilation_mode in ("fastbuild", "dbg"):
return True
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):
"""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.
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 when applicable.
"""
direct_deps = []
direct_crates = []
transitive_crates = []
transitive_data = []
transitive_proc_macro_data = []
transitive_noncrates = []
direct_build_infos = []
transitive_build_infos = []
direct_link_search_paths = []
transitive_link_search_paths = []
build_info = None
linkstamps = []
direct_crate_outputs = []
transitive_crate_outputs = []
direct_metadata_outputs = []
transitive_metadata_outputs = []
crate_deps = []
for dep in deps + proc_macro_deps:
crate_group = getattr(dep, "crate_group_info", None)
if crate_group:
crate_deps.extend(crate_group.dep_variant_infos.to_list())
else:
crate_deps.append(dep)
aliases = {k.label: v for k, v in aliases.items()}
for dep in crate_deps:
crate_info = dep.crate_info
dep_info = dep.dep_info
cc_info = dep.cc_info
dep_build_info = dep.build_info
if cc_info:
for li in cc_info.linking_context.linker_inputs.to_list():
linkstamps.extend(li.linkstamps)
if crate_info:
# This dependency is a rust_library
direct_deps.append(AliasableDepInfo(
name = aliases.get(crate_info.owner, crate_info.name),
dep = crate_info,
))
is_proc_macro = _is_proc_macro(crate_info)
direct_crates.append(crate_info)
if not is_proc_macro:
transitive_crates.append(dep_info.transitive_crates)
if is_proc_macro:
# This crate's data and its non-macro dependencies' data are proc macro data.
transitive_proc_macro_data.append(crate_info.data)
transitive_proc_macro_data.append(dep_info.transitive_data)
else:
# This crate's proc macro dependencies' data are proc macro data.
transitive_proc_macro_data.append(dep_info.transitive_proc_macro_data)
# Track transitive non-macro data in case a proc macro depends on this crate.
transitive_data.append(crate_info.data)
transitive_data.append(dep_info.transitive_data)
# 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 or not crate_info.metadata_supports_pipelining:
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.
direct_metadata_outputs.append(depend_on)
if not is_proc_macro:
transitive_metadata_outputs.append(dep_info.transitive_metadata_outputs)
direct_crate_outputs.append(crate_info.output)
if not is_proc_macro:
transitive_crate_outputs.append(dep_info.transitive_crate_outputs)
if not is_proc_macro:
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 or dep_build_info:
if cc_info:
# This dependency is a cc_library
transitive_noncrates.append(cc_info.linking_context.linker_inputs)
if 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
direct_build_infos.append(build_info)
if build_info.link_search_paths:
direct_link_search_paths.append(build_info.link_search_paths)
transitive_data.append(build_info.compile_data)
else:
fail("rust targets can only depend on rust_library, rust_*_library or cc_library " +
"targets.")
return (
rust_common.dep_info(
direct_crates = depset(direct_deps),
transitive_crates = depset(
direct_crates,
transitive = transitive_crates,
),
transitive_data = depset(
transitive = transitive_data,
),
transitive_proc_macro_data = depset(
transitive = transitive_proc_macro_data,
),
transitive_noncrates = depset(
transitive = transitive_noncrates,
order = "topological", # dylib link flag ordering matters.
),
transitive_crate_outputs = depset(
direct_crate_outputs,
transitive = transitive_crate_outputs,
),
transitive_metadata_outputs = depset(
direct_metadata_outputs,
transitive = transitive_metadata_outputs,
),
transitive_build_infos = depset(
direct_build_infos,
transitive = transitive_build_infos,
),
link_search_path_files = depset(
direct_link_search_paths,
transitive = transitive_link_search_paths,
),
dep_env = build_info.dep_env if build_info else None,
),
build_info,
depset(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_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, crate_type, toolchain, cc_toolchain, feature_configuration, rpaths, add_flags_for_binary = False):
"""Gathers cc_common linker information
Args:
ctx (ctx): The current target's context object
crate_type (str): The target crate's type (i.e. "bin", "proc-macro", etc.).
toolchain (rust_toolchain): The current Rust toolchain.
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.
add_flags_for_binary (bool, optional): Whether to add "bin" link flags to the command regardless of `crate_type`.
Returns:
tuple: A tuple of the following items:
- (str): The tool path for given action.
- (bool): Whether or not the linker is a direct driver (e.g. `ld`) vs a wrapper (e.g. `gcc`).
- (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)
ld = None
ld_is_direct_driver = False
link_args = []
link_env = {}
if cc_toolchain:
if crate_type in ("bin") or add_flags_for_binary:
is_linking_dynamic_library = False
action_name = CPP_LINK_EXECUTABLE_ACTION_NAME
elif crate_type in ("dylib"):
is_linking_dynamic_library = True
action_name = CPP_LINK_NODEPS_DYNAMIC_LIBRARY_ACTION_NAME
elif crate_type in ("staticlib"):
is_linking_dynamic_library = False
action_name = CPP_LINK_STATIC_LIBRARY_ACTION_NAME
elif crate_type in ("cdylib", "proc-macro"):
# Proc macros get compiled as shared libraries to be loaded by the compiler.
is_linking_dynamic_library = True
action_name = CPP_LINK_DYNAMIC_LIBRARY_ACTION_NAME
elif crate_type in ("lib", "rlib"):
fail("Invalid `crate_type` for linking action: {}".format(crate_type))
else:
fail("Unknown `crate_type`: {}".format(crate_type))
link_variables = cc_common.create_link_variables(
feature_configuration = feature_configuration,
cc_toolchain = cc_toolchain,
is_linking_dynamic_library = is_linking_dynamic_library,
runtime_library_search_directories = rpaths,
user_link_flags = user_link_flags,
)
link_args.extend(cc_common.get_memory_inefficient_command_line(
feature_configuration = feature_configuration,
action_name = action_name,
variables = link_variables,
))
link_env = cc_common.get_environment_variables(
feature_configuration = feature_configuration,
action_name = action_name,
variables = link_variables,
)
ld = cc_common.get_tool_for_action(
feature_configuration = feature_configuration,
action_name = action_name,
)
ld_is_direct_driver = False
if not ld or toolchain.linker_preference == "rust":
ld = toolchain.linker.path
ld_is_direct_driver = toolchain.linker_type == "direct"
# When using rust-lld directly, we still need library search paths from cc_toolchain
# to find system libraries that rustc's stdlib depends on (like -lgcc_s, -lutil, etc.)
# Filter link_args to only include flags that help locate libraries.
if cc_toolchain and link_args:
filtered_args = []
skip_next = False
for i, arg in enumerate(link_args):
if skip_next:
skip_next = False
continue
# Strip -Wl, prefix if using direct driver (it's only for compiler drivers)
processed_arg = arg
if ld_is_direct_driver and arg.startswith("-Wl,"):
# Remove -Wl, prefix and split on commas (e.g., "-Wl,-rpath,/path" -> ["-rpath", "/path"])
# For now, we'll handle common cases; complex -Wl, args might need more sophisticated handling
processed_arg = arg[4:] # Strip "-Wl,"
# Handle macOS version flag: convert -mmacos-version-min=X.Y to -macos_version_min X.Y
if processed_arg.startswith("-mmacos-version-min="):
version = processed_arg.split("=", 1)[1]
filtered_args.append("-macos_version_min")
filtered_args.append(version)
# Keep library search path flags
elif processed_arg.startswith("-L"):
filtered_args.append(processed_arg)
# Keep sysroot flags (as single or two-part arguments)
elif processed_arg == "--sysroot" or processed_arg.startswith("--sysroot="):
filtered_args.append(processed_arg)
if processed_arg == "--sysroot" and i + 1 < len(link_args):
# Two-part argument, keep the next arg too
filtered_args.append(link_args[i + 1])
skip_next = True
# Keep dynamic linker flags
elif processed_arg.startswith("--dynamic-linker") or processed_arg == "--dynamic-linker":
filtered_args.append(processed_arg)
if processed_arg == "--dynamic-linker" and i + 1 < len(link_args):
filtered_args.append(link_args[i + 1])
skip_next = True
# Keep rpath-related flags
elif processed_arg.startswith("-rpath") or processed_arg.startswith("--rpath"):
filtered_args.append(processed_arg)
link_args = filtered_args
if not ld:
fail("No linker available for rustc. Either `rust_toolchain.linker` must be set or a `cc_toolchain` configured for the current configuration.")
if "LIB" in link_env:
# Needed to ensure that link.exe will use msvcrt.lib from the cc_toolchain,
# and not a non-hermetic system version.
# https://github.com/bazelbuild/rules_rust/issues/3256
# I don't see a good way to stop rustc from adding the non-hermetic library search path,
# so put our cc_toolchain library search path on the command line where it has
# precedence over the non-hermetic path injected by rustc.
link_args.extend([
"-LIBPATH:" + element
for element in link_env["LIB"].split(";")
])
return ld, ld_is_direct_driver, link_args, link_env
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.target_os.startswith("windows") else get_lib_name_default(lib)
if toolchain.target_os.startswith("windows"):
prefix = ""
extension = ".lib"
elif lib_name.endswith(".pic"):
# Strip the .pic suffix
lib_name = lib_name[:-4]
prefix = "lib"
extension = ".pic.a"
else:
prefix = "lib"
extension = ".a"
# 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.target_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.target_os.startswith(("linux", "mac", "darwin")) and
artifact.basename.endswith(".a") and not artifact.basename.startswith("lib")
) or (
toolchain.target_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, experimental_use_cc_common_link = False):
"""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.
When experimental_use_cc_common_link is True, bin/cdylib crates also use hollow
rlib deps. The rustc step only emits .o files (no rustc linking), so SVH chain
consistency is sufficient; the actual linking is done by cc_common.link, which
does not check SVH.
Callers are responsible for zeroing out experimental_use_cc_common_link for
exec-platform builds before calling this function (see rustc_compile_action).
Exec-platform binaries (build scripts) must use full rlib deps because their
CcInfo linking contexts may lack a CC toolchain.
Args:
crate_info (CrateInfo): The Crate to determine this for.
force_depend_on_objects (bool): if set we will not depend on metadata.
experimental_use_cc_common_link (bool): if set, bin/cdylib crates also use
hollow rlib deps for SVH consistency. Must already be False for
exec-platform builds when this function is called.
Returns:
Whether we can depend on metadata for this crate.
"""
if force_depend_on_objects:
return False
if experimental_use_cc_common_link and crate_info.type in ("bin", "cdylib"):
# cc_common.link: rustc only emits .o files, so hollow rlib deps are safe and
# keep the SVH chain consistent (avoiding E0460 from nondeterministic proc macros).
return True
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,
lint_files,
stamp = False,
force_depend_on_objects = False,
experimental_use_cc_common_link = False,
include_link_flags = True):
"""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 (struct): A struct of all inputs (`ctx.files`). When aspects are involved, the rule context
may not correspond to a rust target, so check that files attributes are present before accessing them.
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.
lint_files (list): List of files with rustc args for the Crate's lint 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.
include_link_flags (bool, optional): Whether to include flags like `-l` that instruct the linker to search for a library.
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", None)
# TODO: As of writing this comment Bazel used Java CcToolchainInfo.
# However there is ongoing work to rewrite provider in Starlark.
# rules_rust is not coupled with Bazel release. Remove conditional and change to
# _linker_files once Starlark CcToolchainInfo is visible to Bazel.
# https://github.com/bazelbuild/rules_rust/issues/2425
if not cc_toolchain:
linker_depset = depset()
elif hasattr(cc_toolchain, "_linker_files"):
linker_depset = cc_toolchain._linker_files
else:
linker_depset = cc_toolchain.linker_files()
compilation_mode = ctx.var["COMPILATION_MODE"]
use_pic = _should_use_pic(cc_toolchain, feature_configuration, crate_info.type, compilation_mode)
# 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.
libs_from_linker_inputs = []
ambiguous_libs = {}
if crate_info.type not in ("lib", "rlib"):
linker_inputs = dep_info.transitive_noncrates.to_list()
ambiguous_libs = _disambiguate_libs(ctx.actions, toolchain, crate_info, dep_info, use_pic)
libs_from_linker_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, experimental_use_cc_common_link):
transitive_crate_outputs = dep_info.transitive_metadata_outputs
nolinkstamp_compile_direct_inputs = []
if build_info:
if build_info.rustc_env:
nolinkstamp_compile_direct_inputs.append(build_info.rustc_env)
if build_info.flags:
nolinkstamp_compile_direct_inputs.append(build_info.flags)
# The old default behavior was to include data files at compile time.
# This flag controls whether to include data files in compile_data.
if not toolchain._incompatible_do_not_include_data_in_compile_data and hasattr(files, "data"):
nolinkstamp_compile_direct_inputs += files.data
if toolchain.target_json:
nolinkstamp_compile_direct_inputs.append(toolchain.target_json)
if linker_script:
nolinkstamp_compile_direct_inputs.append(linker_script)
if not cc_toolchain:
runtime_libs = depset()
elif crate_info.type in ["dylib", "cdylib"]:
# For shared libraries we want to link C++ runtime library dynamically
# (for example libstdc++.so or libc++.so).
runtime_libs = cc_toolchain.dynamic_runtime_lib(feature_configuration = feature_configuration)
else:
runtime_libs = cc_toolchain.static_runtime_lib(feature_configuration = feature_configuration)
nolinkstamp_compile_inputs = depset(
nolinkstamp_compile_direct_inputs +
([] if experimental_use_cc_common_link else libs_from_linker_inputs),
transitive = [
crate_info.srcs,
transitive_crate_outputs,
# Always include hollow rlibs so they are present in the sandbox for
# -Ldependency= resolution. Binaries and proc-macros compile against full
# rlib --extern deps but need hollow rlibs available for transitive
# dependency resolution when those rlibs were themselves compiled against
# hollow deps. For rlib/lib crates this is a no-op (already included above).
dep_info.transitive_metadata_outputs,
crate_info.compile_data,
dep_info.transitive_proc_macro_data,
toolchain.all_files,
] + ([] if experimental_use_cc_common_link else [
runtime_libs,
linker_depset,
]),
)
# 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", "proc-macro"):
# 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,
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,
],
)
build_script_compile_inputs, out_dir, build_env_file, build_flags_files = _process_build_scripts(
build_info = build_info,
dep_info = dep_info,
include_link_flags = include_link_flags,
)
# TODO(parkmycar): Cleanup the handling of lint_files here.
if lint_files:
build_flags_files = depset(lint_files, transitive = [build_flags_files])
# 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", [])
if build_env_file:
build_env_files = list(build_env_files)
build_env_files.append(build_env_file)
compile_inputs = depset(build_env_files + lint_files, transitive = [build_script_compile_inputs, compile_inputs])
return compile_inputs, out_dir, build_env_files, build_flags_files, linkstamp_outs, ambiguous_libs
def _will_emit_object_file(emit):
for e in emit:
if e == "obj" or e.startswith("obj="):
return True
return False
def _remove_codegen_units(flag):
return None if flag.startswith("-Ccodegen-units") else flag
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,
add_flags_for_binary = False,
include_link_flags = True,
stamp = False,
remap_path_prefix = ".",
use_json_output = False,
build_metadata = False,
force_depend_on_objects = False,
experimental_use_cc_common_link = False,
skip_expanding_rustc_env = False,
require_explicit_unstable_features = False,
error_format = None):
"""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.
add_flags_for_binary (bool, optional): Whether to add "bin" link flags to the command regardless of `emit` and `crate_type`.
include_link_flags (bool, optional): Whether to include flags like `-l` that instruct the linker to search for a library.
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.
skip_expanding_rustc_env (bool): Whether to skip expanding CrateInfo.rustc_env_attr
require_explicit_unstable_features (bool): Whether to require all unstable features to be explicitly opted in to using `-Zallow-features=...`.
error_format (str, optional): Error format to pass to the `--error-format` command line argument. If set to None, uses the "_error_format" entry in `attr`.
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")
if require_explicit_unstable_features: