aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkParams.java
blob: dc94c4940862d95849f15e868c90f67390fd761d (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
// 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.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.configuredtargets.RuleConfiguredTarget.Mode;
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.rules.cpp.LinkerInputs.LibraryToLink;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec.VisibleForSerialization;
import com.google.devtools.build.lib.skylarkbuildapi.cpp.CcLinkParamsApi;
import com.google.devtools.build.lib.syntax.SkylarkNestedSet;
import java.util.Collection;
import java.util.Objects;
import javax.annotation.Nullable;

/**
 * Parameters to be passed to the linker.
 *
 * <p>The parameters concerned are the link options (strings) passed to the linker, linkstamps, a
 * list of libraries to be linked in, and a list of libraries to build at link time.
 *
 * <p>Items in the collections are stored in nested sets. Link options and libraries are stored in
 * link order (preorder) and linkstamps are sorted.
 */
@AutoCodec
public final class CcLinkParams implements CcLinkParamsApi {
  /**
   * A list of link options contributed by a single configured target.
   *
   * <p><b>WARNING:</b> Do not implement {@code #equals()} in the obvious way. This class must be
   * checked for equality by object identity because otherwise if two configured targets contribute
   * the same link options, they will be de-duplicated, which is not the desirable behavior.
   */
  @AutoCodec
  @Immutable
  public static final class LinkOptions {
    private final ImmutableList<String> linkOptions;

    @VisibleForSerialization
    LinkOptions(Iterable<String> linkOptions) {
      this.linkOptions = ImmutableList.copyOf(linkOptions);
    }

    public ImmutableList<String> get() {
      return linkOptions;
    }

    public static LinkOptions of(Iterable<String> linkOptions) {
      return new LinkOptions(linkOptions);
    }
  }

  private final NestedSet<LinkOptions> linkOpts;
  private final NestedSet<Linkstamp> linkstamps;
  private final NestedSet<LibraryToLink> libraries;
  private final NestedSet<Artifact> dynamicLibrariesForRuntime;
  private final ExtraLinkTimeLibraries extraLinkTimeLibraries;
  private final NestedSet<Artifact> nonCodeInputs;

  @AutoCodec.Instantiator
  @VisibleForSerialization
  CcLinkParams(
      NestedSet<LinkOptions> linkOpts,
      NestedSet<Linkstamp> linkstamps,
      NestedSet<LibraryToLink> libraries,
      NestedSet<Artifact> dynamicLibrariesForRuntime,
      ExtraLinkTimeLibraries extraLinkTimeLibraries,
      NestedSet<Artifact> nonCodeInputs) {
    this.linkOpts = linkOpts;
    this.linkstamps = linkstamps;
    this.libraries = libraries;
    this.dynamicLibrariesForRuntime = dynamicLibrariesForRuntime;
    this.extraLinkTimeLibraries = extraLinkTimeLibraries;
    this.nonCodeInputs = nonCodeInputs;
  }

  /**
   * Returns the linkopts
   */
  public NestedSet<LinkOptions> getLinkopts() {
    return linkOpts;
  }

  public ImmutableList<String> flattenedLinkopts() {
    return ImmutableList.copyOf(Iterables.concat(Iterables.transform(linkOpts, LinkOptions::get)));
  }

  @Override
  public SkylarkNestedSet getSkylarkLinkopts() {
    // TODO(plf): Shouldn't flatten nested set. Remove LinkOptions class and just have a nested set
    // of strings.
    return SkylarkNestedSet.of(
        String.class, NestedSetBuilder.wrap(Order.COMPILE_ORDER, flattenedLinkopts()));
  }

  /**
   * Returns the linkstamps
   */
  public NestedSet<Linkstamp> getLinkstamps() {
    return linkstamps;
  }

  /**
   * Returns the libraries
   */
  public NestedSet<LibraryToLink> getLibraries() {
    return libraries;
  }

  @Override
  public SkylarkNestedSet getSkylarkLibrariesToLink() {
    return SkylarkNestedSet.of(LibraryToLink.class, libraries);
  }

  /** Returns the dynamicLibrariesForRuntime. */
  public NestedSet<Artifact> getDynamicLibrariesForRuntime() {
    return dynamicLibrariesForRuntime;
  }

  @Override
  public SkylarkNestedSet getSkylarkDynamicLibrariesForRuntime() {
    return SkylarkNestedSet.of(Artifact.class, dynamicLibrariesForRuntime);
  }

  /**
   * The extra link time libraries; will be null if there are no such libraries.
   */
  public @Nullable ExtraLinkTimeLibraries getExtraLinkTimeLibraries() {
    return extraLinkTimeLibraries;
  }

  /**
   * Returns the non-code inputs, e.g. linker scripts; will be null if none.
   */
  public @Nullable NestedSet<Artifact> getNonCodeInputs() {
    return nonCodeInputs;
  }

  public static final Builder builder(boolean linkingStatically, boolean linkShared) {
    return new Builder(linkingStatically, linkShared);
  }

  public static final Builder builder() {
    return new Builder();
  }

  /**
   * Builder for {@link CcLinkParams}.
   */
  public static final class Builder {

    /**
     * linkingStatically is true when we're linking this target in either FULLY STATIC mode
     * (linkopts=["-static"]) or MOSTLY STATIC mode (linkstatic=1). When this is true, we want to
     * use static versions of any libraries that this target depends on (except possibly system
     * libraries, which are not handled by CcLinkParams). When this is false, we want to use dynamic
     * versions of any libraries that this target depends on.
     */
    private boolean linkingStatically;

    /** linkShared is true when we're linking with "-shared" (linkshared=1). */
    private boolean linkShared;

    // TODO(plf): Ideally the two booleans above are removed from this Builder. We would pass the
    // specific instances of CcLinkParams that are needed from transitive dependencies instead of
    // calling the convenience methods that dig them out from the CcLinkParamsStore using these
    // booleans.
    private boolean linkingStaticallyLinkSharedSet;

    private ImmutableList.Builder<String> localLinkoptsBuilder = ImmutableList.builder();

    private final NestedSetBuilder<LinkOptions> linkOptsBuilder =
        NestedSetBuilder.linkOrder();
    private final NestedSetBuilder<Linkstamp> linkstampsBuilder =
        NestedSetBuilder.compileOrder();
    private final NestedSetBuilder<LibraryToLink> librariesBuilder =
        NestedSetBuilder.linkOrder();
    private final NestedSetBuilder<Artifact> dynamicLibrariesForRuntimeBuilder =
        NestedSetBuilder.stableOrder();

    /**
     * A builder for the list of link time libraries.  Most builds
     * won't have any such libraries, so save space by leaving the
     * default as null.
     */
    private ExtraLinkTimeLibraries.Builder extraLinkTimeLibrariesBuilder = null;

    private NestedSetBuilder<Artifact> nonCodeInputsBuilder = null;

    private boolean built = false;

    /** The static builder methods of {@link CcLinkParams} should be used for instantiation. */
    private Builder(boolean linkingStatically, boolean linkShared) {
      this.linkingStatically = linkingStatically;
      this.linkShared = linkShared;
      this.linkingStaticallyLinkSharedSet = true;
    }

    private Builder() {}

    /**
     * Builds a {@link CcLinkParams} object.
     */
    public CcLinkParams build() {
      Preconditions.checkState(!built);
      // Not thread-safe, but builders should not be shared across threads.
      built = true;
      ImmutableList<String> localLinkopts = localLinkoptsBuilder.build();
      if (!localLinkopts.isEmpty()) {
        linkOptsBuilder.add(LinkOptions.of(localLinkopts));
      }
      ExtraLinkTimeLibraries extraLinkTimeLibraries = null;
      if (extraLinkTimeLibrariesBuilder != null) {
        extraLinkTimeLibraries = extraLinkTimeLibrariesBuilder.build();
      }
      NestedSet<Artifact> nonCodeInputs = null;
      if (nonCodeInputsBuilder != null) {
        nonCodeInputs = nonCodeInputsBuilder.build();
      }
      return new CcLinkParams(
          linkOptsBuilder.build(),
          linkstampsBuilder.build(),
          librariesBuilder.build(),
          dynamicLibrariesForRuntimeBuilder.build(),
          extraLinkTimeLibraries,
          nonCodeInputs);
    }

    public boolean add(AbstractCcLinkParamsStore store) {
      Preconditions.checkState(linkingStaticallyLinkSharedSet);
      if (store != null) {
        CcLinkParams args = store.get(linkingStatically, linkShared);
        addTransitiveArgs(args);
      }
      return store != null;
    }

    /**
     * Includes link parameters from a collection of dependency targets.
     */
    public Builder addTransitiveTargets(Iterable<? extends TransitiveInfoCollection> targets) {
      for (TransitiveInfoCollection target : targets) {
        addTransitiveTarget(target);
      }
      return this;
    }

    /**
     * Includes link parameters from a dependency target.
     *
     * <p>The target should implement {@link CcLinkParamsStore}. If it does not, the method does not
     * do anything.
     */
    public Builder addTransitiveTarget(TransitiveInfoCollection target) {
      CcLinkingInfo ccLinkingInfo = target.get(CcLinkingInfo.PROVIDER);
      CcLinkParamsStore ccLinkParamsStore =
          ccLinkingInfo == null ? null : ccLinkingInfo.getCcLinkParamsStore();
      if (ccLinkParamsStore != null) {
        add(ccLinkParamsStore);
      }
      return this;
    }

    /**
     * Includes link parameters from a dependency target. The target is checked for the given
     * mappings in the order specified, and the first mapping that returns a non-null result is
     * added.
     */
    @SafeVarargs
    public final Builder addTransitiveTarget(
        TransitiveInfoCollection target,
        Function<TransitiveInfoCollection, AbstractCcLinkParamsStore> firstMapping,
        @SuppressWarnings("unchecked") // Java arrays don't preserve generic arguments.
            Function<TransitiveInfoCollection, AbstractCcLinkParamsStore>... remainingMappings) {
      if (add(firstMapping.apply(target))) {
        return this;
      }
      for (Function<TransitiveInfoCollection, AbstractCcLinkParamsStore> mapping :
          remainingMappings) {
        if (add(mapping.apply(target))) {
          return this;
        }
      }
      return this;
    }

    /**
     * Includes link parameters from the given targets. Each target is checked for the given
     * mappings in the order specified, and the first mapping that returns a non-null result is
     * added.
     */
    @SafeVarargs
    public final Builder addTransitiveTargets(
        Iterable<? extends TransitiveInfoCollection> targets,
        Function<TransitiveInfoCollection, AbstractCcLinkParamsStore> firstMapping,
        @SuppressWarnings("unchecked") // Java arrays don't preserve generic arguments.
            Function<TransitiveInfoCollection, AbstractCcLinkParamsStore>... remainingMappings) {
      for (TransitiveInfoCollection target : targets) {
        addTransitiveTarget(target, firstMapping, remainingMappings);
      }
      return this;
    }

    /**
     * Merges the other {@link CcLinkParams} object into this one.
     */
    public Builder addTransitiveArgs(CcLinkParams args) {
      linkOptsBuilder.addTransitive(args.getLinkopts());
      linkstampsBuilder.addTransitive(args.getLinkstamps());
      librariesBuilder.addTransitive(args.getLibraries());
      dynamicLibrariesForRuntimeBuilder.addTransitive(args.getDynamicLibrariesForRuntime());
      if (args.getExtraLinkTimeLibraries() != null) {
        if (extraLinkTimeLibrariesBuilder == null) {
          extraLinkTimeLibrariesBuilder = ExtraLinkTimeLibraries.builder();
        }
        extraLinkTimeLibrariesBuilder.addTransitive(args.getExtraLinkTimeLibraries());
      }
      if (args.getNonCodeInputs() != null) {
        if (nonCodeInputsBuilder == null) {
          nonCodeInputsBuilder = NestedSetBuilder.linkOrder();
        }
        nonCodeInputsBuilder.addTransitive(args.getNonCodeInputs());
      }
      return this;
    }

    /**
     * Adds a collection of link options.
     */
    public Builder addLinkOpts(Collection<String> linkOpts) {
      localLinkoptsBuilder.addAll(linkOpts);
      return this;
    }

    /** Adds a collection of linkstamps. */
    public Builder addLinkstamps(
        NestedSet<Artifact> linkstamps, CcCompilationContext ccCompilationContext) {
      for (Artifact linkstamp : linkstamps) {
        linkstampsBuilder.add(
            new Linkstamp(linkstamp, ccCompilationContext.getDeclaredIncludeSrcs()));
      }
      return this;
    }

    /**
     * Adds a library artifact.
     */
    public Builder addLibrary(LibraryToLink library) {
      librariesBuilder.add(library);
      return this;
    }

    /**
     * Adds a collection of library artifacts.
     */
    public Builder addLibraries(Iterable<LibraryToLink> libraries) {
      librariesBuilder.addAll(libraries);
      return this;
    }

    /** Adds a collection of library artifacts. */
    public Builder addDynamicLibrariesForRuntime(Iterable<Artifact> libraries) {
      dynamicLibrariesForRuntimeBuilder.addAll(libraries);
      return this;
    }

    /**
     * Adds an extra link time library, a library that is actually
     * built at link time.
     */
    public Builder addExtraLinkTimeLibrary(ExtraLinkTimeLibrary e) {
      if (extraLinkTimeLibrariesBuilder == null) {
        extraLinkTimeLibrariesBuilder = ExtraLinkTimeLibraries.builder();
      }
      extraLinkTimeLibrariesBuilder.add(e);
      return this;
    }

    /**
     * Adds a collection of non-code inputs.
     */
    public Builder addNonCodeInputs(Iterable<Artifact> nonCodeInputs) {
      if (nonCodeInputsBuilder == null) {
        nonCodeInputsBuilder = NestedSetBuilder.linkOrder();
      }
      nonCodeInputsBuilder.addAll(nonCodeInputs);
      return this;
    }

    /** Processes typical dependencies of a C/C++ library. */
    public Builder addCcLibrary(RuleContext context) {
      addTransitiveTargets(
          context.getPrerequisites("deps", Mode.TARGET), CcLinkParamsStore.TO_LINK_PARAMS);
      return this;
    }
  }

  /**
   * A linkstamp that also knows about its declared includes.
   *
   * <p>This object is required because linkstamp files may include other headers which will have to
   * be provided during compilation.
   */
  @AutoCodec
  public static final class Linkstamp {
    private final Artifact artifact;
    private final NestedSet<Artifact> declaredIncludeSrcs;

    @VisibleForSerialization
    Linkstamp(Artifact artifact, NestedSet<Artifact> declaredIncludeSrcs) {
      this.artifact = Preconditions.checkNotNull(artifact);
      this.declaredIncludeSrcs = Preconditions.checkNotNull(declaredIncludeSrcs);
    }

    /**
     * Returns the linkstamp artifact.
     */
    public Artifact getArtifact() {
      return artifact;
    }

    /**
     * Returns the declared includes.
     */
    public NestedSet<Artifact> getDeclaredIncludeSrcs() {
      return declaredIncludeSrcs;
    }

    @Override
    public int hashCode() {
      return Objects.hash(artifact, declaredIncludeSrcs);
    }

    @Override
    public boolean equals(Object obj) {
      if (this == obj) {
        return true;
      }
      if (!(obj instanceof Linkstamp)) {
        return false;
      }
      Linkstamp other = (Linkstamp) obj;
      return artifact.equals(other.artifact)
          && declaredIncludeSrcs.equals(other.declaredIncludeSrcs);
    }
  }

  /** Empty CcLinkParams. */
  public static final CcLinkParams EMPTY =
      new CcLinkParams(
          NestedSetBuilder.<LinkOptions>emptySet(Order.LINK_ORDER),
          NestedSetBuilder.<Linkstamp>emptySet(Order.COMPILE_ORDER),
          NestedSetBuilder.<LibraryToLink>emptySet(Order.LINK_ORDER),
          NestedSetBuilder.<Artifact>emptySet(Order.STABLE_ORDER),
          null,
          null);
}