Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/ARCMigrate/FileRemapper.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- FileRemapper.cpp - File Remapping Helper -------------------------===//
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
#include "clang/ARCMigrate/FileRemapper.h"
10
#include "clang/Basic/Diagnostic.h"
11
#include "clang/Basic/FileManager.h"
12
#include "clang/Lex/PreprocessorOptions.h"
13
#include "llvm/Support/FileSystem.h"
14
#include "llvm/Support/MemoryBuffer.h"
15
#include "llvm/Support/Path.h"
16
#include "llvm/Support/raw_ostream.h"
17
#include <fstream>
18
19
using namespace clang;
20
using namespace arcmt;
21
22
88
FileRemapper::FileRemapper() {
23
88
  FileMgr.reset(new FileManager(FileSystemOptions()));
24
88
}
25
26
88
FileRemapper::~FileRemapper() {
27
88
  clear();
28
88
}
29
30
90
void FileRemapper::clear(StringRef outputDir) {
31
90
  for (MappingsTy::iterator
32
185
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; 
++I95
)
33
95
    resetTarget(I->second);
34
90
  FromToMappings.clear();
35
90
  assert(ToFromMappings.empty());
36
90
  if (!outputDir.empty()) {
37
0
    std::string infoFile = getRemapInfoFile(outputDir);
38
0
    llvm::sys::fs::remove(infoFile);
39
0
  }
40
90
}
41
42
82
std::string FileRemapper::getRemapInfoFile(StringRef outputDir) {
43
82
  assert(!outputDir.empty());
44
0
  SmallString<128> InfoFile = outputDir;
45
82
  llvm::sys::path::append(InfoFile, "remap");
46
82
  return std::string(InfoFile.str());
47
82
}
48
49
bool FileRemapper::initFromDisk(StringRef outputDir, DiagnosticsEngine &Diag,
50
53
                                bool ignoreIfFilesChanged) {
51
53
  std::string infoFile = getRemapInfoFile(outputDir);
52
53
  return initFromFile(infoFile, Diag, ignoreIfFilesChanged);
53
53
}
54
55
bool FileRemapper::initFromFile(StringRef filePath, DiagnosticsEngine &Diag,
56
53
                                bool ignoreIfFilesChanged) {
57
53
  assert(FromToMappings.empty() &&
58
53
         "initFromDisk should be called before any remap calls");
59
0
  std::string infoFile = std::string(filePath);
60
53
  if (!llvm::sys::fs::exists(infoFile))
61
26
    return false;
62
63
27
  std::vector<std::pair<const FileEntry *, const FileEntry *> > pairs;
64
65
27
  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> fileBuf =
66
27
      llvm::MemoryBuffer::getFile(infoFile, /*IsText=*/true);
67
27
  if (!fileBuf)
68
0
    return report("Error opening file: " + infoFile, Diag);
69
70
27
  SmallVector<StringRef, 64> lines;
71
27
  fileBuf.get()->getBuffer().split(lines, "\n");
72
73
63
  for (unsigned idx = 0; idx+3 <= lines.size(); 
idx += 336
) {
74
36
    StringRef fromFilename = lines[idx];
75
36
    unsigned long long timeModified;
76
36
    if (lines[idx+1].getAsInteger(10, timeModified))
77
0
      return report("Invalid file data: '" + lines[idx+1] + "' not a number",
78
0
                    Diag);
79
36
    StringRef toFilename = lines[idx+2];
80
81
36
    llvm::ErrorOr<const FileEntry *> origFE = FileMgr->getFile(fromFilename);
82
36
    if (!origFE) {
83
0
      if (ignoreIfFilesChanged)
84
0
        continue;
85
0
      return report("File does not exist: " + fromFilename, Diag);
86
0
    }
87
36
    llvm::ErrorOr<const FileEntry *> newFE = FileMgr->getFile(toFilename);
88
36
    if (!newFE) {
89
0
      if (ignoreIfFilesChanged)
90
0
        continue;
91
0
      return report("File does not exist: " + toFilename, Diag);
92
0
    }
93
94
36
    if ((uint64_t)(*origFE)->getModificationTime() != timeModified) {
95
0
      if (ignoreIfFilesChanged)
96
0
        continue;
97
0
      return report("File was modified: " + fromFilename, Diag);
98
0
    }
99
100
36
    pairs.push_back(std::make_pair(*origFE, *newFE));
101
36
  }
102
103
63
  
for (unsigned i = 0, e = pairs.size(); 27
i != e;
++i36
)
104
36
    remap(pairs[i].first, pairs[i].second);
105
106
27
  return false;
107
27
}
108
109
29
bool FileRemapper::flushToDisk(StringRef outputDir, DiagnosticsEngine &Diag) {
110
29
  using namespace llvm::sys;
111
112
29
  if (fs::create_directory(outputDir))
113
0
    return report("Could not create directory: " + outputDir, Diag);
114
115
29
  std::string infoFile = getRemapInfoFile(outputDir);
116
29
  return flushToFile(infoFile, Diag);
117
29
}
118
119
29
bool FileRemapper::flushToFile(StringRef outputPath, DiagnosticsEngine &Diag) {
120
29
  using namespace llvm::sys;
121
122
29
  std::error_code EC;
123
29
  std::string infoFile = std::string(outputPath);
124
29
  llvm::raw_fd_ostream infoOut(infoFile, EC, llvm::sys::fs::OF_Text);
125
29
  if (EC)
126
0
    return report(EC.message(), Diag);
127
128
29
  for (MappingsTy::iterator
129
67
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; 
++I38
) {
130
131
38
    const FileEntry *origFE = I->first;
132
38
    SmallString<200> origPath = StringRef(origFE->getName());
133
38
    fs::make_absolute(origPath);
134
38
    infoOut << origPath << '\n';
135
38
    infoOut << (uint64_t)origFE->getModificationTime() << '\n';
136
137
38
    if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) {
138
3
      SmallString<200> newPath = StringRef(FE->getName());
139
3
      fs::make_absolute(newPath);
140
3
      infoOut << newPath << '\n';
141
35
    } else {
142
143
35
      SmallString<64> tempPath;
144
35
      int fd;
145
35
      if (fs::createTemporaryFile(
146
35
              path::filename(origFE->getName()),
147
35
              path::extension(origFE->getName()).drop_front(), fd, tempPath,
148
35
              llvm::sys::fs::OF_Text))
149
0
        return report("Could not create file: " + tempPath.str(), Diag);
150
151
35
      llvm::raw_fd_ostream newOut(fd, /*shouldClose=*/true);
152
35
      llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>();
153
35
      newOut.write(mem->getBufferStart(), mem->getBufferSize());
154
35
      newOut.close();
155
156
35
      auto newE = FileMgr->getFile(tempPath);
157
35
      if (newE) {
158
35
        remap(origFE, *newE);
159
35
        infoOut << (*newE)->getName() << '\n';
160
35
      }
161
35
    }
162
38
  }
163
164
29
  infoOut.close();
165
29
  return false;
166
29
}
167
168
bool FileRemapper::overwriteOriginal(DiagnosticsEngine &Diag,
169
2
                                     StringRef outputDir) {
170
2
  using namespace llvm::sys;
171
172
2
  for (MappingsTy::iterator
173
4
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; 
++I2
) {
174
2
    const FileEntry *origFE = I->first;
175
2
    assert(I->second.is<llvm::MemoryBuffer *>());
176
2
    if (!fs::exists(origFE->getName()))
177
0
      return report(StringRef("File does not exist: ") + origFE->getName(),
178
0
                    Diag);
179
180
2
    std::error_code EC;
181
2
    llvm::raw_fd_ostream Out(origFE->getName(), EC, llvm::sys::fs::OF_None);
182
2
    if (EC)
183
0
      return report(EC.message(), Diag);
184
185
2
    llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>();
186
2
    Out.write(mem->getBufferStart(), mem->getBufferSize());
187
2
    Out.close();
188
2
  }
189
190
2
  clear(outputDir);
191
2
  return false;
192
2
}
193
194
void FileRemapper::forEachMapping(
195
    llvm::function_ref<void(StringRef, StringRef)> CaptureFile,
196
    llvm::function_ref<void(StringRef, const llvm::MemoryBufferRef &)>
197
49
        CaptureBuffer) const {
198
55
  for (auto &Mapping : FromToMappings) {
199
55
    if (const FileEntry *FE = Mapping.second.dyn_cast<const FileEntry *>()) {
200
30
      CaptureFile(Mapping.first->getName(), FE->getName());
201
30
      continue;
202
30
    }
203
25
    CaptureBuffer(
204
25
        Mapping.first->getName(),
205
25
        Mapping.second.get<llvm::MemoryBuffer *>()->getMemBufferRef());
206
25
  }
207
49
}
208
209
72
void FileRemapper::applyMappings(PreprocessorOptions &PPOpts) const {
210
72
  for (MappingsTy::const_iterator
211
124
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; 
++I52
) {
212
52
    if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) {
213
9
      PPOpts.addRemappedFile(I->first->getName(), FE->getName());
214
43
    } else {
215
43
      llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>();
216
43
      PPOpts.addRemappedFile(I->first->getName(), mem);
217
43
    }
218
52
  }
219
220
72
  PPOpts.RetainRemappedFileBuffers = true;
221
72
}
222
223
void FileRemapper::remap(StringRef filePath,
224
98
                         std::unique_ptr<llvm::MemoryBuffer> memBuf) {
225
98
  remap(getOriginalFile(filePath), std::move(memBuf));
226
98
}
227
228
void FileRemapper::remap(const FileEntry *file,
229
98
                         std::unique_ptr<llvm::MemoryBuffer> memBuf) {
230
98
  assert(file);
231
0
  Target &targ = FromToMappings[file];
232
98
  resetTarget(targ);
233
98
  targ = memBuf.release();
234
98
}
235
236
71
void FileRemapper::remap(const FileEntry *file, const FileEntry *newfile) {
237
71
  assert(file && newfile);
238
0
  Target &targ = FromToMappings[file];
239
71
  resetTarget(targ);
240
71
  targ = newfile;
241
71
  ToFromMappings[newfile] = file;
242
71
}
243
244
98
const FileEntry *FileRemapper::getOriginalFile(StringRef filePath) {
245
98
  const FileEntry *file = nullptr;
246
98
  if (auto fileOrErr = FileMgr->getFile(filePath))
247
98
    file = *fileOrErr;
248
  // If we are updating a file that overridden an original file,
249
  // actually update the original file.
250
98
  llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
251
98
    I = ToFromMappings.find(file);
252
98
  if (I != ToFromMappings.end()) {
253
0
    file = I->second;
254
0
    assert(FromToMappings.find(file) != FromToMappings.end() &&
255
0
           "Original file not in mappings!");
256
0
  }
257
0
  return file;
258
98
}
259
260
264
void FileRemapper::resetTarget(Target &targ) {
261
264
  if (!targ)
262
95
    return;
263
264
169
  if (llvm::MemoryBuffer *oldmem = targ.dyn_cast<llvm::MemoryBuffer *>()) {
265
98
    delete oldmem;
266
98
  } else {
267
71
    const FileEntry *toFE = targ.get<const FileEntry *>();
268
71
    ToFromMappings.erase(toFE);
269
71
  }
270
169
}
271
272
0
bool FileRemapper::report(const Twine &err, DiagnosticsEngine &Diag) {
273
0
  Diag.Report(Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
274
0
      << err.str();
275
0
  return true;
276
0
}