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