Coverage Report

Created: 2020-03-31 06:27

/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
115
      : Input(CommandLine), Position(Input.begin()-1) {}
56
57
115
  std::vector<std::string> parse() {
58
115
    bool HasMoreInput = true;
59
766
    while (HasMoreInput && 
nextNonWhitespace()654
) {
60
651
      std::string Argument;
61
651
      HasMoreInput = parseStringInto(Argument);
62
651
      CommandLine.push_back(Argument);
63
651
    }
64
115
    return CommandLine;
65
115
  }
66
67
 private:
68
  // All private methods return true if there is more input available.
69
70
651
  bool parseStringInto(std::string &String) {
71
658
    do {
72
658
      if (*Position == '"') {
73
18
        if (!parseDoubleQuotedStringInto(String)) 
return false8
;
74
640
      } else if (*Position == '\'') {
75
1
        if (!parseSingleQuotedStringInto(String)) return false;
76
639
      } else {
77
639
        if (!parseFreeStringInto(String)) 
return false103
;
78
546
      }
79
658
    } while (
*Position != ' '546
);
80
651
    
return true539
;
81
651
  }
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
17
    
return next()16
;
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
639
  bool parseFreeStringInto(std::string &String) {
103
20.6k
    do {
104
20.6k
      if (!skipEscapeCharacter()) 
return false0
;
105
20.6k
      String.push_back(*Position);
106
20.6k
      if (!next()) 
return false103
;
107
20.5k
    } while (*Position != ' ' && 
*Position != '"'20.0k
&&
*Position != '\''20.0k
);
108
639
    
return true536
;
109
639
  }
110
111
20.7k
  bool skipEscapeCharacter() {
112
20.7k
    if (*Position == '\\') {
113
7
      return next();
114
7
    }
115
20.7k
    return true;
116
20.7k
  }
117
118
654
  bool nextNonWhitespace() {
119
674
    do {
120
674
      if (!next()) 
return false3
;
121
671
    } while (*Position == ' ');
122
654
    
return true651
;
123
654
  }
124
125
21.4k
  bool next() {
126
21.4k
    ++Position;
127
21.4k
    return Position != Input.end();
128
21.4k
  }
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
115
                                             StringRef EscapedCommandLine) {
137
115
  if (Syntax == JSONCommandLineSyntax::AutoDetect) {
138
83
    Syntax = JSONCommandLineSyntax::Gnu;
139
83
    llvm::Triple Triple(llvm::sys::getProcessTriple());
140
83
    if (Triple.getOS() == llvm::Triple::OSType::Win32) {
141
0
      // Assume Windows command line parsing on Win32 unless the triple
142
0
      // 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
83
  }
148
115
149
115
  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
115
  assert(Syntax == JSONCommandLineSyntax::Gnu);
158
115
  CommandLineArgumentParser parser(EscapedCommandLine);
159
115
  return parser.parse();
160
115
}
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
87
                                      JSONCommandLineSyntax Syntax) {
199
87
  // Don't mmap: if we're a long-lived process, the build system may overwrite.
200
87
  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> DatabaseBuffer =
201
87
      llvm::MemoryBuffer::getFile(FilePath, /*FileSize=*/-1,
202
87
                                  /*RequiresNullTerminator=*/true,
203
87
                                  /*IsVolatile=*/true);
204
87
  if (std::error_code Result = DatabaseBuffer.getError()) {
205
41
    ErrorMessage = "Error while opening JSON database: " + Result.message();
206
41
    return nullptr;
207
41
  }
208
46
  std::unique_ptr<JSONCompilationDatabase> Database(
209
46
      new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
210
46
  if (!Database->parse(ErrorMessage))
211
0
    return nullptr;
212
46
  return Database;
213
46
}
214
215
std::unique_ptr<JSONCompilationDatabase>
216
JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString,
217
                                        std::string &ErrorMessage,
218
51
                                        JSONCommandLineSyntax Syntax) {
219
51
  std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer(
220
51
      llvm::MemoryBuffer::getMemBuffer(DatabaseString));
221
51
  std::unique_ptr<JSONCompilationDatabase> Database(
222
51
      new JSONCompilationDatabase(std::move(DatabaseBuffer), Syntax));
223
51
  if (!Database->parse(ErrorMessage))
224
17
    return nullptr;
225
34
  return Database;
226
34
}
227
228
std::vector<CompileCommand>
229
45
JSONCompilationDatabase::getCompileCommands(StringRef FilePath) const {
230
45
  SmallString<128> NativeFilePath;
231
45
  llvm::sys::path::native(FilePath, NativeFilePath);
232
45
233
45
  std::string Error;
234
45
  llvm::raw_string_ostream ES(Error);
235
45
  StringRef Match = MatchTrie.findEquivalent(NativeFilePath, ES);
236
45
  if (Match.empty())
237
2
    return {};
238
43
  const auto CommandsRefI = IndexByFile.find(Match);
239
43
  if (CommandsRefI == IndexByFile.end())
240
0
    return {};
241
43
  std::vector<CompileCommand> Commands;
242
43
  getCommands(CommandsRefI->getValue(), Commands);
243
43
  return Commands;
244
43
}
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
14.1k
    Result.push_back(CommandRef.first().str());
251
21
  return Result;
252
21
}
253
254
std::vector<CompileCommand>
255
31
JSONCompilationDatabase::getAllCompileCommands() const {
256
31
  std::vector<CompileCommand> Commands;
257
31
  getCommands(AllCommands, Commands);
258
31
  return Commands;
259
31
}
260
261
113
static llvm::StringRef stripExecutableExtension(llvm::StringRef Name) {
262
113
  Name.consume_back(".exe");
263
113
  return Name;
264
113
}
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
122
static bool unwrapCommand(std::vector<std::string> &Args) {
271
122
  if (Args.size() < 2)
272
17
    return false;
273
105
  StringRef Wrapper =
274
105
      stripExecutableExtension(llvm::sys::path::filename(Args.front()));
275
105
  if (Wrapper == "distcc" || 
Wrapper == "gomacc"101
||
Wrapper == "ccache"100
) {
276
9
    // Most of these wrappers support being invoked 3 ways:
277
9
    // `distcc g++ file.c` This is the mode we're trying to match.
278
9
    //                     We need to drop `distcc`.
279
9
    // `distcc file.c`     This acts like compiler is cc or similar.
280
9
    //                     Clang's driver can handle this, no change needed.
281
9
    // `g++ file.c`        g++ is a symlink to distcc.
282
9
    //                     We don't even notice this case, and all is well.
283
9
    //
284
9
    // We need to distinguish between the first and second case.
285
9
    // The wrappers themselves don't take flags, so Args[1] is a compiler flag,
286
9
    // an input file, or a compiler. Inputs have extensions, compilers don't.
287
9
    bool HasCompiler =
288
9
        (Args[1][0] != '-') &&
289
9
        
!llvm::sys::path::has_extension(stripExecutableExtension(Args[1]))8
;
290
9
    if (HasCompiler) {
291
7
      Args.erase(Args.begin());
292
7
      return true;
293
7
    }
294
98
    // If !HasCompiler, wrappers act like GCC. Fine: so do we.
295
98
  }
296
98
  return false;
297
98
}
298
299
static std::vector<std::string>
300
nodeToCommandLine(JSONCommandLineSyntax Syntax,
301
115
                  const std::vector<llvm::yaml::ScalarNode *> &Nodes) {
302
115
  SmallString<1024> Storage;
303
115
  std::vector<std::string> Arguments;
304
115
  if (Nodes.size() == 1)
305
115
    Arguments = unescapeCommandLine(Syntax, Nodes[0]->getValue(Storage));
306
0
  else
307
0
    for (const auto *Node : Nodes)
308
0
      Arguments.push_back(std::string(Node->getValue(Storage)));
309
115
  // There may be multiple wrappers: using distcc and ccache together is common.
310
122
  while (unwrapCommand(Arguments))
311
7
    ;
312
115
  return Arguments;
313
115
}
314
315
void JSONCompilationDatabase::getCommands(
316
    ArrayRef<CompileCommandRef> CommandsRef,
317
74
    std::vector<CompileCommand> &Commands) const {
318
115
  for (const auto &CommandRef : CommandsRef) {
319
115
    SmallString<8> DirectoryStorage;
320
115
    SmallString<32> FilenameStorage;
321
115
    SmallString<32> OutputStorage;
322
115
    auto Output = std::get<3>(CommandRef);
323
115
    Commands.emplace_back(
324
115
        std::get<0>(CommandRef)->getValue(DirectoryStorage),
325
115
        std::get<1>(CommandRef)->getValue(FilenameStorage),
326
115
        nodeToCommandLine(Syntax, std::get<2>(CommandRef)),
327
115
        Output ? 
Output->getValue(OutputStorage)1
:
""114
);
328
115
  }
329
74
}
330
331
97
bool JSONCompilationDatabase::parse(std::string &ErrorMessage) {
332
97
  llvm::yaml::document_iterator I = YAMLStream.begin();
333
97
  if (I == YAMLStream.end()) {
334
0
    ErrorMessage = "Error while parsing YAML.";
335
0
    return false;
336
0
  }
337
97
  llvm::yaml::Node *Root = I->getRoot();
338
97
  if (!Root) {
339
0
    ErrorMessage = "Error while parsing YAML.";
340
0
    return false;
341
0
  }
342
97
  auto *Array = dyn_cast<llvm::yaml::SequenceNode>(Root);
343
97
  if (!Array) {
344
3
    ErrorMessage = "Expected array.";
345
3
    return false;
346
3
  }
347
14.4k
  
for (auto &NextObject : *Array)94
{
348
14.4k
    auto *Object = dyn_cast<llvm::yaml::MappingNode>(&NextObject);
349
14.4k
    if (!Object) {
350
1
      ErrorMessage = "Expected object.";
351
1
      return false;
352
1
    }
353
14.4k
    llvm::yaml::ScalarNode *Directory = nullptr;
354
14.4k
    llvm::Optional<std::vector<llvm::yaml::ScalarNode *>> Command;
355
14.4k
    llvm::yaml::ScalarNode *File = nullptr;
356
14.4k
    llvm::yaml::ScalarNode *Output = nullptr;
357
43.4k
    for (auto& NextKeyValue : *Object) {
358
43.4k
      auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
359
43.4k
      if (!KeyString) {
360
1
        ErrorMessage = "Expected strings as key.";
361
1
        return false;
362
1
      }
363
43.4k
      SmallString<10> KeyStorage;
364
43.4k
      StringRef KeyValue = KeyString->getValue(KeyStorage);
365
43.4k
      llvm::yaml::Node *Value = NextKeyValue.getValue();
366
43.4k
      if (!Value) {
367
0
        ErrorMessage = "Expected value.";
368
0
        return false;
369
0
      }
370
43.4k
      auto *ValueString = dyn_cast<llvm::yaml::ScalarNode>(Value);
371
43.4k
      auto *SequenceString = dyn_cast<llvm::yaml::SequenceNode>(Value);
372
43.4k
      if (KeyValue == "arguments" && 
!SequenceString5
) {
373
2
        ErrorMessage = "Expected sequence as value.";
374
2
        return false;
375
43.4k
      } else if (KeyValue != "arguments" && 
!ValueString43.4k
) {
376
3
        ErrorMessage = "Expected string as value.";
377
3
        return false;
378
3
      }
379
43.4k
      if (KeyValue == "directory") {
380
14.4k
        Directory = ValueString;
381
28.9k
      } else if (KeyValue == "arguments") {
382
3
        Command = std::vector<llvm::yaml::ScalarNode *>();
383
3
        for (auto &Argument : *SequenceString) {
384
2
          auto *Scalar = dyn_cast<llvm::yaml::ScalarNode>(&Argument);
385
2
          if (!Scalar) {
386
1
            ErrorMessage = "Only strings are allowed in 'arguments'.";
387
1
            return false;
388
1
          }
389
1
          Command->push_back(Scalar);
390
1
        }
391
28.9k
      } else if (KeyValue == "command") {
392
14.4k
        if (!Command)
393
14.4k
          Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString);
394
14.4k
      } else if (KeyValue == "file") {
395
14.4k
        File = ValueString;
396
14.4k
      } else 
if (2
KeyValue == "output"2
) {
397
1
        Output = ValueString;
398
1
      } else {
399
1
        ErrorMessage = ("Unknown key: \"" +
400
1
                        KeyString->getRawValue() + "\"").str();
401
1
        return false;
402
1
      }
403
43.4k
    }
404
14.4k
    
if (14.4k
!File14.4k
) {
405
3
      ErrorMessage = "Missing key: \"file\".";
406
3
      return false;
407
3
    }
408
14.4k
    if (!Command) {
409
1
      ErrorMessage = "Missing key: \"command\" or \"arguments\".";
410
1
      return false;
411
1
    }
412
14.4k
    if (!Directory) {
413
1
      ErrorMessage = "Missing key: \"directory\".";
414
1
      return false;
415
1
    }
416
14.4k
    SmallString<8> FileStorage;
417
14.4k
    StringRef FileName = File->getValue(FileStorage);
418
14.4k
    SmallString<128> NativeFilePath;
419
14.4k
    if (llvm::sys::path::is_relative(FileName)) {
420
39
      SmallString<8> DirectoryStorage;
421
39
      SmallString<128> AbsolutePath(
422
39
          Directory->getValue(DirectoryStorage));
423
39
      llvm::sys::path::append(AbsolutePath, FileName);
424
39
      llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/ true);
425
39
      llvm::sys::path::native(AbsolutePath, NativeFilePath);
426
14.4k
    } else {
427
14.4k
      llvm::sys::path::native(FileName, NativeFilePath);
428
14.4k
    }
429
14.4k
    auto Cmd = CompileCommandRef(Directory, File, *Command, Output);
430
14.4k
    IndexByFile[NativeFilePath].push_back(Cmd);
431
14.4k
    AllCommands.push_back(Cmd);
432
14.4k
    MatchTrie.insert(NativeFilePath);
433
14.4k
  }
434
94
  
return true80
;
435
94
}