Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Tooling/JSONCompilationDatabase.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- JSONCompilationDatabase.cpp ----------------------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file contains the implementation of the JSONCompilationDatabase.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Tooling/JSONCompilationDatabase.h"
14
#include "clang/Basic/LLVM.h"
15
#include "clang/Tooling/CompilationDatabase.h"
16
#include "clang/Tooling/CompilationDatabasePluginRegistry.h"
17
#include "clang/Tooling/Tooling.h"
18
#include "llvm/ADT/Optional.h"
19
#include "llvm/ADT/STLExtras.h"
20
#include "llvm/ADT/SmallString.h"
21
#include "llvm/ADT/SmallVector.h"
22
#include "llvm/ADT/StringRef.h"
23
#include "llvm/ADT/Triple.h"
24
#include "llvm/Support/Allocator.h"
25
#include "llvm/Support/Casting.h"
26
#include "llvm/Support/CommandLine.h"
27
#include "llvm/Support/ErrorOr.h"
28
#include "llvm/Support/Host.h"
29
#include "llvm/Support/MemoryBuffer.h"
30
#include "llvm/Support/Path.h"
31
#include "llvm/Support/StringSaver.h"
32
#include "llvm/Support/VirtualFileSystem.h"
33
#include "llvm/Support/YAMLParser.h"
34
#include "llvm/Support/raw_ostream.h"
35
#include <cassert>
36
#include <memory>
37
#include <string>
38
#include <system_error>
39
#include <tuple>
40
#include <utility>
41
#include <vector>
42
43
using namespace clang;
44
using namespace tooling;
45
46
namespace {
47
48
/// A parser for escaped strings of command line arguments.
49
///
50
/// Assumes \-escaping for quoted arguments (see the documentation of
51
/// unescapeCommandLine(...)).
52
class CommandLineArgumentParser {
53
 public:
54
  CommandLineArgumentParser(StringRef CommandLine)
55
206
      : Input(CommandLine), Position(Input.begin()-1) {}
56
57
206
  std::vector<std::string> parse() {
58
206
    bool HasMoreInput = true;
59
1.66k
    while (HasMoreInput && 
nextNonWhitespace()1.45k
) {
60
1.45k
      std::string Argument;
61
1.45k
      HasMoreInput = parseStringInto(Argument);
62
1.45k
      CommandLine.push_back(Argument);
63
1.45k
    }
64
206
    return CommandLine;
65
206
  }
66
67
 private:
68
  // All private methods return true if there is more input available.
69
70
1.45k
  bool parseStringInto(std::string &String) {
71
1.46k
    do {
72
1.46k
      if (*Position == '"') {
73
18
        if (!parseDoubleQuotedStringInto(String)) 
return false8
;
74
1.44k
      } else if (*Position == '\'') {
75
1
        if (!parseSingleQuotedStringInto(String)) return false;
76
1.44k
      } else {
77
1.44k
        if (!parseFreeStringInto(String)) 
return false194
;
78
1.44k
      }
79
1.46k
    } while (
*Position != ' '1.25k
);
80
1.25k
    return true;
81
1.45k
  }
82
83
18
  bool parseDoubleQuotedStringInto(std::string &String) {
84
18
    if (!next()) 
return false1
;
85
88
    
while (17
*Position != '"') {
86
72
      if (!skipEscapeCharacter()) 
return false0
;
87
72
      String.push_back(*Position);
88
72
      if (!next()) 
return false1
;
89
72
    }
90
16
    return next();
91
17
  }
92
93
1
  bool parseSingleQuotedStringInto(std::string &String) {
94
1
    if (!next()) 
return false0
;
95
7
    
while (1
*Position != '\'') {
96
6
      String.push_back(*Position);
97
6
      if (!next()) 
return false0
;
98
6
    }
99
1
    return next();
100
1
  }
101
102
1.44k
  bool parseFreeStringInto(std::string &String) {
103
48.9k
    do {
104
48.9k
      if (!skipEscapeCharacter()) 
return false0
;
105
48.9k
      String.push_back(*Position);
106
48.9k
      if (!next()) 
return false194
;
107
48.9k
    } while (
*Position != ' '48.7k
&&
*Position != '"'47.4k
&&
*Position != '\''47.4k
);
108
1.24k
    return true;
109
1.44k
  }
110
111
49.0k
  bool skipEscapeCharacter() {
112
49.0k
    if (*Position == '\\') {
113
7
      return next();
114
7
    }
115
48.9k
    return true;
116
49.0k
  }
117
118
1.45k
  bool nextNonWhitespace() {
119
1.47k
    do {
120
1.47k
      if (!next()) 
return false3
;
121
1.47k
    } while (
*Position == ' '1.47k
);
122
1.45k
    return true;
123
1.45k
  }
124
125
50.5k
  bool next() {
126
50.5k
    ++Position;
127
50.5k
    return Position != Input.end();
128
50.5k
  }
129
130
  const StringRef Input;
131
  StringRef::iterator Position;
132
  std::vector<std::string> CommandLine;
133
};
134
135
std::vector<std::string> unescapeCommandLine(JSONCommandLineSyntax Syntax,
136
206
                                             StringRef EscapedCommandLine) {
137
206
  if (Syntax == JSONCommandLineSyntax::AutoDetect) {
138
173
    Syntax = JSONCommandLineSyntax::Gnu;
139
173
    llvm::Triple Triple(llvm::sys::getProcessTriple());
140
173
    if (Triple.getOS() == llvm::Triple::OSType::Win32) {
141
      // Assume Windows command line parsing on Win32 unless the triple
142
      // explicitly tells us otherwise.
143
0
      if (!Triple.hasEnvironment() ||
144
0
          Triple.getEnvironment() == llvm::Triple::EnvironmentType::MSVC)
145
0
        Syntax = JSONCommandLineSyntax::Windows;
146
0
    }
147
173
  }
148
149
206
  if (Syntax == JSONCommandLineSyntax::Windows) {
150
0
    llvm::BumpPtrAllocator Alloc;
151
0
    llvm::StringSaver Saver(Alloc);
152
0
    llvm::SmallVector<const char *, 64> T;
153
0
    llvm::cl::TokenizeWindowsCommandLine(EscapedCommandLine, Saver, T);
154
0
    std::vector<std::string> Result(T.begin(), T.end());
155
0
    return Result;
156
0
  }
157
206
  assert(Syntax == JSONCommandLineSyntax::Gnu);
158
0
  CommandLineArgumentParser parser(EscapedCommandLine);
159
206
  return parser.parse();
160
206
}
161
162
// This plugin locates a nearby compile_command.json file, and also infers
163
// compile commands for files not present in the database.
164
class JSONCompilationDatabasePlugin : public CompilationDatabasePlugin {
165
  std::unique_ptr<CompilationDatabase>
166
60
  loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override {
167
60
    SmallString<1024> JSONDatabasePath(Directory);
168
60
    llvm::sys::path::append(JSONDatabasePath, "compile_commands.json");
169
60
    auto Base = JSONCompilationDatabase::loadFromFile(
170
60
        JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect);
171
60
    return Base ? inferTargetAndDriverMode(
172
19
                      inferMissingCompileCommands(expandResponseFiles(
173
19
                          std::move(Base), llvm::vfs::getRealFileSystem())))
174
60
                : 
nullptr41
;
175
60
  }
176
};
177
178
} // namespace
179
180
// Register the JSONCompilationDatabasePlugin with the
181
// CompilationDatabasePluginRegistry using this statically initialized variable.
182
static CompilationDatabasePluginRegistry::Add<JSONCompilationDatabasePlugin>
183
X("json-compilation-database", "Reads JSON formatted compilation databases");
184
185
namespace clang {
186
namespace tooling {
187
188
// This anchor is used to force the linker to link in the generated object file
189
// and thus register the JSONCompilationDatabasePlugin.
190
volatile int JSONAnchorSource = 0;
191
192
} // namespace tooling
193
} // namespace clang
194
195
std::unique_ptr<JSONCompilationDatabase>
196
JSONCompilationDatabase::loadFromFile(StringRef FilePath,
197
                                      std::string &ErrorMessage,
198
114
                                      JSONCommandLineSyntax Syntax) {
199
  // Don't mmap: if we're a long-lived process, the build system may overwrite.
200
114
  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> DatabaseBuffer =
201
114
      llvm::MemoryBuffer::getFile(FilePath, /*IsText=*/false,
202
114
                                  /*RequiresNullTerminator=*/true,
203
114
                                  /*IsVolatile=*/true);
204
114
  if (std::error_code Result = DatabaseBuffer.getError()) {
205
41
    ErrorMessage = "Error while opening JSON database: " + Result.message();
206
41
    return nullptr;
207
41
  }
208
73
  std::unique_ptr<JSONCompilationDatabase> Database(
209
73
      new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
210
73
  if (!Database->parse(ErrorMessage))
211
0
    return nullptr;
212
73
  return Database;
213
73
}
214
215
std::unique_ptr<JSONCompilationDatabase>
216
JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString,
217
                                        std::string &ErrorMessage,
218
52
                                        JSONCommandLineSyntax Syntax) {
219
52
  std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer(
220
52
      llvm::MemoryBuffer::getMemBufferCopy(DatabaseString));
221
52
  std::unique_ptr<JSONCompilationDatabase> Database(
222
52
      new JSONCompilationDatabase(std::move(DatabaseBuffer), Syntax));
223
52
  if (!Database->parse(ErrorMessage))
224
17
    return nullptr;
225
35
  return Database;
226
52
}
227
228
std::vector<CompileCommand>
229
46
JSONCompilationDatabase::getCompileCommands(StringRef FilePath) const {
230
46
  SmallString<128> NativeFilePath;
231
46
  llvm::sys::path::native(FilePath, NativeFilePath);
232
233
46
  std::string Error;
234
46
  llvm::raw_string_ostream ES(Error);
235
46
  StringRef Match = MatchTrie.findEquivalent(NativeFilePath, ES);
236
46
  if (Match.empty())
237
2
    return {};
238
44
  const auto CommandsRefI = IndexByFile.find(Match);
239
44
  if (CommandsRefI == IndexByFile.end())
240
0
    return {};
241
44
  std::vector<CompileCommand> Commands;
242
44
  getCommands(CommandsRefI->getValue(), Commands);
243
44
  return Commands;
244
44
}
245
246
std::vector<std::string>
247
21
JSONCompilationDatabase::getAllFiles() const {
248
21
  std::vector<std::string> Result;
249
21
  for (const auto &CommandRef : IndexByFile)
250
15.4k
    Result.push_back(CommandRef.first().str());
251
21
  return Result;
252
21
}
253
254
std::vector<CompileCommand>
255
58
JSONCompilationDatabase::getAllCompileCommands() const {
256
58
  std::vector<CompileCommand> Commands;
257
58
  getCommands(AllCommands, Commands);
258
58
  return Commands;
259
58
}
260
261
206
static llvm::StringRef stripExecutableExtension(llvm::StringRef Name) {
262
206
  Name.consume_back(".exe");
263
206
  return Name;
264
206
}
265
266
// There are compiler-wrappers (ccache, distcc, gomacc) that take the "real"
267
// compiler as an argument, e.g. distcc gcc -O3 foo.c.
268
// These end up in compile_commands.json when people set CC="distcc gcc".
269
// Clang's driver doesn't understand this, so we need to unwrap.
270
214
static bool unwrapCommand(std::vector<std::string> &Args) {
271
214
  if (Args.size() < 2)
272
17
    return false;
273
197
  StringRef Wrapper =
274
197
      stripExecutableExtension(llvm::sys::path::filename(Args.front()));
275
197
  if (Wrapper == "distcc" || 
Wrapper == "gomacc"193
||
Wrapper == "ccache"192
||
276
197
      
Wrapper == "sccache"188
) {
277
    // Most of these wrappers support being invoked 3 ways:
278
    // `distcc g++ file.c` This is the mode we're trying to match.
279
    //                     We need to drop `distcc`.
280
    // `distcc file.c`     This acts like compiler is cc or similar.
281
    //                     Clang's driver can handle this, no change needed.
282
    // `g++ file.c`        g++ is a symlink to distcc.
283
    //                     We don't even notice this case, and all is well.
284
    //
285
    // We need to distinguish between the first and second case.
286
    // The wrappers themselves don't take flags, so Args[1] is a compiler flag,
287
    // an input file, or a compiler. Inputs have extensions, compilers don't.
288
10
    bool HasCompiler =
289
10
        (Args[1][0] != '-') &&
290
10
        
!llvm::sys::path::has_extension(stripExecutableExtension(Args[1]))9
;
291
10
    if (HasCompiler) {
292
8
      Args.erase(Args.begin());
293
8
      return true;
294
8
    }
295
    // If !HasCompiler, wrappers act like GCC. Fine: so do we.
296
10
  }
297
189
  return false;
298
197
}
299
300
static std::vector<std::string>
301
nodeToCommandLine(JSONCommandLineSyntax Syntax,
302
206
                  const std::vector<llvm::yaml::ScalarNode *> &Nodes) {
303
206
  SmallString<1024> Storage;
304
206
  std::vector<std::string> Arguments;
305
206
  if (Nodes.size() == 1)
306
206
    Arguments = unescapeCommandLine(Syntax, Nodes[0]->getValue(Storage));
307
0
  else
308
0
    for (const auto *Node : Nodes)
309
0
      Arguments.push_back(std::string(Node->getValue(Storage)));
310
  // There may be multiple wrappers: using distcc and ccache together is common.
311
214
  while (unwrapCommand(Arguments))
312
8
    ;
313
206
  return Arguments;
314
206
}
315
316
void JSONCompilationDatabase::getCommands(
317
    ArrayRef<CompileCommandRef> CommandsRef,
318
102
    std::vector<CompileCommand> &Commands) const {
319
206
  for (const auto &CommandRef : CommandsRef) {
320
206
    SmallString<8> DirectoryStorage;
321
206
    SmallString<32> FilenameStorage;
322
206
    SmallString<32> OutputStorage;
323
206
    auto Output = std::get<3>(CommandRef);
324
206
    Commands.emplace_back(
325
206
        std::get<0>(CommandRef)->getValue(DirectoryStorage),
326
206
        std::get<1>(CommandRef)->getValue(FilenameStorage),
327
206
        nodeToCommandLine(Syntax, std::get<2>(CommandRef)),
328
206
        Output ? 
Output->getValue(OutputStorage)1
:
""205
);
329
206
  }
330
102
}
331
332
125
bool JSONCompilationDatabase::parse(std::string &ErrorMessage) {
333
125
  llvm::yaml::document_iterator I = YAMLStream.begin();
334
125
  if (I == YAMLStream.end()) {
335
0
    ErrorMessage = "Error while parsing YAML.";
336
0
    return false;
337
0
  }
338
125
  llvm::yaml::Node *Root = I->getRoot();
339
125
  if (!Root) {
340
0
    ErrorMessage = "Error while parsing YAML.";
341
0
    return false;
342
0
  }
343
125
  auto *Array = dyn_cast<llvm::yaml::SequenceNode>(Root);
344
125
  if (!Array) {
345
3
    ErrorMessage = "Expected array.";
346
3
    return false;
347
3
  }
348
15.8k
  
for (auto &NextObject : *Array)122
{
349
15.8k
    auto *Object = dyn_cast<llvm::yaml::MappingNode>(&NextObject);
350
15.8k
    if (!Object) {
351
1
      ErrorMessage = "Expected object.";
352
1
      return false;
353
1
    }
354
15.8k
    llvm::yaml::ScalarNode *Directory = nullptr;
355
15.8k
    llvm::Optional<std::vector<llvm::yaml::ScalarNode *>> Command;
356
15.8k
    llvm::yaml::ScalarNode *File = nullptr;
357
15.8k
    llvm::yaml::ScalarNode *Output = nullptr;
358
47.4k
    for (auto& NextKeyValue : *Object) {
359
47.4k
      auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
360
47.4k
      if (!KeyString) {
361
1
        ErrorMessage = "Expected strings as key.";
362
1
        return false;
363
1
      }
364
47.4k
      SmallString<10> KeyStorage;
365
47.4k
      StringRef KeyValue = KeyString->getValue(KeyStorage);
366
47.4k
      llvm::yaml::Node *Value = NextKeyValue.getValue();
367
47.4k
      if (!Value) {
368
0
        ErrorMessage = "Expected value.";
369
0
        return false;
370
0
      }
371
47.4k
      auto *ValueString = dyn_cast<llvm::yaml::ScalarNode>(Value);
372
47.4k
      auto *SequenceString = dyn_cast<llvm::yaml::SequenceNode>(Value);
373
47.4k
      if (KeyValue == "arguments") {
374
5
        if (!SequenceString) {
375
2
          ErrorMessage = "Expected sequence as value.";
376
2
          return false;
377
2
        }
378
3
        Command = std::vector<llvm::yaml::ScalarNode *>();
379
3
        for (auto &Argument : *SequenceString) {
380
2
          auto *Scalar = dyn_cast<llvm::yaml::ScalarNode>(&Argument);
381
2
          if (!Scalar) {
382
1
            ErrorMessage = "Only strings are allowed in 'arguments'.";
383
1
            return false;
384
1
          }
385
1
          Command->push_back(Scalar);
386
1
        }
387
47.4k
      } else {
388
47.4k
        if (!ValueString) {
389
3
          ErrorMessage = "Expected string as value.";
390
3
          return false;
391
3
        }
392
47.3k
        if (KeyValue == "directory") {
393
15.8k
          Directory = ValueString;
394
31.5k
        } else if (KeyValue == "command") {
395
15.7k
          if (!Command)
396
15.7k
            Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString);
397
15.7k
        } else if (KeyValue == "file") {
398
15.7k
          File = ValueString;
399
15.7k
        } else 
if (2
KeyValue == "output"2
) {
400
1
          Output = ValueString;
401
1
        } else {
402
1
          ErrorMessage =
403
1
              ("Unknown key: \"" + KeyString->getRawValue() + "\"").str();
404
1
          return false;
405
1
        }
406
47.3k
      }
407
47.4k
    }
408
15.8k
    if (!File) {
409
3
      ErrorMessage = "Missing key: \"file\".";
410
3
      return false;
411
3
    }
412
15.7k
    if (!Command) {
413
1
      ErrorMessage = "Missing key: \"command\" or \"arguments\".";
414
1
      return false;
415
1
    }
416
15.7k
    if (!Directory) {
417
1
      ErrorMessage = "Missing key: \"directory\".";
418
1
      return false;
419
1
    }
420
15.7k
    SmallString<8> FileStorage;
421
15.7k
    StringRef FileName = File->getValue(FileStorage);
422
15.7k
    SmallString<128> NativeFilePath;
423
15.7k
    if (llvm::sys::path::is_relative(FileName)) {
424
39
      SmallString<8> DirectoryStorage;
425
39
      SmallString<128> AbsolutePath(
426
39
          Directory->getValue(DirectoryStorage));
427
39
      llvm::sys::path::append(AbsolutePath, FileName);
428
39
      llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/ true);
429
39
      llvm::sys::path::native(AbsolutePath, NativeFilePath);
430
15.7k
    } else {
431
15.7k
      llvm::sys::path::native(FileName, NativeFilePath);
432
15.7k
    }
433
15.7k
    auto Cmd = CompileCommandRef(Directory, File, *Command, Output);
434
15.7k
    IndexByFile[NativeFilePath].push_back(Cmd);
435
15.7k
    AllCommands.push_back(Cmd);
436
15.7k
    MatchTrie.insert(NativeFilePath);
437
15.7k
  }
438
108
  return true;
439
122
}