aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/test/java/com/google/devtools/build/lib/packages/util/MockCcSupport.java
blob: 324ff10a8653d4cbd84cc1d214969d87c351c1e0 (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
// Copyright 2015 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.packages.util;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Verify;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.rules.cpp.CppCompileAction;
import com.google.devtools.build.lib.rules.cpp.CppRuleClasses;
import com.google.devtools.build.lib.rules.cpp.Link.LinkTargetType;
import com.google.devtools.build.lib.testutil.TestConstants;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig;
import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain;
import com.google.protobuf.TextFormat;
import com.google.protobuf.TextFormat.ParseException;
import java.io.IOException;

/**
 * Creates mock BUILD files required for the C/C++ rules.
 */
public abstract class MockCcSupport {

  /**
   * Builder to build crosstool files for unit testing.
   */
  public static final class CrosstoolBuilder {
    public static final String DEFAULT_TARGET_CPU = "k8";
    public static final String MAJOR_VERSION = "13";
    public static final String MINOR_VERSION = "0";

    private final CrosstoolConfig.CrosstoolRelease.Builder builder =
        CrosstoolConfig.CrosstoolRelease.newBuilder()
            .setMajorVersion(MAJOR_VERSION)
            .setMinorVersion(MINOR_VERSION)
            .setDefaultTargetCpu(DEFAULT_TARGET_CPU);

    /** Adds a default toolchain in the order of the calls. */
    public CrosstoolBuilder addDefaultToolchain(String cpu, String toolchainIdentifier) {
      builder.addDefaultToolchainBuilder().setCpu(cpu).setToolchainIdentifier(toolchainIdentifier);
      return this;
    }

    /** Adds a default toolchain in the order of the calls. */
    public CrosstoolBuilder addDefaultToolchain(
        String cpu, String toolchainIdentifier, boolean supportsLipo) {
      builder
          .addDefaultToolchainBuilder()
          .setCpu(cpu)
          .setToolchainIdentifier(toolchainIdentifier)
          .setSupportsLipo(supportsLipo);
      return this;
    }

    /** Adds a toolchain where all required fields are set. */
    public CrosstoolBuilder addToolchain(String cpu, String toolchainIdentifier, String compiler) {
      builder
          .addToolchainBuilder()
          .setTargetCpu(cpu)
          .setToolchainIdentifier(toolchainIdentifier)
          .setHostSystemName("host-system-name")
          .setTargetSystemName("target-system-name")
          .setTargetLibc("target-libc")
          .setCompiler(compiler)
          .setAbiVersion("abi-version")
          .setAbiLibcVersion("abi-libc-version")
          // TODO(klimek): Move to features.
          .setSupportsStartEndLib(true);
      return this;
    }

    /** Appends the snippet {@code configuration} to all previously added toolchains. */
    public CrosstoolBuilder appendToAllToolchains(CToolchain configuration) {
      for (CToolchain.Builder toolchainBuilder : builder.getToolchainBuilderList()) {
        toolchainBuilder.mergeFrom(configuration);
      }
      return this;
    }

    /** Appends the snippet {@code configuration} to all previously added toolchains. */
    public CrosstoolBuilder appendToAllToolchains(String... configuration) throws IOException {
      CToolchain.Builder toolchainBuilder = CToolchain.newBuilder();
      TextFormat.merge(Joiner.on("\n").join(configuration), toolchainBuilder);
      appendToAllToolchains(toolchainBuilder.buildPartial());
      return this;
    }

    /** Returns the text proto containing the crosstool. */
    public String build() {
      return TextFormat.printToString(builder.build());
    }
  }

  /** Filter to remove implicit crosstool artifact and module map inputs of C/C++ rules. */
  public static final Predicate<Artifact> CC_ARTIFACT_FILTER =
      new Predicate<Artifact>() {
        @Override
        public boolean apply(Artifact artifact) {
          String basename = artifact.getExecPath().getBaseName();
          String pathString = artifact.getExecPathString();
          return !pathString.startsWith("third_party/crosstool/")
              && !pathString.startsWith("tools/cpp/link_dynamic_library")
              && !pathString.startsWith("tools/cpp/build_interface_so")
              && !(pathString.contains("/internal/_middlemen") && basename.contains("crosstool"))
              && !pathString.startsWith("_bin/build_interface_so")
              && !pathString.endsWith(".cppmap")
              && !pathString.startsWith("tools/cpp/grep-includes");
        }
      };

  /** This feature will prevent bazel from patching the crosstool. */
  public static final String NO_LEGACY_FEATURES_FEATURE = "feature { name: 'no_legacy_features' }";

  public static final String DYNAMIC_LINKING_MODE_FEATURE =
      "feature { name: '" + CppRuleClasses.DYNAMIC_LINKING_MODE + "'}";

  /** Feature expected by the C++ rules when pic build is requested */
  public static final String PIC_FEATURE =
      ""
          + "feature {"
          + "  name: 'pic'"
          + "  flag_set {"
          + "    action: 'c-compile'"
          + "    action: 'c++-compile'"
          + "    action: 'c++-module-codegen'"
          + "    action: 'c++-module-compile'"
          + "    action: 'preprocess-assemble'"
          + "    expand_if_all_available: 'pic'"
          + "    flag_group {"
          + "      flag: '-fPIC'"
          + "    }"
          + "  }"
          + "}";

  /**
   * A feature configuration snippet useful for testing header processing.
   */
  public static final String HEADER_PROCESSING_FEATURE_CONFIGURATION =
      ""
          + "feature {"
          + "  name: 'parse_headers'"
          + "  flag_set {"
          + "    action: 'c++-header-parsing'"
          + "    flag_group {"
          + "      flag: '<c++-header-parsing>'"
          + "    }"
          + "  }"
          + "}"
          + "feature {"
          + "  name: 'preprocess_headers'"
          + "  flag_set {"
          + "    action: 'c++-header-preprocessing'"
          + "    flag_group {"
          + "      flag: '<c++-header-preprocessing>'"
          + "    }"
          + "  }"
          + "}";

  /** A feature configuration snippet useful for testing the layering check. */
  public static final String LAYERING_CHECK_FEATURE_CONFIGURATION =
      ""
          + "feature {"
          + "  name: 'layering_check'"
          + "  flag_set {"
          + "    action: 'c-compile'"
          + "    action: 'c++-compile'"
          + "    action: 'c++-header-parsing'"
          + "    action: 'c++-header-preprocessing'"
          + "    action: 'c++-module-compile'"
          + "    flag_group {"
          + "      iterate_over: 'dependent_module_map_files'"
          + "      flag: 'dependent_module_map_file:%{dependent_module_map_files}'"
          + "    }"
          + "  }"
          + "}";

  /** A feature configuration snippet useful for testing header modules. */
  public static final String HEADER_MODULES_FEATURE_CONFIGURATION =
      ""
          + "feature {"
          + "  name: 'header_modules'"
          + "  implies: 'use_header_modules'"
          + "  implies: 'header_module_compile'"
          + "}"
          + "feature {"
          + "  name: 'header_module_compile'"
          + "  implies: 'module_maps'"
          + "  flag_set {"
          + "    action: 'c++-module-compile'"
          + "    flag_group {"
          + "      flag: '--woohoo_modules'"
          + "    }"
          + "  }"
          + "  flag_set {"
          + "    action: 'c++-module-codegen'"
          + "    flag_group {"
          + "      flag: '--this_is_modules_codegen'"
          + "    }"
          + "  }"
          + "}"
          + "feature {"
          + "  name: 'header_module_codegen'"
          + "  implies: 'header_modules'"
          + "}"
          + "feature {"
          + "  name: 'module_maps'"
          + "  flag_set {"
          + "    action: 'c-compile'"
          + "    action: 'c++-compile'"
          + "    action: 'c++-header-parsing'"
          + "    action: 'c++-header-preprocessing'"
          + "    action: 'c++-module-compile'"
          + "    flag_group {"
          + "      flag: 'module_name:%{module_name}'"
          + "      flag: 'module_map_file:%{module_map_file}'"
          + "    }"
          + "  }"
          + "}"
          + "feature {"
          + "  name: 'use_header_modules'"
          + "  flag_set {"
          + "    action: 'c-compile'"
          + "    action: 'c++-compile'"
          + "    action: 'c++-header-parsing'"
          + "    action: 'c++-header-preprocessing'"
          + "    action: 'c++-modules-compile'"
          + "    flag_group {"
          + "      iterate_over: 'module_files'"
          + "      flag: 'module_file:%{module_files}'"
          + "    }"
          + "  }"
          + "}";

  /**
   * A feature configuration snippet useful for testing environment variables.
   */
  public static final String ENV_VAR_FEATURE_CONFIGURATION =
      ""
          + "feature {"
          + "  name: 'env_feature'"
          + "  implies: 'static_env_feature'"
          + "  implies: 'module_maps'"
          + "}"
          + "feature {"
          + "  name: 'static_env_feature'"
          + "  env_set {"
          + "    action: 'c-compile'"
          + "    action: 'c++-compile'"
          + "    action: 'c++-header-parsing'"
          + "    action: 'c++-header-preprocessing'"
          + "    action: 'c++-module-compile'"
          + "    env_entry {"
          + "      key: 'cat'"
          + "      value: 'meow'"
          + "    }"
          + "  }"
          + "}"
          + "feature {"
          + "  name: 'module_maps'"
          + "  env_set {"
          + "    action: 'c-compile'"
          + "    action: 'c++-compile'"
          + "    action: 'c++-header-parsing'"
          + "    action: 'c++-header-preprocessing'"
          + "    action: 'c++-module-compile'"
          + "    env_entry {"
          + "      key: 'module'"
          + "      value: 'module_name:%{module_name}'"
          + "    }"
          + "  }"
          + "}";

  public static final String HOST_AND_NONHOST_CONFIGURATION =
      ""
          + "feature { "
          + "  name: 'host'"
          + "  flag_set {"
          + "    action: 'c-compile'"
          + "    action: 'c++-compile'"
          + "    flag_group {"
          + "      flag: '-host'"
          + "    }"
          + "  }"
          + "}"
          + "feature { "
          + "  name: 'nonhost'"
          + "  flag_set {"
          + "    action: 'c-compile'"
          + "    action: 'c++-compile'"
          + "    flag_group {"
          + "      flag: '-nonhost'"
          + "    }"
          + "  }"
          + "}";

  public static final String THIN_LTO_CONFIGURATION =
      ""
          + "feature { "
          + "  name: 'thin_lto'"
          + "  requires { feature: 'nonhost' }"
          + "  flag_set {"
          + "    expand_if_all_available: 'thinlto_param_file'"
          + "    action: 'c++-link-executable'"
          + "    action: 'c++-link-dynamic-library'"
          + "    action: 'c++-link-nodeps-dynamic-library'"
          + "    action: 'c++-link-static-library'"
          + "    flag_group {"
          + "      flag: 'thinlto_param_file=%{thinlto_param_file}'"
          + "    }"
          + "  }"
          + "  flag_set {"
          + "    action: 'c-compile'"
          + "    action: 'c++-compile'"
          + "    flag_group {"
          + "      flag: '-flto=thin'"
          + "    }"
          + "    flag_group {"
          + "      expand_if_all_available: 'lto_indexing_bitcode_file'"
          + "      flag: 'lto_indexing_bitcode=%{lto_indexing_bitcode_file}'"
          + "    }"
          + "  }"
          + "  flag_set {"
          + "    action: 'lto-indexing'"
          + "    flag_group {"
          + "      flag: 'param_file=%{thinlto_indexing_param_file}'"
          + "      flag: 'prefix_replace=%{thinlto_prefix_replace}'"
          + "    }"
          + "    flag_group {"
          + "      expand_if_all_available: 'thinlto_object_suffix_replace'"
          + "      flag: 'object_suffix_replace=%{thinlto_object_suffix_replace}'"
          + "    }"
          + "    flag_group {"
          + "      expand_if_all_available: 'thinlto_merged_object_file'"
          + "      flag: 'thinlto_merged_object_file=%{thinlto_merged_object_file}'"
          + "    }"
          + "  }"
          + "  flag_set {"
          + "    action: 'lto-backend'"
          + "    flag_group {"
          + "      flag: 'thinlto_index=%{thinlto_index}'"
          + "      flag: 'thinlto_output_object_file=%{thinlto_output_object_file}'"
          + "      flag: 'thinlto_input_bitcode_file=%{thinlto_input_bitcode_file}'"
          + "    }"
          + "  }"
          + "}";

  public static final String THIN_LTO_LINKSTATIC_TESTS_USE_SHARED_NONLTO_BACKENDS_CONFIGURATION =
      "" + "feature {  name: 'thin_lto_linkstatic_tests_use_shared_nonlto_backends'}";

  public static final String ENABLE_AFDO_THINLTO_CONFIGURATION =
      ""
          + "feature {"
          + "  name: 'enable_afdo_thinlto'"
          + "  requires { feature: 'autofdo_implicit_thinlto' }"
          + "  implies: 'thin_lto'"
          + "}";

  public static final String AUTOFDO_IMPLICIT_THINLTO_CONFIGURATION =
      "" + "feature {  name: 'autofdo_implicit_thinlto'}";

  public static final String AUTO_FDO_CONFIGURATION =
      ""
          + "feature {"
          + "  name: 'autofdo'"
          + "  provides: 'profile'"
          + "  flag_set {"
          + "    action: 'c-compile'"
          + "    action: 'c++-compile'"
          + "    action: 'lto-backend'"
          + "    expand_if_all_available: 'fdo_profile_path'"
          + "    flag_group {"
          + "      flag: '-fauto-profile=%{fdo_profile_path}'"
          + "      flag: '-fprofile-correction'"
          + "    }"
          + "  }"
          + "}";

  public static final String FDO_INSTRUMENT_CONFIGURATION =
      ""
          + "feature { "
          + "  name: 'fdo_instrument'"
          + "  provides: 'profile'"
          + "  flag_set {"
          + "    action: 'c-compile'"
          + "    action: 'c++-compile'"
          + "    action: 'c++-link-dynamic-library'"
          + "    action: 'c++-link-nodeps-dynamic-library'"
          + "    action: 'c++-link-executable'"
          + "    flag_group {"
          + "      flag: 'fdo_instrument_option'"
          + "      flag: 'path=%{fdo_instrument_path}'"
          + "    }"
          + "  }"
          + "}";

  public static final String PER_OBJECT_DEBUG_INFO_CONFIGURATION =
      ""
          + "feature { "
          + "  name: 'per_object_debug_info'"
          + "  flag_set {"
          + "    action: 'c-compile'"
          + "    action: 'c++-compile'"
          + "    action: 'assemble'"
          + "    action: 'preprocess-assemble'"
          + "    action: 'c++-module-codegen'"
          + "    action: 'lto-backend'"
          + "    expand_if_all_available: 'per_object_debug_info_file'"
          + "    flag_group {"
          + "      flag: 'per_object_debug_info_option'"
          + "    }"
          + "  }"
          + "}";

  public static final String COPY_DYNAMIC_LIBRARIES_TO_BINARY_CONFIGURATION =
      "" + "feature { " + "  name: 'copy_dynamic_libraries_to_binary'" + "}";

  public static final String TARGETS_WINDOWS_CONFIGURATION =
      ""
          + "feature {"
          + "   name: 'targets_windows'"
          + "   implies: 'copy_dynamic_libraries_to_binary'"
          + "   enabled: true"
          + "}";

  public static final String STATIC_LINK_TWEAKED_CONFIGURATION =
      ""
          + "artifact_name_pattern {"
          + "   category_name: 'static_library'"
          + "   pattern: 'lib%{base_name}.tweaked.a'"
          + "}";

  public static final String STATIC_LINK_AS_DOT_A_CONFIGURATION =
      ""
          + "artifact_name_pattern {"
          + "   category_name: 'static_library'"
          + "   pattern: 'lib%{base_name}.a'"
          + "}";

  public static final String STATIC_LINK_BAD_TEMPLATE_CONFIGURATION =
      ""
          + "artifact_name_pattern {"
          + "   category_name: 'static_library'"
          + "   pattern: 'foo%{bad_variable}bar'"
          + "}";

  public static final String EMPTY_COMPILE_ACTION_CONFIG =
      emptyActionConfigFor(CppCompileAction.CPP_COMPILE);

  public static final String EMPTY_MODULE_CODEGEN_ACTION_CONFIG =
      emptyActionConfigFor(CppCompileAction.CPP_MODULE_CODEGEN);

  public static final String EMPTY_MODULE_COMPILE_ACTION_CONFIG =
      emptyActionConfigFor(CppCompileAction.CPP_MODULE_COMPILE);

  public static final String EMPTY_EXECUTABLE_ACTION_CONFIG =
      emptyActionConfigFor(LinkTargetType.EXECUTABLE.getActionName());

  public static final String EMPTY_DYNAMIC_LIBRARY_ACTION_CONFIG =
      emptyActionConfigFor(LinkTargetType.NODEPS_DYNAMIC_LIBRARY.getActionName());

  public static final String EMPTY_TRANSITIVE_DYNAMIC_LIBRARY_ACTION_CONFIG =
      emptyActionConfigFor(LinkTargetType.DYNAMIC_LIBRARY.getActionName());

  public static final String EMPTY_STATIC_LIBRARY_ACTION_CONFIG =
      emptyActionConfigFor(LinkTargetType.STATIC_LIBRARY.getActionName());

  public static final String EMPTY_CLIF_MATCH_ACTION_CONFIG =
      emptyActionConfigFor(CppCompileAction.CLIF_MATCH);

  public static final String EMPTY_STRIP_ACTION_CONFIG =
      emptyActionConfigFor(CppCompileAction.STRIP_ACTION_NAME);

  /**
   * Creates action_config for {@code actionName} action using DUMMY_TOOL that doesn't imply any
   * features.
   */
  private static String emptyActionConfigFor(String actionName) {
    return String.format(
        "action_config {"
            + "  config_name: '%s'"
            + "  action_name: '%s'"
            + "  tool {"
            + "    tool_path: 'DUMMY_TOOL'"
            + "  }"
            + "}",
        actionName, actionName);
  }

  /** Filter to remove implicit dependencies of C/C++ rules. */
  private final Predicate<Label> ccLabelFilter =
      new Predicate<Label>() {
        @Override
        public boolean apply(Label label) {
          return labelNameFilter().apply("//" + label.getPackageName());
        }
      };

  public static String mergeCrosstoolConfig(String original, CToolchain toolchain)
      throws TextFormat.ParseException {
    CrosstoolConfig.CrosstoolRelease.Builder builder =
        CrosstoolConfig.CrosstoolRelease.newBuilder();
    TextFormat.merge(original, builder);
    for (CToolchain.Builder toolchainBuilder : builder.getToolchainBuilderList()) {
      toolchainBuilder.mergeFrom(toolchain);
    }
    return TextFormat.printToString(builder.build());
  }

  /** Applies the given function to the first toolchain that applies to the given cpu. */
  public static String applyToToolchain(
      String original,
      String targetCpu,
      Function<CToolchain.Builder, CToolchain.Builder> transformation)
      throws ParseException {
    CrosstoolConfig.CrosstoolRelease.Builder crosstoolBuilder =
        CrosstoolConfig.CrosstoolRelease.newBuilder();
    TextFormat.merge(original, crosstoolBuilder);
    for (int i = 0; i < crosstoolBuilder.getToolchainCount(); i++) {
      if (crosstoolBuilder.getToolchain(i).getTargetCpu().equals(targetCpu)) {
        CToolchain.Builder toolchainBuilder =
            CToolchain.newBuilder(crosstoolBuilder.getToolchain(i));
        transformation.apply(toolchainBuilder);
        crosstoolBuilder.removeToolchain(i);
        crosstoolBuilder.addToolchain(toolchainBuilder.build());
        break;
      }
    }

    return TextFormat.printToString(crosstoolBuilder.build());
  }

  public static String addOptionalDefaultCoptsToCrosstool(String original)
      throws TextFormat.ParseException {
    CrosstoolConfig.CrosstoolRelease.Builder builder =
        CrosstoolConfig.CrosstoolRelease.newBuilder();
    TextFormat.merge(original, builder);
    for (CrosstoolConfig.CToolchain.Builder toolchain : builder.getToolchainBuilderList()) {
      CrosstoolConfig.CToolchain.OptionalFlag.Builder defaultTrue =
          CrosstoolConfig.CToolchain.OptionalFlag.newBuilder();
      defaultTrue.setDefaultSettingName("crosstool_default_true");
      defaultTrue.addFlag("-DDEFAULT_TRUE");
      toolchain.addOptionalCompilerFlag(defaultTrue.build());
      CrosstoolConfig.CToolchain.OptionalFlag.Builder defaultFalse =
          CrosstoolConfig.CToolchain.OptionalFlag.newBuilder();
      defaultFalse.setDefaultSettingName("crosstool_default_false");
      defaultFalse.addFlag("-DDEFAULT_FALSE");
      toolchain.addOptionalCompilerFlag(defaultFalse.build());
    }

    CrosstoolConfig.CrosstoolRelease.DefaultSetting.Builder defaultTrue =
        CrosstoolConfig.CrosstoolRelease.DefaultSetting.newBuilder();
    defaultTrue.setName("crosstool_default_true");
    defaultTrue.setDefaultValue(true);
    builder.addDefaultSetting(defaultTrue.build());
    CrosstoolConfig.CrosstoolRelease.DefaultSetting.Builder defaultFalse =
        CrosstoolConfig.CrosstoolRelease.DefaultSetting.newBuilder();
    defaultFalse.setName("crosstool_default_false");
    defaultFalse.setDefaultValue(false);
    builder.addDefaultSetting(defaultFalse.build());

    return TextFormat.printToString(builder.build());
  }

  public static String addLibcLabelToCrosstool(String original, String label)
      throws TextFormat.ParseException {
    CrosstoolConfig.CrosstoolRelease.Builder builder =
        CrosstoolConfig.CrosstoolRelease.newBuilder();
    TextFormat.merge(original, builder);
    for (CrosstoolConfig.CToolchain.Builder toolchain : builder.getToolchainBuilderList()) {
      toolchain.setDefaultGrteTop(label);
    }
    return TextFormat.printToString(builder.build());
  }

  public abstract Predicate<String> labelNameFilter();

  /**
   * Setup the support for building C/C++.
   */
  public abstract void setup(MockToolsConfig config) throws IOException;

  public void setupCrosstoolWithEmbeddedRuntimes(MockToolsConfig config) throws IOException {
    createCrosstoolPackage(config, true);
  }

  /**
   * Creates a crosstool package by merging {@code toolchain} with the default mock CROSSTOOL file.
   *
   * @param partialToolchain A string representation of a CToolchain protocol buffer; note that
   *        this is allowed to be a partial buffer (required fields may be omitted).
   */
  public void setupCrosstool(MockToolsConfig config, String... partialToolchain)
      throws IOException {
    CToolchain.Builder toolchainBuilder = CToolchain.newBuilder();
    TextFormat.merge(Joiner.on("\n").join(partialToolchain), toolchainBuilder);
    setupCrosstool(config, toolchainBuilder.buildPartial());
  }

  /**
   * Creates a crosstool package by merging {@code toolchain} with the default mock CROSSTOOL file.
   */
  public void setupCrosstool(MockToolsConfig config, CToolchain toolchain) throws IOException {
    createCrosstoolPackage(
        config, /* addEmbeddedRuntimes= */ false, /* addModuleMap= */ true, null, null, toolchain);
  }

  /**
   * Create a crosstool package. For integration tests, it actually links in a working crosstool,
   * for all other tests, it only creates a dummy package, with a working CROSSTOOL file.
   *
   * <p>If <code>addEmbeddedRuntimes</code> is true, it also adds filegroups for the embedded
   * runtimes.
   */
  public void setupCrosstool(
      MockToolsConfig config,
      boolean addEmbeddedRuntimes,
      boolean addModuleMap,
      String staticRuntimesLabel,
      String dynamicRuntimesLabel,
      CToolchain toolchain)
      throws IOException {
    createCrosstoolPackage(
        config,
        addEmbeddedRuntimes,
        addModuleMap,
        staticRuntimesLabel,
        dynamicRuntimesLabel,
        toolchain);
  }

  public void setupCrosstool(
      MockToolsConfig config,
      boolean addEmbeddedRuntimes,
      boolean addModuleMap,
      String staticRuntimesLabel,
      String dynamicRuntimesLabel,
      String crosstool)
      throws IOException {
    createCrosstoolPackage(
        config,
        addEmbeddedRuntimes,
        addModuleMap,
        staticRuntimesLabel,
        dynamicRuntimesLabel,
        crosstool);
  }

  public void setupCrosstoolWithRelease(MockToolsConfig config, String crosstool)
      throws IOException {
    createCrosstoolPackage(config, false, true, null, null, crosstool);
  }

  /**
   * Create a new crosstool configuration specified by {@code builder}.
   *
   * <p>If used from a {@code BuildViewTestCase}, make sure to call {@code
   * BuildViewTestCase.invalidatePackages} after calling this method to force re-loading of the
   * crosstool's BUILD files.
   */
  public void setupCrosstoolFromScratch(MockToolsConfig config, CrosstoolBuilder builder)
      throws IOException {
    if (config.isRealFileSystem()) {
      throw new RuntimeException(
          "Cannot use setupCrosstoolFromScratch when config.isRealFileSystem() is true; "
              + "use this function only for unit tests.");
    }
    // TODO(klimek): Get the version information from the crosstool builder and set up the
    // crosstool with that information.
    createCrosstoolPackage(
        config,
        /*addEmbeddedRuntimes=*/ false,
        /*addModuleMap=*/ true,
        null,
        null,
        builder.build());
  }

  protected static void createToolsCppPackage(MockToolsConfig config) throws IOException {
    config.create(
        "tools/cpp/BUILD",
        "package(default_visibility = ['//visibility:public'])",
        "toolchain_type(name = 'toolchain_type')",
        "cc_library(name = 'stl')",
        "alias(name='toolchain', actual='//third_party/crosstool')",
        "cc_library(name = 'malloc')",
        "filegroup(",
        "    name = 'interface_library_builder',",
        "    srcs = ['build_interface_so'],",
        ")",
        "filegroup(",
        "    name = 'link_dynamic_library',",
        "    srcs = ['link_dynamic_library.sh'],",
        ")",
        "exports_files(['grep-includes'])");
    if (config.isRealFileSystem()) {
      config.linkTool("tools/cpp/link_dynamic_library.sh");
      config.linkTool("tools/cpp/build_interface_so");
      config.linkTool("tools/cpp/grep-includes");
    } else {
      config.create("tools/cpp/link_dynamic_library.sh", "");
      config.create("tools/cpp/build_interface_so", "");
      config.create("tools/cpp/grep-includes", "");
    }
  }

  protected void createCrosstoolPackage(MockToolsConfig config, boolean addEmbeddedRuntimes)
      throws IOException {
    createCrosstoolPackage(config, addEmbeddedRuntimes, /*addModuleMap=*/ true, null, null);
  }

  private void createCrosstoolPackage(
      MockToolsConfig config,
      boolean addEmbeddedRuntimes,
      boolean addModuleMap,
      String staticRuntimesLabel,
      String dynamicRuntimesLabel)
      throws IOException {
    createCrosstoolPackage(
        config,
        addEmbeddedRuntimes,
        addModuleMap,
        staticRuntimesLabel,
        dynamicRuntimesLabel,
        readCrosstoolFile());
  }

  private void createCrosstoolPackage(
      MockToolsConfig config,
      boolean addEmbeddedRuntimes,
      boolean addModuleMap,
      String staticRuntimesLabel,
      String dynamicRuntimesLabel,
      CToolchain toolchain)
      throws IOException {
    String crosstoolFile = mergeCrosstoolConfig(readCrosstoolFile(), toolchain);
    createCrosstoolPackage(
        config,
        addEmbeddedRuntimes,
        addModuleMap,
        staticRuntimesLabel,
        dynamicRuntimesLabel,
        crosstoolFile);
  }

  protected void createCrosstoolPackage(
      MockToolsConfig config,
      boolean addEmbeddedRuntimes,
      boolean addModuleMap,
      String staticRuntimesLabel,
      String dynamicRuntimesLabel,
      String crosstoolFile)
      throws IOException {
    String crosstoolTop = getCrosstoolTopPathForConfig(config);
    if (config.isRealFileSystem()) {
      config.linkTools(getRealFilesystemTools(crosstoolTop));
    } else {
      new Crosstool(config, crosstoolTop)
          .setEmbeddedRuntimes(addEmbeddedRuntimes, staticRuntimesLabel, dynamicRuntimesLabel)
          .setCrosstoolFile(getMockCrosstoolVersion(), crosstoolFile)
          .setSupportedArchs(getCrosstoolArchs())
          .setAddModuleMap(addModuleMap)
          .setSupportsHeaderParsing(true)
          .write();
    }
  }

  protected String getCrosstoolTopPathForConfig(MockToolsConfig config) {
    if (config.isRealFileSystem()) {
      return getRealFilesystemCrosstoolTopPath();
    } else {
      return getMockCrosstoolPath();
    }
  }

  public abstract String getMockCrosstoolPath();

  public static PackageIdentifier getMockCrosstoolsTop() {
    try {
      return PackageIdentifier.create(
          RepositoryName.create(TestConstants.TOOLS_REPOSITORY),
          PathFragment.create(TestConstants.MOCK_CC_CROSSTOOL_PATH));
    } catch (LabelSyntaxException e) {
      Verify.verify(false);
      throw new AssertionError();
    }
  }

  public abstract String getMockCrosstoolVersion();

  public abstract Label getMockCrosstoolLabel();

  public abstract String readCrosstoolFile() throws IOException;

  public abstract String getMockLibcPath();

  protected abstract ImmutableList<String> getCrosstoolArchs();

  protected abstract String[] getRealFilesystemTools(String crosstoolTop);

  protected abstract String getRealFilesystemCrosstoolTopPath();

  public final Predicate<Label> labelFilter() {
    return ccLabelFilter;
  }
}