Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Frontend/DependencyFile.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- DependencyFile.cpp - Generate dependency file --------------------===//
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 code generates dependency files.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Frontend/Utils.h"
14
#include "clang/Basic/FileManager.h"
15
#include "clang/Basic/SourceManager.h"
16
#include "clang/Frontend/DependencyOutputOptions.h"
17
#include "clang/Frontend/FrontendDiagnostic.h"
18
#include "clang/Lex/DirectoryLookup.h"
19
#include "clang/Lex/ModuleMap.h"
20
#include "clang/Lex/PPCallbacks.h"
21
#include "clang/Lex/Preprocessor.h"
22
#include "clang/Serialization/ASTReader.h"
23
#include "llvm/ADT/StringSet.h"
24
#include "llvm/ADT/StringSwitch.h"
25
#include "llvm/Support/FileSystem.h"
26
#include "llvm/Support/Path.h"
27
#include "llvm/Support/raw_ostream.h"
28
29
using namespace clang;
30
31
namespace {
32
struct DepCollectorPPCallbacks : public PPCallbacks {
33
  DependencyCollector &DepCollector;
34
  SourceManager &SM;
35
  DiagnosticsEngine &Diags;
36
  DepCollectorPPCallbacks(DependencyCollector &L, SourceManager &SM,
37
                          DiagnosticsEngine &Diags)
38
3.49k
      : DepCollector(L), SM(SM), Diags(Diags) {}
39
40
  void FileChanged(SourceLocation Loc, FileChangeReason Reason,
41
                   SrcMgr::CharacteristicKind FileType,
42
1.03M
                   FileID PrevFID) override {
43
1.03M
    if (Reason != PPCallbacks::EnterFile)
44
577k
      return;
45
46
    // Dependency generation really does want to go all the way to the
47
    // file entry for a source location to find out what is depended on.
48
    // We do not want #line markers to affect dependency generation!
49
453k
    if (Optional<StringRef> Filename = SM.getNonBuiltinFilenameForID(
50
453k
            SM.getFileID(SM.getExpansionLoc(Loc))))
51
446k
      DepCollector.maybeAddDependency(
52
446k
          llvm::sys::path::remove_leading_dotslash(*Filename),
53
446k
          /*FromModule*/ false, isSystem(FileType), /*IsModuleFile*/ false,
54
446k
          /*IsMissing*/ false);
55
453k
  }
56
57
  void FileSkipped(const FileEntryRef &SkippedFile, const Token &FilenameTok,
58
1.04M
                   SrcMgr::CharacteristicKind FileType) override {
59
1.04M
    StringRef Filename =
60
1.04M
        llvm::sys::path::remove_leading_dotslash(SkippedFile.getName());
61
1.04M
    DepCollector.maybeAddDependency(Filename, /*FromModule=*/false,
62
1.04M
                                    /*IsSystem=*/isSystem(FileType),
63
1.04M
                                    /*IsModuleFile=*/false,
64
1.04M
                                    /*IsMissing=*/false);
65
1.04M
  }
66
67
  void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
68
                          StringRef FileName, bool IsAngled,
69
                          CharSourceRange FilenameRange, const FileEntry *File,
70
                          StringRef SearchPath, StringRef RelativePath,
71
                          const Module *Imported,
72
1.48M
                          SrcMgr::CharacteristicKind FileType) override {
73
1.48M
    if (!File)
74
23
      DepCollector.maybeAddDependency(FileName, /*FromModule*/false,
75
23
                                     /*IsSystem*/false, /*IsModuleFile*/false,
76
23
                                     /*IsMissing*/true);
77
    // Files that actually exist are handled by FileChanged.
78
1.48M
  }
79
80
  void HasInclude(SourceLocation Loc, StringRef SpelledFilename, bool IsAngled,
81
                  Optional<FileEntryRef> File,
82
11.4k
                  SrcMgr::CharacteristicKind FileType) override {
83
11.4k
    if (!File)
84
4.65k
      return;
85
6.77k
    StringRef Filename =
86
6.77k
        llvm::sys::path::remove_leading_dotslash(File->getName());
87
6.77k
    DepCollector.maybeAddDependency(Filename, /*FromModule=*/false,
88
6.77k
                                    /*IsSystem=*/isSystem(FileType),
89
6.77k
                                    /*IsModuleFile=*/false,
90
6.77k
                                    /*IsMissing=*/false);
91
6.77k
  }
92
93
3.49k
  void EndOfMainFile() override { DepCollector.finishedMainFile(Diags); }
94
};
95
96
struct DepCollectorMMCallbacks : public ModuleMapCallbacks {
97
  DependencyCollector &DepCollector;
98
3.49k
  DepCollectorMMCallbacks(DependencyCollector &DC) : DepCollector(DC) {}
99
100
  void moduleMapFileRead(SourceLocation Loc, const FileEntry &Entry,
101
4.93k
                         bool IsSystem) override {
102
4.93k
    StringRef Filename = Entry.getName();
103
4.93k
    DepCollector.maybeAddDependency(Filename, /*FromModule*/false,
104
4.93k
                                    /*IsSystem*/IsSystem,
105
4.93k
                                    /*IsModuleFile*/false,
106
4.93k
                                    /*IsMissing*/false);
107
4.93k
  }
108
};
109
110
struct DepCollectorASTListener : public ASTReaderListener {
111
  DependencyCollector &DepCollector;
112
912
  DepCollectorASTListener(DependencyCollector &L) : DepCollector(L) { }
113
515k
  bool needsInputFileVisitation() override { return true; }
114
515k
  bool needsSystemInputFileVisitation() override {
115
515k
    return DepCollector.needSystemDependencies();
116
515k
  }
117
  void visitModuleFile(StringRef Filename,
118
3.95k
                       serialization::ModuleKind Kind) override {
119
3.95k
    DepCollector.maybeAddDependency(Filename, /*FromModule*/true,
120
3.95k
                                   /*IsSystem*/false, /*IsModuleFile*/true,
121
3.95k
                                   /*IsMissing*/false);
122
3.95k
  }
123
  bool visitInputFile(StringRef Filename, bool IsSystem,
124
511k
                      bool IsOverridden, bool IsExplicitModule) override {
125
511k
    if (IsOverridden || 
IsExplicitModule511k
)
126
131
      return true;
127
128
511k
    DepCollector.maybeAddDependency(Filename, /*FromModule*/true, IsSystem,
129
511k
                                   /*IsModuleFile*/false, /*IsMissing*/false);
130
511k
    return true;
131
511k
  }
132
};
133
} // end anonymous namespace
134
135
void DependencyCollector::maybeAddDependency(StringRef Filename,
136
                                             bool FromModule, bool IsSystem,
137
                                             bool IsModuleFile,
138
2.01M
                                             bool IsMissing) {
139
2.01M
  if (sawDependency(Filename, FromModule, IsSystem, IsModuleFile, IsMissing))
140
2.01M
    addDependency(Filename);
141
2.01M
}
142
143
2.01M
bool DependencyCollector::addDependency(StringRef Filename) {
144
2.01M
  StringRef SearchPath;
145
#ifdef _WIN32
146
  // Make the search insensitive to case and separators.
147
  llvm::SmallString<256> TmpPath = Filename;
148
  llvm::sys::path::native(TmpPath);
149
  std::transform(TmpPath.begin(), TmpPath.end(), TmpPath.begin(), ::tolower);
150
  SearchPath = TmpPath.str();
151
#else
152
2.01M
  SearchPath = Filename;
153
2.01M
#endif
154
155
2.01M
  if (Seen.insert(SearchPath).second) {
156
903k
    Dependencies.push_back(std::string(Filename));
157
903k
    return true;
158
903k
  }
159
1.11M
  return false;
160
2.01M
}
161
162
2.01M
static bool isSpecialFilename(StringRef Filename) {
163
2.01M
  return llvm::StringSwitch<bool>(Filename)
164
2.01M
      .Case("<built-in>", true)
165
2.01M
      .Case("<stdin>", true)
166
2.01M
      .Default(false);
167
2.01M
}
168
169
bool DependencyCollector::sawDependency(StringRef Filename, bool FromModule,
170
                                        bool IsSystem, bool IsModuleFile,
171
270
                                        bool IsMissing) {
172
270
  return !isSpecialFilename(Filename) &&
173
270
         (needSystemDependencies() || 
!IsSystem0
);
174
270
}
175
176
444
DependencyCollector::~DependencyCollector() { }
177
3.49k
void DependencyCollector::attachToPreprocessor(Preprocessor &PP) {
178
3.49k
  PP.addPPCallbacks(std::make_unique<DepCollectorPPCallbacks>(
179
3.49k
      *this, PP.getSourceManager(), PP.getDiagnostics()));
180
3.49k
  PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
181
3.49k
      std::make_unique<DepCollectorMMCallbacks>(*this));
182
3.49k
}
183
912
void DependencyCollector::attachToASTReader(ASTReader &R) {
184
912
  R.addListener(std::make_unique<DepCollectorASTListener>(*this));
185
912
}
186
187
DependencyFileGenerator::DependencyFileGenerator(
188
    const DependencyOutputOptions &Opts)
189
    : OutputFile(Opts.OutputFile), Targets(Opts.Targets),
190
      IncludeSystemHeaders(Opts.IncludeSystemHeaders),
191
      PhonyTarget(Opts.UsePhonyTargets),
192
      AddMissingHeaderDeps(Opts.AddMissingHeaderDeps), SeenMissingHeader(false),
193
      IncludeModuleFiles(Opts.IncludeModuleFiles),
194
3.53k
      OutputFormat(Opts.OutputFormat), InputFileIndex(0) {
195
3.53k
  for (const auto &ExtraDep : Opts.ExtraDeps) {
196
15
    if (addDependency(ExtraDep.first))
197
14
      ++InputFileIndex;
198
15
  }
199
3.53k
}
200
201
3.40k
void DependencyFileGenerator::attachToPreprocessor(Preprocessor &PP) {
202
  // Disable the "file not found" diagnostic if the -MG option was given.
203
3.40k
  if (AddMissingHeaderDeps)
204
4
    PP.SetSuppressIncludeNotFoundError(true);
205
206
3.40k
  DependencyCollector::attachToPreprocessor(PP);
207
3.40k
}
208
209
bool DependencyFileGenerator::sawDependency(StringRef Filename, bool FromModule,
210
                                            bool IsSystem, bool IsModuleFile,
211
2.01M
                                            bool IsMissing) {
212
2.01M
  if (IsMissing) {
213
    // Handle the case of missing file from an inclusion directive.
214
22
    if (AddMissingHeaderDeps)
215
17
      return true;
216
5
    SeenMissingHeader = true;
217
5
    return false;
218
22
  }
219
2.01M
  if (IsModuleFile && 
!IncludeModuleFiles3.93k
)
220
3.92k
    return false;
221
222
2.01M
  if (isSpecialFilename(Filename))
223
0
    return false;
224
225
2.01M
  if (IncludeSystemHeaders)
226
2.01M
    return true;
227
228
98
  return !IsSystem;
229
2.01M
}
230
231
3.26k
void DependencyFileGenerator::finishedMainFile(DiagnosticsEngine &Diags) {
232
3.26k
  outputDependencyFile(Diags);
233
3.26k
}
234
235
/// Print the filename, with escaping or quoting that accommodates the three
236
/// most likely tools that use dependency files: GNU Make, BSD Make, and
237
/// NMake/Jom.
238
///
239
/// BSD Make is the simplest case: It does no escaping at all.  This means
240
/// characters that are normally delimiters, i.e. space and # (the comment
241
/// character) simply aren't supported in filenames.
242
///
243
/// GNU Make does allow space and # in filenames, but to avoid being treated
244
/// as a delimiter or comment, these must be escaped with a backslash. Because
245
/// backslash is itself the escape character, if a backslash appears in a
246
/// filename, it should be escaped as well.  (As a special case, $ is escaped
247
/// as $$, which is the normal Make way to handle the $ character.)
248
/// For compatibility with BSD Make and historical practice, if GNU Make
249
/// un-escapes characters in a filename but doesn't find a match, it will
250
/// retry with the unmodified original string.
251
///
252
/// GCC tries to accommodate both Make formats by escaping any space or #
253
/// characters in the original filename, but not escaping backslashes.  The
254
/// apparent intent is so that filenames with backslashes will be handled
255
/// correctly by BSD Make, and by GNU Make in its fallback mode of using the
256
/// unmodified original string; filenames with # or space characters aren't
257
/// supported by BSD Make at all, but will be handled correctly by GNU Make
258
/// due to the escaping.
259
///
260
/// A corner case that GCC gets only partly right is when the original filename
261
/// has a backslash immediately followed by space or #.  GNU Make would expect
262
/// this backslash to be escaped; however GCC escapes the original backslash
263
/// only when followed by space, not #.  It will therefore take a dependency
264
/// from a directive such as
265
///     #include "a\ b\#c.h"
266
/// and emit it as
267
///     a\\\ b\\#c.h
268
/// which GNU Make will interpret as
269
///     a\ b\
270
/// followed by a comment. Failing to find this file, it will fall back to the
271
/// original string, which probably doesn't exist either; in any case it won't
272
/// find
273
///     a\ b\#c.h
274
/// which is the actual filename specified by the include directive.
275
///
276
/// Clang does what GCC does, rather than what GNU Make expects.
277
///
278
/// NMake/Jom has a different set of scary characters, but wraps filespecs in
279
/// double-quotes to avoid misinterpreting them; see
280
/// https://msdn.microsoft.com/en-us/library/dd9y37ha.aspx for NMake info,
281
/// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
282
/// for Windows file-naming info.
283
static void PrintFilename(raw_ostream &OS, StringRef Filename,
284
1.80M
                          DependencyOutputFormat OutputFormat) {
285
  // Convert filename to platform native path
286
1.80M
  llvm::SmallString<256> NativePath;
287
1.80M
  llvm::sys::path::native(Filename.str(), NativePath);
288
289
1.80M
  if (OutputFormat == DependencyOutputFormat::NMake) {
290
    // Add quotes if needed. These are the characters listed as "special" to
291
    // NMake, that are legal in a Windows filespec, and that could cause
292
    // misinterpretation of the dependency string.
293
6
    if (NativePath.find_first_of(" #${}^!") != StringRef::npos)
294
4
      OS << '\"' << NativePath << '\"';
295
2
    else
296
2
      OS << NativePath;
297
6
    return;
298
6
  }
299
1.80M
  assert(OutputFormat == DependencyOutputFormat::Make);
300
235M
  for (unsigned i = 0, e = NativePath.size(); i != e; 
++i233M
) {
301
233M
    if (NativePath[i] == '#') // Handle '#' the broken gcc way.
302
6
      OS << '\\';
303
233M
    else if (NativePath[i] == ' ') { // Handle space correctly.
304
10
      OS << '\\';
305
10
      unsigned j = i;
306
10
      while (j > 0 && 
NativePath[--j] == '\\'8
)
307
0
        OS << '\\';
308
233M
    } else if (NativePath[i] == '$') // $ is escaped by $$.
309
4
      OS << '$';
310
233M
    OS << NativePath[i];
311
233M
  }
312
1.80M
}
313
314
3.26k
void DependencyFileGenerator::outputDependencyFile(DiagnosticsEngine &Diags) {
315
3.26k
  if (SeenMissingHeader) {
316
1
    llvm::sys::fs::remove(OutputFile);
317
1
    return;
318
1
  }
319
320
3.26k
  std::error_code EC;
321
3.26k
  llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::OF_TextWithCRLF);
322
3.26k
  if (EC) {
323
0
    Diags.Report(diag::err_fe_error_opening) << OutputFile << EC.message();
324
0
    return;
325
0
  }
326
327
3.26k
  outputDependencyFile(OS);
328
3.26k
}
329
330
3.39k
void DependencyFileGenerator::outputDependencyFile(llvm::raw_ostream &OS) {
331
  // Write out the dependency targets, trying to avoid overly long
332
  // lines when possible. We try our best to emit exactly the same
333
  // dependency file as GCC (4.2), assuming the included files are the
334
  // same.
335
3.39k
  const unsigned MaxColumns = 75;
336
3.39k
  unsigned Columns = 0;
337
338
3.40k
  for (StringRef Target : Targets) {
339
3.40k
    unsigned N = Target.size();
340
3.40k
    if (Columns == 0) {
341
3.39k
      Columns += N;
342
3.39k
    } else 
if (6
Columns + N + 2 > MaxColumns6
) {
343
0
      Columns = N + 2;
344
0
      OS << " \\\n  ";
345
6
    } else {
346
6
      Columns += N + 1;
347
6
      OS << ' ';
348
6
    }
349
    // Targets already quoted as needed.
350
3.40k
    OS << Target;
351
3.40k
  }
352
353
3.39k
  OS << ':';
354
3.39k
  Columns += 1;
355
356
  // Now add each dependency in the order it was seen, but avoiding
357
  // duplicates.
358
3.39k
  ArrayRef<std::string> Files = getDependencies();
359
902k
  for (StringRef File : Files) {
360
    // Start a new line if this would exceed the column limit. Make
361
    // sure to leave space for a trailing " \" in case we need to
362
    // break the line on the next iteration.
363
902k
    unsigned N = File.size();
364
902k
    if (Columns + (N + 1) + 2 > MaxColumns) {
365
902k
      OS << " \\\n ";
366
902k
      Columns = 2;
367
902k
    }
368
902k
    OS << ' ';
369
902k
    PrintFilename(OS, File, OutputFormat);
370
902k
    Columns += N + 1;
371
902k
  }
372
3.39k
  OS << '\n';
373
374
  // Create phony targets if requested.
375
3.39k
  if (PhonyTarget && 
!Files.empty()3.21k
) {
376
3.21k
    unsigned Index = 0;
377
905k
    for (auto I = Files.begin(), E = Files.end(); I != E; 
++I901k
) {
378
901k
      if (Index++ == InputFileIndex)
379
3.21k
        continue;
380
898k
      OS << '\n';
381
898k
      PrintFilename(OS, *I, OutputFormat);
382
898k
      OS << ":\n";
383
898k
    }
384
3.21k
  }
385
3.39k
}