aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/rules/cpp/CppLinkAction.java
blob: 3779c61fffc1009cd8032c963ef09f10185d5a2e (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
// Copyright 2014 Google Inc. 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.

package com.google.devtools.build.lib.rules.cpp;

import static java.nio.charset.StandardCharsets.ISO_8859_1;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.AbstractAction;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.ActionExecutionException;
import com.google.devtools.build.lib.actions.ActionOwner;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ExecException;
import com.google.devtools.build.lib.actions.Executor;
import com.google.devtools.build.lib.actions.ParameterFile;
import com.google.devtools.build.lib.actions.ResourceSet;
import com.google.devtools.build.lib.actions.extra.CppLinkInfo;
import com.google.devtools.build.lib.actions.extra.ExtraActionInfo;
import com.google.devtools.build.lib.analysis.AnalysisEnvironment;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.TransitiveInfoProvider;
import com.google.devtools.build.lib.analysis.actions.ParameterFileWriteAction;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.collect.CollectionUtils;
import com.google.devtools.build.lib.collect.ImmutableIterable;
import com.google.devtools.build.lib.collect.IterablesChain;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadCompatible;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
import com.google.devtools.build.lib.packages.RuleErrorConsumer;
import com.google.devtools.build.lib.rules.cpp.Link.LinkStaticness;
import com.google.devtools.build.lib.rules.cpp.Link.LinkTargetType;
import com.google.devtools.build.lib.rules.cpp.LinkerInputs.LibraryToLink;
import com.google.devtools.build.lib.util.Fingerprint;
import com.google.devtools.build.lib.util.OS;
import com.google.devtools.build.lib.util.ShellEscaper;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Nullable;

/**
 * Action that represents a linking step.
 */
@ThreadCompatible
public final class CppLinkAction extends AbstractAction {
  /**
   * An abstraction for creating intermediate and output artifacts for C++ linking.
   *
   * <p>This is unfortunately necessary, because most of the time, these artifacts are well-behaved
   * ones sitting under a package directory, but nativedeps link actions can be shared. In order to
   * avoid creating every artifact here with {@code getShareableArtifact()}, we abstract the
   * artifact creation away.
   */
  public interface LinkArtifactFactory {
    /**
     * Create an artifact at the specified root-relative path in the bin directory.
     */
    Artifact create(RuleContext ruleContext, PathFragment rootRelativePath);
  }

  /**
   * An implementation of {@link LinkArtifactFactory} that can only create artifacts in the package
   * directory.
   */
  public static final LinkArtifactFactory DEFAULT_ARTIFACT_FACTORY = new LinkArtifactFactory() {
    @Override
    public Artifact create(RuleContext ruleContext, PathFragment rootRelativePath) {
      return ruleContext.getDerivedArtifact(rootRelativePath,
          ruleContext.getConfiguration().getBinDirectory());
    }
  };

  private static final String LINK_GUID = "58ec78bd-1176-4e36-8143-439f656b181d";
  private static final String FAKE_LINK_GUID = "da36f819-5a15-43a9-8a45-e01b60e10c8b";

  private final CppConfiguration cppConfiguration;
  private final LibraryToLink outputLibrary;
  private final LibraryToLink interfaceOutputLibrary;

  private final LinkCommandLine linkCommandLine;

  /** True for cc_fake_binary targets. */
  private final boolean fake;
  private final boolean isLTOIndexing;

  // This is set for both LTO indexing and LTO linking.
  @Nullable private final Iterable<LTOBackendArtifacts> allLTOBackendArtifacts;
  private final Iterable<Artifact> mandatoryInputs;

  // Linking uses a lot of memory; estimate 1 MB per input file, min 1.5 Gib.
  // It is vital to not underestimate too much here,
  // because running too many concurrent links can
  // thrash the machine to the point where it stops
  // responding to keystrokes or mouse clicks.
  // CPU and IO do not scale similarly and still use the static minimum estimate.
  public static final ResourceSet LINK_RESOURCES_PER_INPUT =
      ResourceSet.createWithRamCpuIo(1, 0, 0);

  // This defines the minimum of each resource that will be reserved.
  public static final ResourceSet MIN_STATIC_LINK_RESOURCES =
      ResourceSet.createWithRamCpuIo(1536, 1, 0.3);

  // Dynamic linking should be cheaper than static linking.
  public static final ResourceSet MIN_DYNAMIC_LINK_RESOURCES =
      ResourceSet.createWithRamCpuIo(1024, 0.3, 0.2);

  /**
   * Use {@link Builder} to create instances of this class. Also see there for
   * the documentation of all parameters.
   *
   * <p>This constructor is intentionally private and is only to be called from
   * {@link Builder#build()}.
   */
  private CppLinkAction(
      ActionOwner owner,
      Iterable<Artifact> inputs,
      ImmutableList<Artifact> outputs,
      CppConfiguration cppConfiguration,
      LibraryToLink outputLibrary,
      LibraryToLink interfaceOutputLibrary,
      boolean fake,
      boolean isLTOIndexing,
      Iterable<LTOBackendArtifacts> allLTOBackendArtifacts,
      LinkCommandLine linkCommandLine) {
    super(owner, inputs, outputs);
    this.mandatoryInputs = inputs;
    this.cppConfiguration = cppConfiguration;
    this.outputLibrary = outputLibrary;
    this.interfaceOutputLibrary = interfaceOutputLibrary;
    this.fake = fake;
    this.isLTOIndexing = isLTOIndexing;
    this.allLTOBackendArtifacts = allLTOBackendArtifacts;
    this.linkCommandLine = linkCommandLine;
  }

  private static Iterable<LinkerInput> filterLinkerInputs(Iterable<LinkerInput> inputs) {
    return Iterables.filter(inputs, new Predicate<LinkerInput>() {
      @Override
      public boolean apply(LinkerInput input) {
        return Link.VALID_LINKER_INPUTS.matches(input.getArtifact().getFilename());
      }
    });
  }

  private static Iterable<Artifact> filterLinkerInputArtifacts(Iterable<Artifact> inputs) {
    return Iterables.filter(inputs, new Predicate<Artifact>() {
      @Override
      public boolean apply(Artifact input) {
        return Link.VALID_LINKER_INPUTS.matches(input.getFilename());
      }
    });
  }

  private CppConfiguration getCppConfiguration() {
    return cppConfiguration;
  }

  @VisibleForTesting
  public String getTargetCpu() {
    return getCppConfiguration().getTargetCpu();
  }

  public String getHostSystemName() {
    return getCppConfiguration().getHostSystemName();
  }

  public ImmutableMap<String, String> getEnvironment() {
    if (OS.getCurrent() == OS.WINDOWS) {
      // TODO(bazel-team): Both GCC and clang rely on their execution directories being on
      // PATH, otherwise they fail to find dependent DLLs (and they fail silently...). On
      // the other hand, Windows documentation says that the directory of the executable
      // is always searched for DLLs first. Not sure what to make of it.
      // Other options are to forward the system path (brittle), or to add a PATH field to
      // the crosstool file.
      //
      // @see com.google.devtools.build.lib.rules.cpp.CppCompileAction#getEnvironment.
      return ImmutableMap.of(
          "PATH",
          cppConfiguration.getToolPathFragment(CppConfiguration.Tool.GCC).getParentDirectory()
              .getPathString()
      );
    }
    return ImmutableMap.of();
  }

  /**
   * Returns the link configuration; for correctness you should not call this method during
   * execution - only the argv is part of the action cache key, and we therefore don't guarantee
   * that the action will be re-executed if the contents change in a way that does not affect the
   * argv.
   */
  @VisibleForTesting
  public LinkCommandLine getLinkCommandLine() {
    return linkCommandLine;
  }

  public LibraryToLink getOutputLibrary() {
    return outputLibrary;
  }

  public LibraryToLink getInterfaceOutputLibrary() {
    return interfaceOutputLibrary;
  }

  /**
   * Returns the path to the output artifact produced by the linker.
   */
  public Path getOutputFile() {
    return outputLibrary.getArtifact().getPath();
  }

  @VisibleForTesting
  public List<String> getRawLinkArgv() {
    return linkCommandLine.getRawLinkArgv();
  }

  @VisibleForTesting
  public List<String> getArgv() {
    return linkCommandLine.arguments();
  }

  /**
   * Returns the command line specification for this link, included any required linkstamp
   * compilation steps. The command line may refer to a .params file.
   *
   * @return a finalized command line suitable for execution
   */
  public final List<String> getCommandLine() {
    return linkCommandLine.getCommandLine();
  }

  Iterable<LTOBackendArtifacts> getAllLTOBackendArtifacts() {
    return allLTOBackendArtifacts;
  }

  @Override
  @ThreadCompatible
  public void execute(
      ActionExecutionContext actionExecutionContext)
          throws ActionExecutionException, InterruptedException {
    if (fake) {
      executeFake();
    } else {
      Executor executor = actionExecutionContext.getExecutor();

      try {
        executor.getContext(CppLinkActionContext.class).exec(
            this, actionExecutionContext);
      } catch (ExecException e) {
        throw e.toActionExecutionException("Linking of rule '" + getOwner().getLabel() + "'",
            executor.getVerboseFailures(), this);
      }
    }
  }

  @Override
  public String describeStrategy(Executor executor) {
    return fake
        ? "fake,local"
        : executor.getContext(CppLinkActionContext.class).strategyLocality(this);
  }

  // Don't forget to update FAKE_LINK_GUID if you modify this method.
  @ThreadCompatible
  private void executeFake()
      throws ActionExecutionException {
    // The uses of getLinkConfiguration in this method may not be consistent with the computed key.
    // I.e., this may be incrementally incorrect.
    final Collection<Artifact> linkstampOutputs = getLinkCommandLine().getLinkstamps().values();

    // Prefix all fake output files in the command line with $TEST_TMPDIR/.
    final String outputPrefix = "$TEST_TMPDIR/";
    List<String> escapedLinkArgv = escapeLinkArgv(linkCommandLine.getRawLinkArgv(),
        linkstampOutputs, outputPrefix);
    // Write the commands needed to build the real target to the fake target
    // file.
    StringBuilder s = new StringBuilder();
    Joiner.on('\n').appendTo(s,
        "# This is a fake target file, automatically generated.",
        "# Do not edit by hand!",
        "echo $0 is a fake target file and not meant to be executed.",
        "exit 0",
        "EOS",
        "",
        "makefile_dir=.",
        "");

    try {
      // Concatenate all the (fake) .o files into the result.
      for (LinkerInput linkerInput : getLinkCommandLine().getLinkerInputs()) {
        Artifact objectFile = linkerInput.getArtifact();
        if ((CppFileTypes.OBJECT_FILE.matches(objectFile.getFilename())
                || CppFileTypes.PIC_OBJECT_FILE.matches(objectFile.getFilename()))
            && linkerInput.isFake()) {
          s.append(FileSystemUtils.readContentAsLatin1(objectFile.getPath())); // (IOException)
        }
      }

      s.append(getOutputFile().getBaseName()).append(": ");
      for (Artifact linkstamp : linkstampOutputs) {
        s.append("mkdir -p " + outputPrefix +
            linkstamp.getExecPath().getParentDirectory() + " && ");
      }
      Joiner.on(' ').appendTo(s,
          ShellEscaper.escapeAll(linkCommandLine.finalizeAlreadyEscapedWithLinkstampCommands(
              escapedLinkArgv, outputPrefix)));
      s.append('\n');
      if (getOutputFile().exists()) {
        getOutputFile().setWritable(true); // (IOException)
      }
      FileSystemUtils.writeContent(getOutputFile(), ISO_8859_1, s.toString());
      getOutputFile().setExecutable(true); // (IOException)
      for (Artifact linkstamp : linkstampOutputs) {
        FileSystemUtils.touchFile(linkstamp.getPath());
      }
    } catch (IOException e) {
      throw new ActionExecutionException("failed to create fake link command for rule '" +
                                         getOwner().getLabel() + ": " + e.getMessage(),
                                         this, false);
    }
  }

  /**
   * Shell-escapes the raw link command line.
   *
   * @param rawLinkArgv raw link command line
   * @param linkstampOutputs linkstamp artifacts
   * @param outputPrefix to be prepended to any outputs
   * @return escaped link command line
   */
  private List<String> escapeLinkArgv(List<String> rawLinkArgv,
      final Collection<Artifact> linkstampOutputs, final String outputPrefix) {
    final List<String> linkstampExecPaths = Artifact.asExecPaths(linkstampOutputs);
    ImmutableList.Builder<String> escapedArgs = ImmutableList.builder();
    for (String rawArg : rawLinkArgv) {
      String escapedArg;
      if (rawArg.equals(getPrimaryOutput().getExecPathString())
          || linkstampExecPaths.contains(rawArg)) {
        escapedArg = outputPrefix + ShellEscaper.escapeString(rawArg);
      } else if (rawArg.startsWith(Link.FAKE_OBJECT_PREFIX)) {
        escapedArg = outputPrefix + ShellEscaper.escapeString(
            rawArg.substring(Link.FAKE_OBJECT_PREFIX.length()));
      } else {
        escapedArg = ShellEscaper.escapeString(rawArg);
      }
      escapedArgs.add(escapedArg);
    }
    return escapedArgs.build();
  }

  @Override
  public ExtraActionInfo.Builder getExtraActionInfo() {
    // The uses of getLinkConfiguration in this method may not be consistent with the computed key.
    // I.e., this may be incrementally incorrect.
    CppLinkInfo.Builder info = CppLinkInfo.newBuilder();
    info.addAllInputFile(Artifact.toExecPaths(
        LinkerInputs.toLibraryArtifacts(getLinkCommandLine().getLinkerInputs())));
    info.addAllInputFile(Artifact.toExecPaths(
        LinkerInputs.toLibraryArtifacts(getLinkCommandLine().getRuntimeInputs())));
    info.setOutputFile(getPrimaryOutput().getExecPathString());
    if (interfaceOutputLibrary != null) {
      info.setInterfaceOutputFile(interfaceOutputLibrary.getArtifact().getExecPathString());
    }
    info.setLinkTargetType(getLinkCommandLine().getLinkTargetType().name());
    info.setLinkStaticness(getLinkCommandLine().getLinkStaticness().name());
    info.addAllLinkStamp(Artifact.toExecPaths(getLinkCommandLine().getLinkstamps().values()));
    info.addAllBuildInfoHeaderArtifact(
        Artifact.toExecPaths(getLinkCommandLine().getBuildInfoHeaderArtifacts()));
    info.addAllLinkOpt(getLinkCommandLine().getLinkopts());

    return super.getExtraActionInfo()
        .setExtension(CppLinkInfo.cppLinkInfo, info.build());
  }

  @Override
  protected String computeKey() {
    Fingerprint f = new Fingerprint();
    f.addString(fake ? FAKE_LINK_GUID : LINK_GUID);
    f.addString(getCppConfiguration().getLdExecutable().getPathString());
    f.addStrings(linkCommandLine.arguments());
    // TODO(bazel-team): For correctness, we need to ensure the invariant that all values accessed
    // during the execution phase are also covered by the key. Above, we add the argv to the key,
    // which covers most cases. Unfortunately, the extra action and fake support methods above also
    // sometimes directly access settings from the link configuration that may or may not affect the
    // key. We either need to change the code to cover them in the key computation, or change the
    // LinkConfiguration to disallow the combinations where the value of a setting does not affect
    // the argv.
    f.addBoolean(linkCommandLine.isNativeDeps());
    f.addBoolean(linkCommandLine.useTestOnlyFlags());
    if (linkCommandLine.getRuntimeSolibDir() != null) {
      f.addPath(linkCommandLine.getRuntimeSolibDir());
    }
    f.addBoolean(isLTOIndexing);
    return f.hexDigestAndReset();
  }

  @Override
  public String describeKey() {
    StringBuilder message = new StringBuilder();
    if (fake) {
      message.append("Fake ");
    }
    message.append(getProgressMessage());
    message.append('\n');
    message.append("  Command: ");
    message.append(
        ShellEscaper.escapeString(getCppConfiguration().getLdExecutable().getPathString()));
    message.append('\n');
    // Outputting one argument per line makes it easier to diff the results.
    for (String argument : ShellEscaper.escapeAll(linkCommandLine.arguments())) {
      message.append("  Argument: ");
      message.append(argument);
      message.append('\n');
    }
    return message.toString();
  }

  @Override
  public String getMnemonic() {
    return (isLTOIndexing) ? "CppLTOIndexing" : "CppLink";
  }

  @Override
  protected String getRawProgressMessage() {
    return (isLTOIndexing ? "LTO indexing " : "Linking ")
        + outputLibrary.getArtifact().prettyPrint();
  }

  @Override
  public ResourceSet estimateResourceConsumption(Executor executor) {
    return executor.getContext(CppLinkActionContext.class).estimateResourceConsumption(this);
  }

  /**
   * Estimate the resources consumed when this action is run locally.
   */
  public ResourceSet estimateResourceConsumptionLocal() {
    // It's ok if this behaves differently even if the key is identical.
    ResourceSet minLinkResources =
        getLinkCommandLine().getLinkStaticness() == Link.LinkStaticness.DYNAMIC
        ? MIN_DYNAMIC_LINK_RESOURCES
        : MIN_STATIC_LINK_RESOURCES;

    final int inputSize = Iterables.size(getLinkCommandLine().getLinkerInputs())
        + Iterables.size(getLinkCommandLine().getRuntimeInputs());

    return ResourceSet.createWithRamCpuIo(
        Math.max(inputSize * LINK_RESOURCES_PER_INPUT.getMemoryMb(),
            minLinkResources.getMemoryMb()),
        Math.max(inputSize * LINK_RESOURCES_PER_INPUT.getCpuUsage(),
            minLinkResources.getCpuUsage()),
        Math.max(inputSize * LINK_RESOURCES_PER_INPUT.getIoUsage(),
            minLinkResources.getIoUsage())
    );
  }

  @Override
  public Iterable<Artifact> getMandatoryInputs() {
    return mandatoryInputs;
  }

  /**
   * Determines whether or not this link should output a symbol counts file.
   */
  public static boolean enableSymbolsCounts(
      CppConfiguration cppConfiguration, boolean fake, LinkTargetType linkType) {
    return cppConfiguration.getSymbolCounts()
        && cppConfiguration.supportsGoldLinker()
        && linkType == LinkTargetType.EXECUTABLE
        && !fake;
  }

  public static PathFragment symbolCountsFileName(PathFragment binaryName) {
    return binaryName.replaceName(binaryName.getBaseName() + ".sc");
  }

  /**
   * Builder class to construct {@link CppLinkAction}s.
   */
  public static class Builder {
    // Builder-only
    // Null when invoked from tests (e.g. via createTestBuilder).
    @Nullable private final RuleContext ruleContext;
    private final AnalysisEnvironment analysisEnvironment;
    private final Artifact output;

    @Nullable private PathFragment interfaceOutputPath;
    // can be null for CppLinkAction.createTestBuilder()
    @Nullable private final CcToolchainProvider toolchain;
    private Artifact interfaceOutput;
    private Artifact symbolCounts;
    private PathFragment runtimeSolibDir;
    protected final BuildConfiguration configuration;
    private final CppConfiguration cppConfiguration;

    // Morally equivalent with {@link Context}, except these are mutable.
    // Keep these in sync with {@link Context}.
    private final Set<LinkerInput> nonLibraries = new LinkedHashSet<>();
    private final NestedSetBuilder<LibraryToLink> libraries = NestedSetBuilder.linkOrder();
    private NestedSet<Artifact> crosstoolInputs = NestedSetBuilder.emptySet(Order.STABLE_ORDER);
    private Artifact runtimeMiddleman;
    private NestedSet<Artifact> runtimeInputs = NestedSetBuilder.emptySet(Order.STABLE_ORDER);
    private final NestedSetBuilder<Artifact> compilationInputs = NestedSetBuilder.stableOrder();
    private final Set<Artifact> linkstamps = new LinkedHashSet<>();
    private List<String> linkstampOptions = new ArrayList<>();
    private final List<String> linkopts = new ArrayList<>();
    private LinkTargetType linkType = LinkTargetType.STATIC_LIBRARY;
    private LinkStaticness linkStaticness = LinkStaticness.FULLY_STATIC;
    private boolean fake;
    private boolean isNativeDeps;
    private boolean useTestOnlyFlags;
    private boolean wholeArchive;
    private LinkArtifactFactory linkArtifactFactory = DEFAULT_ARTIFACT_FACTORY;

    private boolean isLTOIndexing = false;
    private Iterable<LTOBackendArtifacts> allLTOArtifacts = null;

    /**
     * Creates a builder that builds {@link CppLinkAction} instances.
     *
     * @param ruleContext the rule that owns the action
     * @param output the output artifact
     */
    public Builder(RuleContext ruleContext, Artifact output) {
      this(ruleContext, output, ruleContext.getConfiguration(),
          ruleContext.getAnalysisEnvironment(), CppHelper.getToolchain(ruleContext));
    }

    /**
     * Creates a builder that builds {@link CppLinkAction} instances.
     *
     * @param ruleContext the rule that owns the action
     * @param output the output artifact
     */
    public Builder(RuleContext ruleContext, Artifact output,
        BuildConfiguration configuration, CcToolchainProvider toolchain) {
      this(ruleContext, output, configuration,
          ruleContext.getAnalysisEnvironment(), toolchain);
    }

    /**
     * Creates a builder that builds {@link CppLinkAction}s.
     *
     * @param ruleContext the rule that owns the action
     * @param output the output artifact
     * @param configuration the configuration used to determine the tool chain
     *        and the default link options
     */
    private Builder(@Nullable RuleContext ruleContext, Artifact output,
        BuildConfiguration configuration, AnalysisEnvironment analysisEnvironment,
        CcToolchainProvider toolchain) {
      this.ruleContext = ruleContext;
      this.analysisEnvironment = Preconditions.checkNotNull(analysisEnvironment);
      this.output = Preconditions.checkNotNull(output);
      this.configuration = Preconditions.checkNotNull(configuration);
      this.cppConfiguration = configuration.getFragment(CppConfiguration.class);
      this.toolchain = toolchain;
      if (cppConfiguration.supportsEmbeddedRuntimes() && toolchain != null) {
        runtimeSolibDir = toolchain.getDynamicRuntimeSolibDir();
      }
    }

    /**
     * Given a Context, creates a Builder that builds {@link CppLinkAction}s.
     * Note well: Keep the Builder->Context and Context->Builder transforms consistent!
     * @param ruleContext the rule that owns the action
     * @param output the output artifact
     * @param linkContext an immutable CppLinkAction.Context from the original builder
     */
    public Builder(RuleContext ruleContext, Artifact output, Context linkContext,
        BuildConfiguration configuration) {
      // These Builder-only fields get set in the constructor:
      //   ruleContext, analysisEnvironment, outputPath, configuration, runtimeSolibDir
      this(ruleContext, output, configuration, ruleContext.getAnalysisEnvironment(),
          CppHelper.getToolchain(ruleContext));
      Preconditions.checkNotNull(linkContext);

      // All linkContext fields should be transferred to this Builder.
      this.nonLibraries.addAll(linkContext.nonLibraries);
      this.libraries.addTransitive(linkContext.libraries);
      this.crosstoolInputs = linkContext.crosstoolInputs;
      this.runtimeMiddleman = linkContext.runtimeMiddleman;
      this.runtimeInputs = linkContext.runtimeInputs;
      this.compilationInputs.addTransitive(linkContext.compilationInputs);
      this.linkstamps.addAll(linkContext.linkstamps);
      this.linkopts.addAll(linkContext.linkopts);
      this.linkType = linkContext.linkType;
      this.linkStaticness = linkContext.linkStaticness;
      this.fake = linkContext.fake;
      this.isNativeDeps = linkContext.isNativeDeps;
      this.useTestOnlyFlags = linkContext.useTestOnlyFlags;
    }

    public CppLinkAction.Builder setLinkArtifactFactory(LinkArtifactFactory linkArtifactFactory) {
      this.linkArtifactFactory = linkArtifactFactory;
      return this;
    }

    private Iterable<LTOBackendArtifacts> createLTOArtifacts(
        PathFragment ltoOutputRootPrefix, NestedSet<LibraryToLink> uniqueLibraries) {
      // This flattens the set of object files, so for M binaries and N .o files,
      // this is O(M*N). If we had a nested set of .o files, we could have O(M + N) instead.
      NestedSetBuilder<Artifact> bitcodeBuilder = NestedSetBuilder.stableOrder();
      for (LibraryToLink lib : uniqueLibraries) {
        bitcodeBuilder.addAll(lib.getObjectFiles());
      }
      for (LinkerInput input : nonLibraries) {
        // This relies on file naming conventions. It would be less fragile to have a dedicated
        // field for non-library .o files.
        if (CppFileTypes.OBJECT_FILE.matches(input.getArtifact().getExecPath())
            || CppFileTypes.PIC_OBJECT_FILE.matches(input.getArtifact().getExecPath())) {
          bitcodeBuilder.add(input.getArtifact());
        }
      }

      NestedSet<Artifact> allBitcode = bitcodeBuilder.build();

      ImmutableList.Builder<LTOBackendArtifacts> ltoOutputs = ImmutableList.builder();
      for (Artifact a : allBitcode) {
        LTOBackendArtifacts ltoArtifacts = new LTOBackendArtifacts(
            ltoOutputRootPrefix, a, allBitcode, ruleContext, linkArtifactFactory);
        ltoOutputs.add(ltoArtifacts);
      }
      return ltoOutputs.build();
    }

    @VisibleForTesting
    boolean canSplitCommandLine() {
      if (toolchain == null || !toolchain.supportsParamFiles()) {
        return false;
      }

      switch (linkType) {
          // We currently can't split dynamic library links if they have interface outputs. That was
          // probably an unintended side effect of the change that introduced interface outputs.
        case DYNAMIC_LIBRARY:
          return interfaceOutput == null;
        case EXECUTABLE:
        case STATIC_LIBRARY:
        case PIC_STATIC_LIBRARY:
        case ALWAYS_LINK_STATIC_LIBRARY:
        case ALWAYS_LINK_PIC_STATIC_LIBRARY:
          return true;

        default:
          return false;
      }
    }

    /**
     * Builds the Action as configured and returns it.
     */
    public CppLinkAction build() {
      if (interfaceOutput != null && (fake || linkType != LinkTargetType.DYNAMIC_LIBRARY)) {
        throw new RuntimeException("Interface output can only be used "
                                   + "with non-fake DYNAMIC_LIBRARY targets");
      }

      final ImmutableList<Artifact> buildInfoHeaderArtifacts = !linkstamps.isEmpty()
          ? ruleContext.getBuildInfo(CppBuildInfo.KEY)
          : ImmutableList.<Artifact>of();

      boolean needWholeArchive = wholeArchive || needWholeArchive(
          linkStaticness, linkType, linkopts, isNativeDeps, cppConfiguration);

      NestedSet<LibraryToLink> uniqueLibraries = libraries.build();
      final Iterable<Artifact> filteredNonLibraryArtifacts =
          filterLinkerInputArtifacts(LinkerInputs.toLibraryArtifacts(nonLibraries));

      final Iterable<LinkerInput> linkerInputs = IterablesChain.<LinkerInput>builder()
          .add(ImmutableList.copyOf(filterLinkerInputs(nonLibraries)))
          .add(ImmutableIterable.from(Link.mergeInputsCmdLine(
              uniqueLibraries, needWholeArchive, cppConfiguration.archiveType())))
          .build();

      // ruleContext can only be null during testing. This is kind of ugly.
      final ImmutableSet<String> features = (ruleContext == null)
          ? ImmutableSet.<String>of()
          : ruleContext.getFeatures();

      final LibraryToLink outputLibrary =
          LinkerInputs.newInputLibrary(output, filteredNonLibraryArtifacts);
      final LibraryToLink interfaceOutputLibrary =
          (interfaceOutput == null)
              ? null
              : LinkerInputs.newInputLibrary(interfaceOutput, filteredNonLibraryArtifacts);

      final ImmutableMap<Artifact, Artifact> linkstampMap =
          mapLinkstampsToOutputs(linkstamps, ruleContext, output, linkArtifactFactory);

      PathFragment ltoOutputRootPrefix = null;
      if (isLTOIndexing && allLTOArtifacts == null) {
        ltoOutputRootPrefix =
            FileSystemUtils.appendExtension(
                outputLibrary.getArtifact().getRootRelativePath(), ".lto");
        allLTOArtifacts = createLTOArtifacts(ltoOutputRootPrefix, uniqueLibraries);
      }

      final ImmutableList<Artifact> actionOutputs;
      if (isLTOIndexing) {
        ImmutableList.Builder<Artifact> builder = ImmutableList.builder();
        for (LTOBackendArtifacts ltoA : allLTOArtifacts) {
          ltoA.addIndexingOutputs(builder);
        }
        actionOutputs = builder.build();
      } else {
        actionOutputs =
            constructOutputs(
                outputLibrary.getArtifact(),
                linkstampMap.values(),
                interfaceOutputLibrary == null ? null : interfaceOutputLibrary.getArtifact(),
                symbolCounts);
      }

      PathFragment paramRootPath =
          ParameterFile.derivePath(
              outputLibrary.getArtifact().getRootRelativePath(), (isLTOIndexing) ? "lto" : "2");

      @Nullable
      final Artifact paramFile =
          canSplitCommandLine()
              ? linkArtifactFactory.create(ruleContext, paramRootPath)
              : null;

      LinkCommandLine.Builder linkCommandLineBuilder =
          new LinkCommandLine.Builder(configuration, getOwner(), ruleContext)
              .setLinkerInputs(linkerInputs)
              .setRuntimeInputs(
                  ImmutableList.copyOf(LinkerInputs.simpleLinkerInputs(runtimeInputs)))
              .setLinkTargetType(linkType)
              .setLinkStaticness(linkStaticness)
              .setFeatures(features)
              .setRuntimeSolibDir(linkType.isStaticLibraryLink() ? null : runtimeSolibDir)
              .setNativeDeps(isNativeDeps)
              .setUseTestOnlyFlags(useTestOnlyFlags)
              .setNeedWholeArchive(needWholeArchive)
              .setParamFile(paramFile)
              .setAllLTOArtifacts(isLTOIndexing ? null : allLTOArtifacts);

      if (!isLTOIndexing) {
        linkCommandLineBuilder
            .setOutput(outputLibrary.getArtifact())
            .setInterfaceOutput(interfaceOutput)
            .setSymbolCountsOutput(symbolCounts)
            .setBuildInfoHeaderArtifacts(buildInfoHeaderArtifacts)
            .setInterfaceSoBuilder(getInterfaceSoBuilder())
            .setLinkstamps(linkstampMap)
            .setLinkopts(ImmutableList.copyOf(linkopts))
            .addLinkstampCompileOptions(linkstampOptions);
      } else {
        // TODO(bazel-team): once the LLVM compiler patches have been finalized, this should
        // be converted to a crosstool feature configuration instead.
        List<String> opts = new ArrayList<>(linkopts);
        opts.add("-flto");
        opts.add(
            "-Wl,-plugin-opt,thin-lto="
                + configuration.getBinDirectory().getExecPathString()
                + ":"
                + configuration
                    .getBinDirectory()
                    .getExecPath()
                    .getRelative(ltoOutputRootPrefix)
                    .toString());
        linkCommandLineBuilder.setLinkopts(ImmutableList.copyOf(opts));
      }

      LinkCommandLine linkCommandLine = linkCommandLineBuilder.build();

      // Compute the set of inputs - we only need stable order here.
      NestedSetBuilder<Artifact> dependencyInputsBuilder = NestedSetBuilder.stableOrder();
      dependencyInputsBuilder.addTransitive(crosstoolInputs);
      if (runtimeMiddleman != null) {
        dependencyInputsBuilder.add(runtimeMiddleman);
      }
      if (!isLTOIndexing) {
        dependencyInputsBuilder.addAll(buildInfoHeaderArtifacts);
        dependencyInputsBuilder.addAll(linkstamps);
        dependencyInputsBuilder.addTransitive(compilationInputs.build());
      }

      Iterable<Artifact> expandedInputs =
          LinkerInputs.toLibraryArtifacts(
              Link.mergeInputsDependencies(
                  uniqueLibraries, needWholeArchive, cppConfiguration.archiveType()));

      if (!isLTOIndexing && allLTOArtifacts != null) {
        // This is the real link, rename the inputs.
        List<Artifact> renamed = new ArrayList<>();
        for (LTOBackendArtifacts a : allLTOArtifacts) {
          renamed.add(a.getObjectFile());
        }
        expandedInputs = renamed;
      }

      // getPrimaryInput returns the first element, and that is a public interface - therefore the
      // order here is important.
      IterablesChain.Builder<Artifact> inputsBuilder = IterablesChain.<Artifact>builder()
          .add(ImmutableList.copyOf(LinkerInputs.toLibraryArtifacts(nonLibraries)))
          .add(dependencyInputsBuilder.build())
          .add(ImmutableIterable.from(expandedInputs));

      if (linkCommandLine.getParamFile() != null) {
        inputsBuilder.add(ImmutableList.of(linkCommandLine.getParamFile()));
        Action parameterFileWriteAction =
            new ParameterFileWriteAction(
                getOwner(),
                paramFile,
                linkCommandLine.paramCmdLine(),
                ParameterFile.ParameterFileType.UNQUOTED,
                ISO_8859_1);
        analysisEnvironment.registerAction(parameterFileWriteAction);
      }

      return new CppLinkAction(
          getOwner(),
          inputsBuilder.deduplicate().build(),
          actionOutputs,
          cppConfiguration,
          outputLibrary,
          interfaceOutputLibrary,
          fake,
          isLTOIndexing,
          allLTOArtifacts,
          linkCommandLine);
    }

    /**
     * The default heuristic on whether we need to use whole-archive for the link.
     */
    private static boolean needWholeArchive(LinkStaticness staticness,
        LinkTargetType type, Collection<String> linkopts, boolean isNativeDeps,
        CppConfiguration cppConfig) {
      boolean fullyStatic = (staticness == LinkStaticness.FULLY_STATIC);
      boolean mostlyStatic = (staticness == LinkStaticness.MOSTLY_STATIC);
      boolean sharedLinkopts = type == LinkTargetType.DYNAMIC_LIBRARY
          || linkopts.contains("-shared")
          || cppConfig.getLinkOptions().contains("-shared");
      return (isNativeDeps || cppConfig.legacyWholeArchive())
          && (fullyStatic || mostlyStatic)
          && sharedLinkopts;
    }

    private static ImmutableList<Artifact> constructOutputs(Artifact primaryOutput,
        Collection<Artifact> outputList, Artifact... outputs) {
      return new ImmutableList.Builder<Artifact>()
          .add(primaryOutput)
          .addAll(outputList)
          .addAll(CollectionUtils.asListWithoutNulls(outputs))
          .build();
    }

    /**
     * Translates a collection of linkstamp source files to an immutable
     * mapping from source files to object files. In other words, given a
     * set of source files, this method determines the output path to which
     * each file should be compiled.
     *
     * @param linkstamps collection of linkstamp source files
     * @param ruleContext the rule for which this link is being performed
     * @param outputBinary the binary output path for this link
     * @return an immutable map that pairs each source file with the
     *         corresponding object file that should be fed into the link
     */
    public static ImmutableMap<Artifact, Artifact> mapLinkstampsToOutputs(
        Collection<Artifact> linkstamps, RuleContext ruleContext, Artifact outputBinary,
        LinkArtifactFactory linkArtifactFactory) {
      ImmutableMap.Builder<Artifact, Artifact> mapBuilder = ImmutableMap.builder();

      PathFragment outputBinaryPath = outputBinary.getRootRelativePath();
      PathFragment stampOutputDirectory = outputBinaryPath.getParentDirectory().
          getRelative("_objs").getRelative(outputBinaryPath.getBaseName());

      for (Artifact linkstamp : linkstamps) {
        PathFragment stampOutputPath = stampOutputDirectory.getRelative(
            FileSystemUtils.replaceExtension(linkstamp.getRootRelativePath(), ".o"));
        mapBuilder.put(linkstamp,
            // Note that link stamp actions can be shared between link actions that output shared
            // native dep libraries.
            linkArtifactFactory.create(ruleContext, stampOutputPath));
      }
      return mapBuilder.build();    }

    protected ActionOwner getOwner() {
      return ruleContext.getActionOwner();
    }

    protected Artifact getInterfaceSoBuilder() {
      return analysisEnvironment.getEmbeddedToolArtifact(CppRuleClasses.BUILD_INTERFACE_SO);
    }

    /**
     * Set the crosstool inputs required for the action.
     */
    public Builder setCrosstoolInputs(NestedSet<Artifact> inputs) {
      this.crosstoolInputs = inputs;
      return this;
    }

    /**
     * This is the LTO indexing step, rather than the real link.
     *
     * <p>When using this, build() will store allLTOArtifacts as a side-effect so the next build()
     * call can emit the real link. Do not call addInput() between the two build() calls.
     *
     */
    public Builder setLTOIndexing(boolean ltoIndexing) {
      this.isLTOIndexing = ltoIndexing;
      return this;
    }

    /**
     * Sets the C++ runtime library inputs for the action.
     */
    public Builder setRuntimeInputs(Artifact middleman, NestedSet<Artifact> inputs) {
      Preconditions.checkArgument((middleman == null) == inputs.isEmpty());
      this.runtimeMiddleman = middleman;
      this.runtimeInputs = inputs;
      return this;
    }

    /**
     * Sets the interface output of the link.  A non-null argument can
     * only be provided if the link type is {@code DYNAMIC_LIBRARY}
     * and fake is false.
     */
    public Builder setInterfaceOutput(Artifact interfaceOutput) {
      this.interfaceOutput = interfaceOutput;
      return this;
    }

    public Builder setSymbolCountsOutput(Artifact symbolCounts) {
      this.symbolCounts = symbolCounts;
      return this;
    }

    /**
     * Add additional inputs needed for the linkstamp compilation that is being done as part of the
     * link.
     */
    public Builder addCompilationInputs(Iterable<Artifact> inputs) {
      this.compilationInputs.addAll(inputs);
      return this;
    }

    public Builder addTransitiveCompilationInputs(NestedSet<Artifact> inputs) {
      this.compilationInputs.addTransitive(inputs);
      return this;
    }

    private void addNonLibraryInput(LinkerInput input) {
      String name = input.getArtifact().getFilename();
      Preconditions.checkArgument(
          !Link.ARCHIVE_LIBRARY_FILETYPES.matches(name)
          && !Link.SHARED_LIBRARY_FILETYPES.matches(name),
          "'%s' is a library file", input);
      this.nonLibraries.add(input);
    }

    /**
     * Adds a single artifact to the set of inputs (C++ source files, header files, etc). Artifacts
     * that are not of recognized types will be used for dependency checking but will not be passed
     * to the linker. The artifact must not be an archive or a shared library.
     */
    public Builder addNonLibraryInput(Artifact input) {
      addNonLibraryInput(LinkerInputs.simpleLinkerInput(input));
      return this;
    }

    /**
     * Adds multiple artifacts to the set of inputs (C++ source files, header files, etc).
     * Artifacts that are not of recognized types will be used for dependency checking but will
     * not be passed to the linker. The artifacts must not be archives or shared libraries.
     */
    public Builder addNonLibraryInputs(Iterable<Artifact> inputs) {
      for (Artifact input : inputs) {
        addNonLibraryInput(LinkerInputs.simpleLinkerInput(input));
      }
      return this;
    }

    public Builder addFakeNonLibraryInputs(Iterable<Artifact> inputs) {
      for (Artifact input : inputs) {
        addNonLibraryInput(LinkerInputs.fakeLinkerInput(input));
      }
      return this;
    }

    private void checkLibrary(LibraryToLink input) {
      String name = input.getArtifact().getFilename();
      Preconditions.checkArgument(
          Link.ARCHIVE_LIBRARY_FILETYPES.matches(name)
              || Link.SHARED_LIBRARY_FILETYPES.matches(name),
          "'%s' is not a library file",
          input);
    }

    /**
     * Adds a single artifact to the set of inputs. The artifact must be an archive or a shared
     * library. Note that all directly added libraries are implicitly ordered before all nested
     * sets added with {@link #addLibraries}, even if added in the opposite order.
     */
    public Builder addLibrary(LibraryToLink input) {
      checkLibrary(input);
      libraries.add(input);
      return this;
    }

    /**
     * Adds multiple artifact to the set of inputs. The artifacts must be archives or shared
     * libraries.
     */
    public Builder addLibraries(NestedSet<LibraryToLink> inputs) {
      for (LibraryToLink input : inputs) {
        checkLibrary(input);
      }
      this.libraries.addTransitive(inputs);
      return this;
    }

    /**
     * Sets the type of ELF file to be created (.a, .so, .lo, executable). The
     * default is {@link LinkTargetType#STATIC_LIBRARY}.
     */
    public Builder setLinkType(LinkTargetType linkType) {
      this.linkType = linkType;
      return this;
    }

    /**
     * Sets the degree of "staticness" of the link: fully static (static binding
     * of all symbols), mostly static (use dynamic binding only for symbols from
     * glibc), dynamic (use dynamic binding wherever possible). The default is
     * {@link LinkStaticness#FULLY_STATIC}.
     */
    public Builder setLinkStaticness(LinkStaticness linkStaticness) {
      this.linkStaticness = linkStaticness;
      return this;
    }

    /**
     * Adds a C++ source file which will be compiled at link time. This is used
     * to embed various values from the build system into binaries to identify
     * their provenance.
     *
     * <p>Link stamps are also automatically added to the inputs.
     */
    public Builder addLinkstamps(Map<Artifact, ImmutableList<Artifact>> linkstamps) {
      this.linkstamps.addAll(linkstamps.keySet());
      // Add inputs for linkstamping.
      if (!linkstamps.isEmpty()) {
        // This will just be the compiler unless include scanning is disabled, in which case it will
        // include all header files. Since we insist that linkstamps declare all their headers, all
        // header files would be overkill, but that only happens when include scanning is disabled.
        addTransitiveCompilationInputs(toolchain.getCompile());
        for (Map.Entry<Artifact, ImmutableList<Artifact>> entry : linkstamps.entrySet()) {
          addCompilationInputs(entry.getValue());
        }
      }
      return this;
    }

    public Builder addLinkstampCompilerOptions(ImmutableList<String> linkstampOptions) {
      this.linkstampOptions = linkstampOptions;
      return this;
    }

    /**
     * Adds an additional linker option.
     */
    public Builder addLinkopt(String linkopt) {
      this.linkopts.add(linkopt);
      return this;
    }

    /**
     * Adds multiple linker options at once.
     *
     * @see #addLinkopt(String)
     */
    public Builder addLinkopts(Collection<String> linkopts) {
      this.linkopts.addAll(linkopts);
      return this;
    }

    /**
     * Merges the given link params into this builder by calling {@link #addLinkopts}, {@link
     * #addLibraries}, and {@link #addLinkstamps}.
     */
    public Builder addLinkParams(CcLinkParams linkParams, RuleErrorConsumer errorListener) {
      addLinkopts(linkParams.flattenedLinkopts());
      addLibraries(linkParams.getLibraries());
      addLinkstamps(CppHelper.resolveLinkstamps(errorListener, linkParams));
      return this;
    }

    /**
     * Sets whether this link action will be used for a cc_fake_binary; false by
     * default.
     */
    public Builder setFake(boolean fake) {
      this.fake = fake;
      return this;
    }

    /**
     * Sets whether this link action is used for a native dependency library.
     */
    public Builder setNativeDeps(boolean isNativeDeps) {
      this.isNativeDeps = isNativeDeps;
      return this;
    }

    /**
     * Setting this to true overrides the default whole-archive computation and force-enables
     * whole archives for every archive in the link. This is only necessary for linking executable
     * binaries that are supposed to export symbols.
     *
     * <p>Usually, the link action while use whole archives for dynamic libraries that are native
     * deps (or the legacy whole archive flag is enabled), and that are not dynamically linked.
     *
     * <p>(Note that it is possible to build dynamic libraries with cc_binary rules by specifying
     * linkshared = 1, and giving the rule a name that matches the pattern {@code
     * lib&lt;name&gt;.so}.)
     */
    public Builder setWholeArchive(boolean wholeArchive) {
      this.wholeArchive = wholeArchive;
      return this;
    }

    /**
     * Sets whether this link action should use test-specific flags (e.g. $EXEC_ORIGIN instead of
     * $ORIGIN for the solib search path or lazy binding);  false by default.
     */
    public Builder setUseTestOnlyFlags(boolean useTestOnlyFlags) {
      this.useTestOnlyFlags = useTestOnlyFlags;
      return this;
    }

    /**
     * Sets the name of the directory where the solib symlinks for the dynamic runtime libraries
     * live. This is usually automatically set from the cc_toolchain.
     */
    public Builder setRuntimeSolibDir(PathFragment runtimeSolibDir) {
      this.runtimeSolibDir = runtimeSolibDir;
      return this;
    }

    /**
     * Creates a builder without the need for a {@link RuleContext}.
     * This is to be used exclusively for testing purposes.
     *
     * <p>Link stamping is not supported if using this method.
     */
    @VisibleForTesting
    public static Builder createTestBuilder(
        final ActionOwner owner, final AnalysisEnvironment analysisEnvironment,
        final Artifact output, BuildConfiguration config) {
      return new Builder(null, output, config, analysisEnvironment, null) {
        @Override
        protected ActionOwner getOwner() {
          return owner;
        }
      };
    }
  }

  /**
   * TransitiveInfoProvider for ELF link actions.
   */
  @Immutable @ThreadSafe
  public static final class Context implements TransitiveInfoProvider {
    // Morally equivalent with {@link Builder}, except these are immutable.
    // Keep these in sync with {@link Builder}.
    private final ImmutableSet<LinkerInput> nonLibraries;
    private final NestedSet<LibraryToLink> libraries;
    private final NestedSet<Artifact> crosstoolInputs;
    private final Artifact runtimeMiddleman;
    private final NestedSet<Artifact> runtimeInputs;
    private final NestedSet<Artifact> compilationInputs;
    private final ImmutableSet<Artifact> linkstamps;
    private final ImmutableList<String> linkopts;
    private final LinkTargetType linkType;
    private final LinkStaticness linkStaticness;
    private final boolean fake;
    private final boolean isNativeDeps;
    private final boolean useTestOnlyFlags;

    /**
     * Given a {@link Builder}, creates a {@code Context} to pass to another target.
     * Note well: Keep the Builder->Context and Context->Builder transforms consistent!
     * @param builder a mutable {@link CppLinkAction.Builder} to clone from
     */
    public Context(Builder builder) {
      this.nonLibraries = ImmutableSet.copyOf(builder.nonLibraries);
      this.libraries = NestedSetBuilder.<LibraryToLink>linkOrder()
          .addTransitive(builder.libraries.build()).build();
      this.crosstoolInputs =
          NestedSetBuilder.<Artifact>stableOrder().addTransitive(builder.crosstoolInputs).build();
      this.runtimeMiddleman = builder.runtimeMiddleman;
      this.runtimeInputs =
          NestedSetBuilder.<Artifact>stableOrder().addTransitive(builder.runtimeInputs).build();
      this.compilationInputs = NestedSetBuilder.<Artifact>stableOrder()
          .addTransitive(builder.compilationInputs.build()).build();
      this.linkstamps = ImmutableSet.copyOf(builder.linkstamps);
      this.linkopts = ImmutableList.copyOf(builder.linkopts);
      this.linkType = builder.linkType;
      this.linkStaticness = builder.linkStaticness;
      this.fake = builder.fake;
      this.isNativeDeps = builder.isNativeDeps;
      this.useTestOnlyFlags = builder.useTestOnlyFlags;
    }
  }
}