aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedStrategy.java
blob: 99d71831828a5cd52c3b9091b1811e4fb7dfc098 (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
// 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.sandbox;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Files;
import com.google.devtools.build.lib.Constants;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.ActionInput;
import com.google.devtools.build.lib.actions.ActionInputHelper;
import com.google.devtools.build.lib.actions.ActionStatusMessage;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.EnvironmentalExecException;
import com.google.devtools.build.lib.actions.ExecException;
import com.google.devtools.build.lib.actions.ExecutionStrategy;
import com.google.devtools.build.lib.actions.Executor;
import com.google.devtools.build.lib.actions.Spawn;
import com.google.devtools.build.lib.actions.SpawnActionContext;
import com.google.devtools.build.lib.actions.UserExecException;
import com.google.devtools.build.lib.analysis.AnalysisUtils;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.analysis.config.RunUnder;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.rules.cpp.CppCompileAction;
import com.google.devtools.build.lib.rules.fileset.FilesetActionContext;
import com.google.devtools.build.lib.rules.test.TestRunnerAction;
import com.google.devtools.build.lib.standalone.StandaloneSpawnStrategy;
import com.google.devtools.build.lib.unix.NativePosixFiles;
import com.google.devtools.build.lib.util.Preconditions;
import com.google.devtools.build.lib.util.io.FileOutErr;
import com.google.devtools.build.lib.vfs.Dirent;
import com.google.devtools.build.lib.vfs.FileStatus;
import com.google.devtools.build.lib.vfs.FileSystem;
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 com.google.devtools.build.lib.vfs.SearchPath;
import com.google.devtools.build.lib.vfs.Symlinks;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Strategy that uses sandboxing to execute a process.
 */
@ExecutionStrategy(name = {"sandboxed"},
                   contextType = SpawnActionContext.class)
public class LinuxSandboxedStrategy implements SpawnActionContext {
  private final ExecutorService backgroundWorkers;

  private final ImmutableMap<String, String> clientEnv;
  private final BlazeDirectories blazeDirs;
  private final Path execRoot;
  private final boolean verboseFailures;
  private final boolean sandboxDebug;
  private final StandaloneSpawnStrategy standaloneStrategy;
  private final List<String> sandboxAddPath;
  private final UUID uuid = UUID.randomUUID();
  private final AtomicInteger execCounter = new AtomicInteger();

  public LinuxSandboxedStrategy(
      Map<String, String> clientEnv,
      BlazeDirectories blazeDirs,
      ExecutorService backgroundWorkers,
      boolean verboseFailures,
      boolean sandboxDebug,
      List<String> sandboxAddPath) {
    this.clientEnv = ImmutableMap.copyOf(clientEnv);
    this.blazeDirs = blazeDirs;
    this.execRoot = blazeDirs.getExecRoot();
    this.backgroundWorkers = Preconditions.checkNotNull(backgroundWorkers);
    this.verboseFailures = verboseFailures;
    this.sandboxDebug = sandboxDebug;
    this.sandboxAddPath = sandboxAddPath;
    this.standaloneStrategy = new StandaloneSpawnStrategy(blazeDirs.getExecRoot(), verboseFailures);
  }

  /**
   * Executes the given {@code spawn}.
   */
  @Override
  public void exec(Spawn spawn, ActionExecutionContext actionExecutionContext)
      throws ExecException {
    // Certain actions can't run remotely or in a sandbox - pass them on to the standalone strategy.
    if (!spawn.isRemotable()) {
      standaloneStrategy.exec(spawn, actionExecutionContext);
      return;
    }

    Executor executor = actionExecutionContext.getExecutor();

    if (executor.reportsSubcommands()) {
      executor.reportSubcommand(
          Label.print(spawn.getOwner().getLabel()) + " [" + spawn.getResourceOwner().prettyPrint()
              + "]", spawn.asShellCommand(executor.getExecRoot()));
    }

    executor
        .getEventBus()
        .post(ActionStatusMessage.runningStrategy(spawn.getResourceOwner(), "sandbox"));

    FileOutErr outErr = actionExecutionContext.getFileOutErr();

    // The execId is a unique ID just for this invocation of "exec".
    String execId = uuid + "-" + execCounter.getAndIncrement();

    // Each invocation of "exec" gets its own sandbox.
    Path sandboxPath =
        execRoot.getRelative(Constants.PRODUCT_NAME + "-sandbox").getRelative(execId);

    ImmutableMap<Path, Path> mounts;
    try {
      // Gather all necessary mounts for the sandbox.
      mounts = getMounts(spawn, actionExecutionContext);
    } catch (IllegalArgumentException | IOException e) {
      throw new EnvironmentalExecException("Could not prepare mounts for sandbox execution", e);
    }

    ImmutableSet<Path> createDirs = createImportantDirs(spawn.getEnvironment());

    int timeout = getTimeout(spawn);

    ImmutableSet.Builder<PathFragment> outputFiles = ImmutableSet.<PathFragment>builder();
    for (PathFragment optionalOutput : spawn.getOptionalOutputFiles()) {
      Preconditions.checkArgument(!optionalOutput.isAbsolute());
      outputFiles.add(optionalOutput);
    }
    for (ActionInput output : spawn.getOutputFiles()) {
      outputFiles.add(new PathFragment(output.getExecPathString()));
    }

    try {
      final NamespaceSandboxRunner runner =
          new NamespaceSandboxRunner(
              execRoot, sandboxPath, mounts, createDirs, verboseFailures, sandboxDebug);
      try {
        runner.run(
            spawn.getArguments(),
            spawn.getEnvironment(),
            execRoot.getPathFile(),
            outErr,
            outputFiles.build(),
            timeout,
            !spawn.getExecutionInfo().containsKey("requires-network"));
      } finally {
        // Due to the Linux kernel behavior, if we try to remove the sandbox too quickly after the
        // process has exited, we get "Device busy" errors because some of the mounts have not yet
        // been undone. A second later it usually works. We will just clean the old sandboxes up
        // using a background worker.
        backgroundWorkers.execute(
            new Runnable() {
              @Override
              public void run() {
                try {
                  while (!Thread.currentThread().isInterrupted()) {
                    try {
                      runner.cleanup();
                      return;
                    } catch (IOException e2) {
                      // Sleep & retry.
                      Thread.sleep(250);
                    }
                  }
                } catch (InterruptedException e) {
                  // Exit.
                }
              }
            });
      }
    } catch (IOException e) {
      throw new UserExecException("I/O error during sandboxed execution", e);
    }
  }

  private int getTimeout(Spawn spawn) throws ExecException {
    String timeoutStr = spawn.getExecutionInfo().get("timeout");
    if (timeoutStr != null) {
      try {
        return Integer.parseInt(timeoutStr);
      } catch (NumberFormatException e) {
        throw new UserExecException("Could not parse timeout", e);
      }
    }
    return -1;
  }

  /**
   * Most programs expect certain directories to be present, e.g. /tmp. Make sure they are.
   *
   * <p>Note that $HOME is handled by namespace-sandbox.c, because it changes user to nobody and the
   * home directory of that user is not known by us.
   */
  private ImmutableSet<Path> createImportantDirs(Map<String, String> env) {
    ImmutableSet.Builder<Path> dirs = ImmutableSet.builder();
    FileSystem fs = blazeDirs.getFileSystem();
    if (env.containsKey("TEST_TMPDIR")) {
      dirs.add(fs.getPath(env.get("TEST_TMPDIR")));
    }
    dirs.add(fs.getPath("/tmp"));
    return dirs.build();
  }

  private ImmutableMap<Path, Path> getMounts(Spawn spawn, ActionExecutionContext executionContext)
      throws IOException, ExecException {
    ImmutableMap.Builder<Path, Path> result = new ImmutableMap.Builder<>();
    result.putAll(mountUsualUnixDirs());
    result.putAll(mountUserDefinedPath());

    MountMap mounts = new MountMap();
    mounts.putAll(setupBlazeUtils());
    mounts.putAll(mountRunfilesFromManifests(spawn));
    mounts.putAll(mountRunfilesFromSuppliers(spawn));
    mounts.putAll(mountFilesFromFilesetManifests(spawn, executionContext));
    mounts.putAll(mountInputs(spawn, executionContext));
    mounts.putAll(mountRunUnderCommand(spawn));
    result.putAll(finalizeMounts(mounts));
    return result.build();
  }

  /**
   * Helper method of {@link #finalizeMounts}. This method handles adding a single path
   * to the output map, including making sure it exists and adding the target of a
   * symbolic link if necessary.
   *
   * @param finalizedMounts the map to add the mapping(s) to
   * @param target the key to add to the map
   * @param source the value to add to the map
   * @param stat information about source (passed in to avoid fetching it twice)
   */
  private static void finalizeMountPath(
      MountMap finalizedMounts, Path target, Path source, FileStatus stat) throws IOException {
    // The source must exist.
    Preconditions.checkArgument(stat != null, "%s does not exist", source.toString());

    if (stat.isSymbolicLink()) {
      Path symlinkTarget = source.resolveSymbolicLinks();
      Preconditions.checkArgument(
          symlinkTarget.exists(), "%s does not exist", symlinkTarget.toString());
      finalizedMounts.put(target, symlinkTarget);
    } else {
      finalizedMounts.put(target, source);
    }
  }

  /**
   * Checks if a folder is fully mounted (meaning it can be mounted as a whole instead
   * of mounting its contents individually).
   *
   * The results of previous lookups are cached to make this process faster, and this
   * function updates those caches as appropriate.
   *
   * @param directory the directory to check for being fully mounted or not
   * @param mounts all of the files which are being mounted
   * @param fullyMountedDirectories all the directories which have been found to be
   *                                fully mounted previously
   * @param notFullyMountedDirectories all the directories which been found to not be
   *                                   fully mounted previously
   */
  private static boolean isFullyMounted(
      Entry<Path, Path> directory,
      MountMap mounts,
      Set<Entry<Path, Path>> fullyMountedDirectories,
      Set<Entry<Path, Path>> notFullyMountedDirectories)
      throws IOException {
    if (fullyMountedDirectories.contains(directory)) {
      return true;
    } else if (notFullyMountedDirectories.contains(directory)) {
      return false;
    } else {
      boolean result = true;
      for (Dirent entry : directory.getValue().readdir(Symlinks.NOFOLLOW)) {
        Path entryKey = directory.getKey().getChild(entry.getName());
        Path entryValue = directory.getValue().getChild(entry.getName());
        if (entry.getType() == Dirent.Type.DIRECTORY) {
          if (!isFullyMounted(
              new SimpleImmutableEntry<Path, Path>(entryKey, entryValue),
              mounts,
              fullyMountedDirectories,
              notFullyMountedDirectories)) {
            result = false;
            break;
          }
        } else {
          Path mountsValue = mounts.get(entryKey);
          if (mountsValue == null || !mountsValue.equals(entryValue)) {
            result = false;
            break;
          }
        }
      }

      if (result) {
        fullyMountedDirectories.add(directory);
      } else {
        notFullyMountedDirectories.add(directory);
      }
      return result;
    }
  }

  /**
   * Performs various checks on each mounted file which require stating each one.
   * Contained in one function to allow minimizing the number of syscalls involved.
   *
   * Checks for each mount if the source refers to a symbolic link and if yes, adds another mount
   * for the target of that symlink to ensure that it keeps working inside the sandbox.
   *
   * Checks for each mount if the source refers to a directory and if yes, replaces that mount with
   * mounts of all files inside that directory.
   *
   * Validates all mounts against a set of criteria and throws an exception on error.
   *
   * @return a new mounts multimap with all mounts and the added mounts.
   */
  @VisibleForTesting
  static MountMap finalizeMounts(Map<Path, Path> mounts) throws IOException {
    Set<Entry<Path, Path>> fullyMountedDirectories = new HashSet<>();
    MountMap finalizedMounts = new MountMap();
    for (Entry<Path, Path> mount : mounts.entrySet()) {
      Path target = mount.getKey();
      Path source = mount.getValue();

      FileStatus stat = source.statNullable(Symlinks.NOFOLLOW);

      if (stat != null && stat.isDirectory()) {
        fullyMountedDirectories.add(new SimpleImmutableEntry<Path, Path>(target, source));
        for (Path subSource : FileSystemUtils.traverseTree(source, Predicates.alwaysTrue())) {
          Path subTarget = target.getRelative(subSource.relativeTo(source));
          FileStatus subStat = subSource.statNullable(Symlinks.NOFOLLOW);
          if (subStat.isDirectory()) {
            fullyMountedDirectories.add(new SimpleImmutableEntry<Path, Path>(subTarget, subSource));
          }
          finalizeMountPath(finalizedMounts, subTarget, subSource, subStat);
        }
      } else {
        finalizeMountPath(finalizedMounts, target, source, stat);
      }
    }

    MountMap deduplicatedMounts = new MountMap();
    Set<Entry<Path, Path>> notFullyMountedDirectories = new HashSet<>();
    for (Entry<Path, Path> mount : finalizedMounts.entrySet()) {
      Entry<Path, Path> parent =
          new SimpleImmutableEntry<>(
              mount.getKey().getParentDirectory(), mount.getValue().getParentDirectory());
      if (!parent.getKey().equals(parent.getValue())
          || !isFullyMounted(
              parent, finalizedMounts, fullyMountedDirectories, notFullyMountedDirectories)) {
        deduplicatedMounts.put(mount.getKey(), mount.getValue());
      }
    }

    for (Entry<Path, Path> mount : fullyMountedDirectories) {
      deduplicatedMounts.put(mount.getKey(), mount.getValue());
    }
    return deduplicatedMounts;
  }

  /**
   * Mount a certain set of unix directories to make the usual tools and libraries available to the
   * spawn that runs.
   *
   * Throws an exception if any of them do not exist.
   */
  private MountMap mountUsualUnixDirs() throws IOException {
    MountMap mounts = new MountMap();
    FileSystem fs = blazeDirs.getFileSystem();
    mounts.put(fs.getPath("/bin"), fs.getPath("/bin"));
    mounts.put(fs.getPath("/sbin"), fs.getPath("/sbin"));
    mounts.put(fs.getPath("/etc"), fs.getPath("/etc"));

    // Check if /etc/resolv.conf is a symlink and mount its target
    // Fix #738
    Path resolv = fs.getPath("/etc/resolv.conf");
    if (resolv.exists() && resolv.isSymbolicLink()) {
      mounts.put(resolv.resolveSymbolicLinks(), resolv.resolveSymbolicLinks());
    }

    for (String entry : NativePosixFiles.readdir("/")) {
      if (entry.startsWith("lib")) {
        Path libDir = fs.getRootDirectory().getRelative(entry);
        mounts.put(libDir, libDir);
      }
    }
    for (String entry : NativePosixFiles.readdir("/usr")) {
      if (!entry.equals("local")) {
        Path usrDir = fs.getPath("/usr").getRelative(entry);
        mounts.put(usrDir, usrDir);
      }
    }
    for (Path path : mounts.values()) {
      Preconditions.checkArgument(path.exists(), "%s does not exist", path.toString());
    }
    return mounts;
  }

  /**
   * Mount the embedded tools.
   */
  private MountMap setupBlazeUtils() {
    MountMap mounts = new MountMap();
    Path mount = blazeDirs.getEmbeddedBinariesRoot().getRelative("build-runfiles");
    mounts.put(mount, mount);
    return mounts;
  }

  /**
   * Mount all runfiles that the spawn needs as specified in its runfiles manifests.
   */
  private MountMap mountRunfilesFromManifests(Spawn spawn) throws IOException, ExecException {
    MountMap mounts = new MountMap();
    for (Entry<PathFragment, Artifact> manifest : spawn.getRunfilesManifests().entrySet()) {
      String manifestFilePath = manifest.getValue().getPath().getPathString();
      Preconditions.checkState(!manifest.getKey().isAbsolute());
      Path targetDirectory = execRoot.getRelative(manifest.getKey());

      mounts.putAll(parseManifestFile(targetDirectory, new File(manifestFilePath), false, ""));
    }
    return mounts;
  }

  /**
   * Mount all files that the spawn needs as specified in its fileset manifests.
   */
  private MountMap mountFilesFromFilesetManifests(
      Spawn spawn, ActionExecutionContext executionContext) throws IOException, ExecException {
    final FilesetActionContext filesetContext =
        executionContext.getExecutor().getContext(FilesetActionContext.class);
    MountMap mounts = new MountMap();
    for (Artifact fileset : spawn.getFilesetManifests()) {
      Path manifest =
          execRoot.getRelative(AnalysisUtils.getManifestPathFromFilesetPath(fileset.getExecPath()));
      Path targetDirectory = execRoot.getRelative(fileset.getExecPathString());

      mounts.putAll(
          parseManifestFile(
              targetDirectory, manifest.getPathFile(), true, filesetContext.getWorkspaceName()));
    }
    return mounts;
  }

  static MountMap parseManifestFile(
      Path targetDirectory, File manifestFile, boolean isFilesetManifest, String workspaceName)
      throws IOException, ExecException {
    MountMap mounts = new MountMap();
    int lineNum = 0;
    for (String line : Files.readLines(manifestFile, StandardCharsets.UTF_8)) {
      if (isFilesetManifest && (++lineNum % 2 == 0)) {
        continue;
      }
      if (line.isEmpty()) {
        continue;
      }

      String[] fields = line.trim().split(" ");

      Path targetPath;
      if (isFilesetManifest) {
        PathFragment targetPathFragment = new PathFragment(fields[0]);
        if (!workspaceName.isEmpty()) {
          if (!targetPathFragment.getSegment(0).equals(workspaceName)) {
            throw new EnvironmentalExecException(
                "Fileset manifest line must start with workspace name");
          }
          targetPathFragment = targetPathFragment.subFragment(1, targetPathFragment.segmentCount());
        }
        targetPath = targetDirectory.getRelative(targetPathFragment);
      } else {
        targetPath = targetDirectory.getRelative(fields[0]);
      }

      Path source;
      switch (fields.length) {
        case 1:
          source = targetDirectory.getFileSystem().getPath("/dev/null");
          break;
        case 2:
          source = targetDirectory.getFileSystem().getPath(fields[1]);
          break;
        default:
          throw new IllegalStateException("'" + line + "' splits into more than 2 parts");
      }

      mounts.put(targetPath, source);
    }
    return mounts;
  }

  /**
   * Mount all runfiles that the spawn needs as specified via its runfiles suppliers.
   */
  private MountMap mountRunfilesFromSuppliers(Spawn spawn) throws IOException {
    MountMap mounts = new MountMap();
    FileSystem fs = blazeDirs.getFileSystem();
    Map<PathFragment, Map<PathFragment, Artifact>> rootsAndMappings =
        spawn.getRunfilesSupplier().getMappings();
    for (Entry<PathFragment, Map<PathFragment, Artifact>> rootAndMappings :
        rootsAndMappings.entrySet()) {
      Path root = fs.getRootDirectory().getRelative(rootAndMappings.getKey());
      for (Entry<PathFragment, Artifact> mapping : rootAndMappings.getValue().entrySet()) {
        Artifact sourceArtifact = mapping.getValue();
        Path source = (sourceArtifact != null) ? sourceArtifact.getPath() : fs.getPath("/dev/null");

        Preconditions.checkArgument(!mapping.getKey().isAbsolute());
        Path target = root.getRelative(mapping.getKey());
        mounts.put(target, source);
      }
    }
    return mounts;
  }

  /**
   * Mount all inputs of the spawn.
   */
  private MountMap mountInputs(Spawn spawn, ActionExecutionContext actionExecutionContext) {
    MountMap mounts = new MountMap();

    List<ActionInput> inputs =
        ActionInputHelper.expandArtifacts(
            spawn.getInputFiles(), actionExecutionContext.getArtifactExpander());

    if (spawn.getResourceOwner() instanceof CppCompileAction) {
      CppCompileAction action = (CppCompileAction) spawn.getResourceOwner();
      if (action.shouldScanIncludes()) {
        inputs.addAll(action.getAdditionalInputs());
      }
    }

    for (ActionInput input : inputs) {
      if (input.getExecPathString().contains("internal/_middlemen/")) {
        continue;
      }
      Path mount = execRoot.getRelative(input.getExecPathString());
      mounts.put(mount, mount);
    }
    return mounts;
  }

  /**
   * If a --run_under= option is set and refers to a command via its path (as opposed to via its
   * label), we have to mount this. Note that this is best effort and works fine for shell scripts
   * and small binaries, but we can't track any further dependencies of this command.
   *
   * <p>If --run_under= refers to a label, it is automatically provided in the spawn's input files,
   * so mountInputs() will catch that case.
   */
  private MountMap mountRunUnderCommand(Spawn spawn) {
    MountMap mounts = new MountMap();

    if (spawn.getResourceOwner() instanceof TestRunnerAction) {
      TestRunnerAction testRunnerAction = ((TestRunnerAction) spawn.getResourceOwner());
      RunUnder runUnder = testRunnerAction.getExecutionSettings().getRunUnder();
      if (runUnder != null && runUnder.getCommand() != null) {
        PathFragment sourceFragment = new PathFragment(runUnder.getCommand());
        Path mount;
        if (sourceFragment.isAbsolute()) {
          mount = blazeDirs.getFileSystem().getPath(sourceFragment);
        } else if (blazeDirs.getExecRoot().getRelative(sourceFragment).exists()) {
          mount = blazeDirs.getExecRoot().getRelative(sourceFragment);
        } else {
          List<Path> searchPath =
              SearchPath.parse(blazeDirs.getFileSystem(), clientEnv.get("PATH"));
          mount = SearchPath.which(searchPath, runUnder.getCommand());
        }
        if (mount != null) {
          mounts.put(mount, mount);
        }
      }
    }
    return mounts;
  }

  /**
   * Mount all user defined path in --sandbox_add_path.
   */
  private MountMap mountUserDefinedPath() throws IOException {
    MountMap mounts = new MountMap();
    FileSystem fs = blazeDirs.getFileSystem();

    ImmutableList<Path> exclude =
        ImmutableList.of(blazeDirs.getWorkspace(), blazeDirs.getOutputBase());

    for (String pathStr : sandboxAddPath) {
      Path path = fs.getPath(pathStr);

      // Check if path is in {workspace, outputBase}
      for (Path exc : exclude) {
        if (path.startsWith(exc)) {
          throw new IllegalArgumentException(
              "Mounting subdirectory of WORKSPACE or OUTPUTBASE to sandbox is not allowed.");
        }
      }

      // Check if path is ancestor of {workspace, outputBase}
      // Mount subdirectory of path except {workspace, outputBase}
      mounts.putAll(mountChildDirExclude(path, exclude));
    }

    return mounts;
  }

  /**
   * Mount all subdirectories recursively except some paths
   */
  private MountMap mountDirExclude(Path path, List<Path> exclude) throws IOException {
    MountMap mounts = new MountMap();

    if (!path.isDirectory(Symlinks.NOFOLLOW)) {
      if (!exclude.contains(path)) {
        mounts.put(path, path);
      }
      return mounts;
    }

    try {
      for (Path child : path.getDirectoryEntries()) {
        // Ignore broken symlink
        if (!child.exists()) {
          continue;
        }

        mounts.putAll(mountChildDirExclude(child, exclude));
      }
    } catch (IOException e) {
      throw new IOException("Illegal additional path for mount", e);
    }

    return mounts;
  }

  /**
   * Helper function of mountDirExclude and mountUserDefinedPath
   */
  private MountMap mountChildDirExclude(Path child, List<Path> exclude) throws IOException {
    MountMap mounts = new MountMap();

    boolean startsWithFlag = false;
    for (Path exc : exclude) {
      if (exc.startsWith(child)) {
        startsWithFlag = true;
        break;
      }
    }
    if (!startsWithFlag) {
      mounts.put(child, child);
    } else if (!exclude.contains(child)) {
      mounts.putAll(mountDirExclude(child, exclude));
    }

    return mounts;
  }

  @Override
  public boolean willExecuteRemotely(boolean remotable) {
    return false;
  }

  @Override
  public String toString() {
    return "sandboxed";
  }
}