aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/rules/cpp/LinkBuildVariables.java
blob: f0e56358aacfd780639ab7a5ce67d7e340b9805b (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
// Copyright 2014 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.
package com.google.devtools.build.lib.rules.cpp;

import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.ActionInput;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.config.InvalidConfigurationException;
import com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.FeatureConfiguration;
import com.google.devtools.build.lib.rules.cpp.CcToolchainVariables.SequenceBuilder;
import com.google.devtools.build.lib.syntax.EvalException;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.List;

/** Enum covering all build variables we create for all various {@link CppLinkAction}. */
public enum LinkBuildVariables {
  /** Entries in the linker runtime search path (usually set by -rpath flag) */
  RUNTIME_LIBRARY_SEARCH_DIRECTORIES("runtime_library_search_directories"),
  /** Entries in the linker search path (usually set by -L flag) */
  LIBRARY_SEARCH_DIRECTORIES("library_search_directories"),
  /** Flags providing files to link as inputs in the linker invocation */
  LIBRARIES_TO_LINK("libraries_to_link"),
  /** Thinlto param file produced by thinlto-indexing action consumed by the final link action. */
  THINLTO_PARAM_FILE("thinlto_param_file"),
  /** Location of def file used on Windows with MSVC */
  DEF_FILE_PATH("def_file_path"),
  /** Location where hinlto should write thinlto_param_file flags when indexing. */
  THINLTO_INDEXING_PARAM_FILE("thinlto_indexing_param_file"),

  THINLTO_PREFIX_REPLACE("thinlto_prefix_replace"),
  /**
   * A build variable to let the LTO indexing step know how to map from the minimized bitcode file
   * to the full bitcode file used by the LTO Backends.
   */
  THINLTO_OBJECT_SUFFIX_REPLACE("thinlto_object_suffix_replace"),
  /**
   * A build variable for the path to the merged object file, which is an object file that is
   * created during the LTO indexing step and needs to be passed to the final link.
   */
  THINLTO_MERGED_OBJECT_FILE("thinlto_merged_object_file"),
  /** Location of linker param file created by bazel to overcome command line length limit */
  LINKER_PARAM_FILE("linker_param_file"),
  /** execpath of the output of the linker. */
  OUTPUT_EXECPATH("output_execpath"),
  /** "yes"|"no" depending on whether interface library should be generated. */
  GENERATE_INTERFACE_LIBRARY("generate_interface_library"),
  /** Path to the interface library builder tool. */
  INTERFACE_LIBRARY_BUILDER("interface_library_builder_path"),
  /** Input for the interface library ifso builder tool. */
  INTERFACE_LIBRARY_INPUT("interface_library_input_path"),
  /** Path where to generate interface library using the ifso builder tool. */
  INTERFACE_LIBRARY_OUTPUT("interface_library_output_path"),
  /** Linker flags coming from the legacy crosstool fields. */
  LEGACY_LINK_FLAGS("legacy_link_flags"),
  /** Linker flags coming from the --linkopt or linkopts attribute. */
  USER_LINK_FLAGS("user_link_flags"),
  /** Path to which to write symbol counts. */
  SYMBOL_COUNTS_OUTPUT("symbol_counts_output"),
  /** A build variable giving linkstamp paths. */
  LINKSTAMP_PATHS("linkstamp_paths"),
  /** Presence of this variable indicates that PIC code should be generated. */
  FORCE_PIC("force_pic"),
  /** Presence of this variable indicates that the debug symbols should be stripped. */
  STRIP_DEBUG_SYMBOLS("strip_debug_symbols"),
  @Deprecated
  IS_CC_TEST_LINK_ACTION("is_cc_test_link_action"),
  @Deprecated
  IS_NOT_CC_TEST_LINK_ACTION("is_not_cc_test_link_action"),
  /** Truthy when current action is a cc_test linking action, falsey otherwise. */
  IS_CC_TEST("is_cc_test"),
  /**
   * Presence of this variable indicates that files were compiled with fission (debug info is in
   * .dwo files instead of .o files and linker needs to know).
   */
  IS_USING_FISSION("is_using_fission");

  private final String variableName;

  LinkBuildVariables(String variableName) {
    this.variableName = variableName;
  }

  public String getVariableName() {
    return variableName;
  }

  public static CcToolchainVariables setupVariables(
      boolean isUsingLinkerNotArchiver,
      BuildConfiguration configuration,
      Artifact outputArtifact,
      boolean isCreatingSharedLibrary,
      Artifact paramFile,
      Artifact thinltoParamFile,
      Artifact thinltoMergedObjectFile,
      boolean mustKeepDebug,
      Artifact symbolCounts,
      CcToolchainProvider ccToolchainProvider,
      FeatureConfiguration featureConfiguration,
      boolean useTestOnlyFlags,
      boolean isLtoIndexing,
      ImmutableList<String> userLinkFlags,
      Artifact interfaceLibraryBuilder,
      Artifact interfaceLibraryOutput,
      PathFragment ltoOutputRootPrefix,
      ActionInput defFile,
      FdoSupportProvider fdoSupport,
      Iterable<String> runtimeLibrarySearchDirectories,
      SequenceBuilder librariesToLink,
      Iterable<String> librarySearchDirectories,
      boolean isLegacyFullyStaticLinkingMode,
      boolean isStaticLinkingMode)
      throws EvalException {
    CcToolchainVariables.Builder buildVariables = new CcToolchainVariables.Builder();

    // symbol counting
    if (symbolCounts != null) {
      buildVariables.addStringVariable(
          SYMBOL_COUNTS_OUTPUT.getVariableName(), symbolCounts.getExecPathString());
    }

    // pic
    if (ccToolchainProvider.getForcePic()) {
      buildVariables.addStringVariable(FORCE_PIC.getVariableName(), "");
    }

    if (!mustKeepDebug && ccToolchainProvider.getShouldStripBinaries()) {
      buildVariables.addStringVariable(STRIP_DEBUG_SYMBOLS.getVariableName(), "");
    }

    if (isUsingLinkerNotArchiver
        && ccToolchainProvider.shouldCreatePerObjectDebugInfo(featureConfiguration)) {
      buildVariables.addStringVariable(IS_USING_FISSION.getVariableName(), "");
    }

    if (useTestOnlyFlags) {
      buildVariables.addIntegerVariable(IS_CC_TEST.getVariableName(), 1);
      buildVariables.addStringVariable(IS_CC_TEST_LINK_ACTION.getVariableName(), "");
    } else {
      buildVariables.addIntegerVariable(IS_CC_TEST.getVariableName(), 0);
      buildVariables.addStringVariable(IS_NOT_CC_TEST_LINK_ACTION.getVariableName(), "");
    }

    if (runtimeLibrarySearchDirectories != null) {
      buildVariables.addStringSequenceVariable(
          RUNTIME_LIBRARY_SEARCH_DIRECTORIES.getVariableName(), runtimeLibrarySearchDirectories);
    }

    buildVariables.addCustomBuiltVariable(LIBRARIES_TO_LINK.getVariableName(), librariesToLink);
    // TODO(b/72803478): Remove once existing crosstools have been migrated
    buildVariables.addStringVariable("libs_to_link_dont_emit_objects_for_archiver", "");

    buildVariables.addStringSequenceVariable(
        LIBRARY_SEARCH_DIRECTORIES.getVariableName(), librarySearchDirectories);

    if (paramFile != null) {
      buildVariables.addStringVariable(
          LINKER_PARAM_FILE.getVariableName(), paramFile.getExecPathString());
    }

    // output exec path
    if (outputArtifact != null && !isLtoIndexing) {
      buildVariables.addStringVariable(
          OUTPUT_EXECPATH.getVariableName(), outputArtifact.getExecPathString());
    }

    if (isLtoIndexing) {
      if (thinltoParamFile != null) {
        // This is a lto-indexing action and we want it to populate param file.
        buildVariables.addStringVariable(
            THINLTO_INDEXING_PARAM_FILE.getVariableName(), thinltoParamFile.getExecPathString());
        // TODO(b/33846234): Remove once all the relevant crosstools don't depend on the variable.
        buildVariables.addStringVariable(
            "thinlto_optional_params_file", "=" + thinltoParamFile.getExecPathString());
      } else {
        buildVariables.addStringVariable(THINLTO_INDEXING_PARAM_FILE.getVariableName(), "");
        // TODO(b/33846234): Remove once all the relevant crosstools don't depend on the variable.
        buildVariables.addStringVariable("thinlto_optional_params_file", "");
      }
      buildVariables.addStringVariable(
          THINLTO_PREFIX_REPLACE.getVariableName(),
          configuration.getBinDirectory().getExecPathString()
              + ";"
              + configuration.getBinDirectory().getExecPath().getRelative(ltoOutputRootPrefix));
      String objectFileExtension;
      try {
        objectFileExtension = ccToolchainProvider.getFeatures()
            .getArtifactNameExtensionForCategory(ArtifactCategory.OBJECT_FILE);
      } catch (InvalidConfigurationException e) {
        throw new EvalException(null, "artifact name pattern for object_file must be specified", e);
      }
      buildVariables.addStringVariable(
          THINLTO_OBJECT_SUFFIX_REPLACE.getVariableName(),
          Iterables.getOnlyElement(CppFileTypes.LTO_INDEXING_OBJECT_FILE.getExtensions())
              + ";" + objectFileExtension);
      if (thinltoMergedObjectFile != null) {
        buildVariables.addStringVariable(
            THINLTO_MERGED_OBJECT_FILE.getVariableName(),
            thinltoMergedObjectFile.getExecPathString());
      }
    } else {
      if (thinltoParamFile != null) {
        // This is a normal link action and we need to use param file created by lto-indexing.
        buildVariables.addStringVariable(
            THINLTO_PARAM_FILE.getVariableName(), thinltoParamFile.getExecPathString());
      }
    }
    boolean shouldGenerateInterfaceLibrary =
        outputArtifact != null
            && interfaceLibraryBuilder != null
            && interfaceLibraryOutput != null
            && !isLtoIndexing;
    buildVariables.addStringVariable(
        GENERATE_INTERFACE_LIBRARY.getVariableName(),
        shouldGenerateInterfaceLibrary ? "yes" : "no");
    buildVariables.addStringVariable(
        INTERFACE_LIBRARY_BUILDER.getVariableName(),
        shouldGenerateInterfaceLibrary ? interfaceLibraryBuilder.getExecPathString() : "ignored");
    buildVariables.addStringVariable(
        INTERFACE_LIBRARY_INPUT.getVariableName(),
        shouldGenerateInterfaceLibrary ? outputArtifact.getExecPathString() : "ignored");
    buildVariables.addStringVariable(
        INTERFACE_LIBRARY_OUTPUT.getVariableName(),
        shouldGenerateInterfaceLibrary ? interfaceLibraryOutput.getExecPathString() : "ignored");

    if (defFile != null) {
      buildVariables.addStringVariable(
          DEF_FILE_PATH.getVariableName(), defFile.getExecPathString());
    }

    fdoSupport.getFdoSupport().getLinkOptions(featureConfiguration, buildVariables);

    ImmutableList<String> userLinkFlagsWithLtoIndexingIfNeeded;
    if (!isLtoIndexing) {
      userLinkFlagsWithLtoIndexingIfNeeded = ImmutableList.copyOf(userLinkFlags);

    } else {
      List<String> opts = new ArrayList<>(userLinkFlags);
      opts.addAll(
          featureConfiguration.getCommandLine(
              "lto-indexing", buildVariables.build(), /* expander= */ null));
      opts.addAll(ccToolchainProvider.getCppConfiguration().getLtoIndexOptions());
      userLinkFlagsWithLtoIndexingIfNeeded = ImmutableList.copyOf(opts);
    }

    // For now, silently ignore linkopts if this is a static library
    userLinkFlagsWithLtoIndexingIfNeeded =
        isUsingLinkerNotArchiver ? userLinkFlagsWithLtoIndexingIfNeeded : ImmutableList.of();

    buildVariables.addStringSequenceVariable(
        LinkBuildVariables.USER_LINK_FLAGS.getVariableName(),
        removePieIfCreatingSharedLibrary(
            isCreatingSharedLibrary, userLinkFlagsWithLtoIndexingIfNeeded));
    buildVariables.addStringSequenceVariable(
        LinkBuildVariables.LEGACY_LINK_FLAGS.getVariableName(),
        getToolchainFlags(
            isLegacyFullyStaticLinkingMode,
            isStaticLinkingMode,
            isUsingLinkerNotArchiver,
            featureConfiguration,
            ccToolchainProvider,
            useTestOnlyFlags,
            isCreatingSharedLibrary,
            userLinkFlags));

    return buildVariables.build();
  }

  private static ImmutableList<String> getToolchainFlags(
      boolean isLegacyFullyStaticLinkingMode,
      boolean isStaticLinkingMode,
      boolean isUsingLinkerNotArchiver,
      FeatureConfiguration featureConfiguration,
      CcToolchainProvider ccToolchainProvider,
      boolean useTestOnlyFlags,
      boolean isCreatingSharedLibrary,
      List<String> userLinkFlags) {
    if (!isUsingLinkerNotArchiver) {
      return ImmutableList.of();
    }
    CppConfiguration cppConfiguration = ccToolchainProvider.getCppConfiguration();
    boolean sharedLinkopts =
        isCreatingSharedLibrary
            || userLinkFlags.contains("-shared")
            || cppConfiguration.hasSharedLinkOption();

    List<String> result = new ArrayList<>();

    // Extra toolchain link options based on the output's link staticness.
    if (isLegacyFullyStaticLinkingMode) {
      result.addAll(
          CppHelper.getFullyStaticLinkOptions(
              cppConfiguration, ccToolchainProvider, sharedLinkopts));
    } else if (isStaticLinkingMode) {
      if (!featureConfiguration.isEnabled(CppRuleClasses.STATIC_LINKING_MODE)) {
        result.addAll(
            CppHelper.getMostlyStaticLinkOptions(
                cppConfiguration,
                ccToolchainProvider,
                sharedLinkopts,
                featureConfiguration.isEnabled(CppRuleClasses.STATIC_LINK_CPP_RUNTIMES)));
      } else {
        result.addAll(ccToolchainProvider.getLegacyLinkOptions());
      }
    } else {
      if (!featureConfiguration.isEnabled(CppRuleClasses.DYNAMIC_LINKING_MODE)) {
        result.addAll(
            CppHelper.getDynamicLinkOptions(cppConfiguration, ccToolchainProvider, sharedLinkopts));
      } else {
        result.addAll(ccToolchainProvider.getLegacyLinkOptions());
      }
    }

    // Extra test-specific link options.
    if (useTestOnlyFlags) {
      result.addAll(ccToolchainProvider.getTestOnlyLinkOptions());
    }

    result.addAll(ccToolchainProvider.getLinkOptions());

    // -pie is not compatible with shared and should be
    // removed when the latter is part of the link command. Should we need to further
    // distinguish between shared libraries and executables, we could add additional
    // command line / CROSSTOOL flags that distinguish them. But as long as this is
    // the only relevant use case we're just special-casing it here.
    return ImmutableList.copyOf(removePieIfCreatingSharedLibrary(isCreatingSharedLibrary, result));
  }

  private static Iterable<String> removePieIfCreatingSharedLibrary(
      boolean isCreatingSharedLibrary, List<String> flags) {
    if (isCreatingSharedLibrary) {
      return Iterables.filter(flags, Predicates.not(Predicates.equalTo("-pie")));
    } else {
      return flags;
    }
  }
}