File: DepsBuildEngineTest.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (328 lines) | stat: -rw-r--r-- 11,147 bytes parent folder | download
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
//===- unittests/Core/DepsBuildEngineTest.cpp -----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "llbuild/Core/BuildEngine.h"

#include "llbuild/Basic/ExecutionQueue.h"
#include "llbuild/Basic/LLVM.h"
#include "llbuild/Core/BuildDB.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/FileSystem.h"

#include "gtest/gtest.h"

#include <unordered_map>
#include <vector>
#include <thread>

using namespace llbuild;
using namespace llbuild::core;

namespace {

class SimpleBuildEngineDelegate : public core::BuildEngineDelegate, public basic::ExecutionQueueDelegate {
  virtual std::unique_ptr<core::Rule> lookupRule(const core::KeyType& key) override {
    // We never expect dynamic rule lookup.
    fprintf(stderr, "error: unexpected rule lookup for \"%s\"\n",
            key.c_str());
    abort();
    return nullptr;
  }

  virtual void cycleDetected(const std::vector<core::Rule*>& items) override {
    // We never expect a cycle.
    fprintf(stderr, "error: cycle\n");
    abort();
  }

  virtual void error(const Twine& message) override {
    fprintf(stderr, "error: %s\n", message.str().c_str());
    abort();
  }

  void processStarted(basic::ProcessContext*, basic::ProcessHandle, llbuild_pid_t) override { }
  void processHadError(basic::ProcessContext*, basic::ProcessHandle, const Twine&) override { }
  void processHadOutput(basic::ProcessContext*, basic::ProcessHandle, StringRef) override { }
  void processFinished(basic::ProcessContext*, basic::ProcessHandle, const basic::ProcessResult&) override { }
  void queueJobStarted(basic::JobDescriptor*) override { }
  void queueJobFinished(basic::JobDescriptor*) override { }

  std::unique_ptr<basic::ExecutionQueue> createExecutionQueue() override {
    return createSerialQueue(*this, nullptr);
  }
};

static int32_t intFromValue(const core::ValueType& value) {
  assert(value.size() == 4);
  return ((value[0] << 0) |
          (value[1] << 8) |
          (value[2] << 16) |
          (value[3] << 24));
}
static core::ValueType intToValue(int32_t value) {
  std::vector<uint8_t> result(4);
  result[0] = (value >> 0) & 0xFF;
  result[1] = (value >> 8) & 0xFF;
  result[2] = (value >> 16) & 0xFF;
  result[3] = (value >> 24) & 0xFF;
  return result;
}

// Simple task implementation which takes a fixed set of dependencies, evaluates
// them all, and then provides the output.
class SimpleTask : public Task {
public:
  typedef std::function<int(const std::vector<int>&)> ComputeFnType;

private:
  std::vector<KeyType> inputs;
  std::vector<int> inputValues;
  ComputeFnType compute;

public:
  SimpleTask(const std::vector<KeyType>& inputs, ComputeFnType compute)
    : inputs(inputs), compute(compute)
  {
    inputValues.resize(inputs.size());
  }

  virtual void start(TaskInterface ti) override {
    // Request all of the inputs.
    for (int i = 0, e = inputs.size(); i != e; ++i) {
      ti.request(inputs[i], i);
    }
  }

  virtual void provideValue(TaskInterface, uintptr_t inputID,
                            const ValueType& value) override {
    // Update the input values.
    assert(inputID < inputValues.size());
    inputValues[inputID] = intFromValue(value);
  }

  virtual void inputsAvailable(TaskInterface ti) override {
    ti.complete(intToValue(compute(inputValues)));
  }
};

// Helper function for creating a simple action.
typedef std::function<Task*(BuildEngine&)> ActionFn;

class SimpleRule: public Rule {
public:
    typedef std::function<bool(const ValueType& value)> ValidFnType;

private:
    SimpleTask::ComputeFnType compute;
    std::vector<KeyType> inputs;
    ValidFnType valid;
public:
    SimpleRule(const KeyType& key, const std::vector<KeyType>& inputs,
               SimpleTask::ComputeFnType compute, ValidFnType valid = nullptr)
        : Rule(key), compute(compute), inputs(inputs), valid(valid) { }

    Task* createTask(BuildEngine&) override { return new SimpleTask(inputs, compute); }

    bool isResultValid(BuildEngine&, const ValueType& value) override {
        if (!valid) return true;
        return valid(value);
    }
};

// Test for a tricky case involving concurrent dependency scanning.
//
// The problem that this test is checking for is that we don't immediately start
// running rules we have *scanned* as part of an input dependency, before they
// have actually been requested. For example, if a rule requests something like
// the contents of a directory, then requests something based on each file in
// the directory, we don't want to possibly run a rule for a file which was
// previously present (and thus recorded as an input dependency) but which is no
// longer present.
TEST(DepsBuildEngineTest, BogusConcurrentDepScan) {
  std::vector<KeyType> builtKeys;
  SimpleBuildEngineDelegate delegate;
  core::BuildEngine engine(delegate);
  
  // This models a rule which retrieves some dynamic content (like a directory
  // list).
  //
  // We need to model a separate input to trigger the continued scanning
  // behavior (so that when "output" is considering its "dir-list" input, it
  // isn't immediately obvious it needs to run).
  int dirListValue = 2 * 3;
  engine.addRule(std::unique_ptr<core::Rule>(new SimpleRule(
      "dir-list-input", {}, [&] (const std::vector<int>& inputs) {
          builtKeys.push_back("dir-list-input");
          return dirListValue; },
      [&](const ValueType&) {
        // Always rebuild
        return false;
      } )));
  engine.addRule(std::unique_ptr<core::Rule>(new SimpleRule(
      "dir-list", { "dir-list-input" }, [&] (const std::vector<int>& inputs) {
          builtKeys.push_back("dir-list");
          assert(inputs.size() == 1);
          return inputs[0]; })));

  // These are the rules for individual discovered "files".
  engine.addRule(std::unique_ptr<core::Rule>(new SimpleRule(
      "input-2", {}, [&] (const std::vector<int>& inputs) {
          builtKeys.push_back("input-2");
          return 5; },
      [&](const ValueType&) {
        // Always rebuild
        return false;
      } )));
  engine.addRule(std::unique_ptr<core::Rule>(new SimpleRule(
      "input-3", {}, [&] (const std::vector<int>& inputs) {
          builtKeys.push_back("input-3");
          return 7; },
      [&](const ValueType&) {
        // Always rebuild
        return false;
      } )));

  // This models a rule which uses the dynamic content to drive some other
  // action (compiling files).
  class DynamicTask : public Task {
    int result = 1;

  public:
    virtual void start(TaskInterface ti) override {
      // Request the known input.
      ti.request("dir-list", 0);
    }

    virtual void provideValue(TaskInterface ti, uintptr_t inputID,
                              const ValueType& value) override {
      int N = intFromValue(value);
      result *= N;

      // If this is the initial input, use it to derive
      // the subsequent inputs.
      if (inputID == 0) {
        if (N == 2) {
          ti.request("input-2", 1);
        } else if (N == 3) {
          ti.request("input-3", 1);
        } else {
          assert(N == 2 * 3);
          ti.request("input-2", 1);
          ti.request("input-3", 1);
        }
      }
    }

    virtual void inputsAvailable(TaskInterface ti) override {
      ti.complete(intToValue(result));
    }
  };

  class DynamicRule: public Rule {
    std::vector<KeyType>& builtKeys;
  public:
    DynamicRule(const KeyType& key, std::vector<KeyType>& builtKeys)
      : Rule(key), builtKeys(builtKeys) { }
    Task* createTask(BuildEngine&) override {
      builtKeys.push_back(key);
      return new DynamicTask();
    }
    bool isResultValid(BuildEngine&, const ValueType&) override { return true; }
  };
  engine.addRule(std::unique_ptr<core::Rule>(new DynamicRule("output", builtKeys)));

  // Build the first result.
  EXPECT_EQ(2 * 3 * 5 * 7, intFromValue(engine.build("output")));
  EXPECT_EQ(5U, builtKeys.size());
  EXPECT_EQ(KeyType("output"), builtKeys[0]);
  EXPECT_EQ(KeyType("dir-list-input"), builtKeys[1]);
  EXPECT_EQ(KeyType("dir-list"), builtKeys[2]);
  EXPECT_EQ(KeyType("input-2"), builtKeys[3]);
  EXPECT_EQ(KeyType("input-3"), builtKeys[4]);

  // Now change the dynamic contents and rebuild.
  builtKeys.clear();
  // Suppress a static analyzer false positive (rdar://problem/22165179).
#ifndef __clang_analyzer__
  dirListValue = 3;
#endif
  EXPECT_EQ(3 * 7, intFromValue(engine.build("output")));
  EXPECT_EQ(4U, builtKeys.size());
  EXPECT_EQ(KeyType("dir-list-input"), builtKeys[0]);
  EXPECT_EQ(KeyType("dir-list"), builtKeys[1]);
  EXPECT_EQ(KeyType("output"), builtKeys[2]);
  EXPECT_EQ(KeyType("input-3"), builtKeys[3]);
}

TEST(DepsBuildEngineTest, KeysWithNull) {
  // Check build engine support for keys with embedded null characters.
  std::vector<std::string> builtKeys;
  SimpleBuildEngineDelegate delegate;

  // Create a temporary file.
  llvm::SmallString<256> dbPath;
  auto ec = llvm::sys::fs::createTemporaryFile("build", "db", dbPath);
  EXPECT_EQ(bool(ec), false);

  fprintf(stderr, "using db: %s\n", dbPath.c_str());
  for (int iteration = 0; iteration < 2; ++iteration) {
    fprintf(stderr, "iteration: %d\n", iteration);
    
    core::BuildEngine engine(delegate);

    // Attach the database.
    {
      std::string error;
      auto db = createSQLiteBuildDB(dbPath, 1, /* recreateUnmatchedVersion = */ true, &error);
      EXPECT_EQ(bool(db), true);
      if (!db) {
        fprintf(stderr, "unable to open database: %s\n", error.c_str());
        return;
      }
      engine.attachDB(std::move(db), &error);
    }

    std::string inputA{"i\0A", 3};
    std::string inputB{"i\0B", 3};
    engine.addRule(std::unique_ptr<core::Rule>(new SimpleRule(
        inputA, {}, [&] (const std::vector<int>& inputs) {
            builtKeys.push_back(inputA);
            return 2; })));
    engine.addRule(std::unique_ptr<core::Rule>(new SimpleRule(
        inputB, {}, [&] (const std::vector<int>& inputs) {
            builtKeys.push_back(inputB);
            return 3; })));
    engine.addRule(std::unique_ptr<core::Rule>(new SimpleRule(
        "output", { inputA, inputB }, [&] (const std::vector<int>& inputs) {
            assert(inputs.size() == 2);
            builtKeys.push_back("output");
            return inputs[0] * inputs[1]; })));

    // Run the build.
    builtKeys.clear();
    EXPECT_EQ(2 * 3, intFromValue(engine.build("output")));
    if (iteration == 0) {
      EXPECT_EQ(3U, builtKeys.size());
      EXPECT_EQ(inputA, builtKeys[0]);
      EXPECT_EQ(inputB, builtKeys[1]);
      EXPECT_EQ("output", builtKeys[2]);
    } else {
      EXPECT_EQ(0U, builtKeys.size());
    }
  }

  ec = llvm::sys::fs::remove(dbPath.str());
  EXPECT_EQ(bool(ec), false);
}

}