head	1.1;
branch	1.1.1;
access;
symbols
	netbsd-11-0-RC4:1.1.1.10
	netbsd-11-0-RC3:1.1.1.10
	netbsd-11-0-RC2:1.1.1.10
	netbsd-11-0-RC1:1.1.1.10
	perseant-exfatfs-base-20250801:1.1.1.10
	netbsd-11:1.1.1.10.0.10
	netbsd-11-base:1.1.1.10
	netbsd-10-1-RELEASE:1.1.1.10
	perseant-exfatfs-base-20240630:1.1.1.10
	perseant-exfatfs:1.1.1.10.0.8
	perseant-exfatfs-base:1.1.1.10
	netbsd-8-3-RELEASE:1.1.1.9
	netbsd-9-4-RELEASE:1.1.1.9
	netbsd-10-0-RELEASE:1.1.1.10
	netbsd-10-0-RC6:1.1.1.10
	netbsd-10-0-RC5:1.1.1.10
	netbsd-10-0-RC4:1.1.1.10
	netbsd-10-0-RC3:1.1.1.10
	netbsd-10-0-RC2:1.1.1.10
	netbsd-10-0-RC1:1.1.1.10
	netbsd-10:1.1.1.10.0.6
	netbsd-10-base:1.1.1.10
	netbsd-9-3-RELEASE:1.1.1.9
	cjep_sun2x:1.1.1.10.0.4
	cjep_sun2x-base:1.1.1.10
	cjep_staticlib_x-base1:1.1.1.10
	netbsd-9-2-RELEASE:1.1.1.9
	cjep_staticlib_x:1.1.1.10.0.2
	cjep_staticlib_x-base:1.1.1.10
	netbsd-9-1-RELEASE:1.1.1.9
	phil-wifi-20200421:1.1.1.10
	phil-wifi-20200411:1.1.1.10
	phil-wifi-20200406:1.1.1.10
	netbsd-8-2-RELEASE:1.1.1.9
	netbsd-9-0-RELEASE:1.1.1.9
	netbsd-9-0-RC2:1.1.1.9
	netbsd-9-0-RC1:1.1.1.9
	netbsd-9:1.1.1.9.0.16
	netbsd-9-base:1.1.1.9
	phil-wifi-20190609:1.1.1.9
	netbsd-8-1-RELEASE:1.1.1.9
	netbsd-8-1-RC1:1.1.1.9
	pgoyette-compat-merge-20190127:1.1.1.9
	pgoyette-compat-20190127:1.1.1.9
	pgoyette-compat-20190118:1.1.1.9
	pgoyette-compat-1226:1.1.1.9
	pgoyette-compat-1126:1.1.1.9
	pgoyette-compat-1020:1.1.1.9
	pgoyette-compat-0930:1.1.1.9
	pgoyette-compat-0906:1.1.1.9
	netbsd-7-2-RELEASE:1.1.1.6.2.1
	pgoyette-compat-0728:1.1.1.9
	clang-337282:1.1.1.9
	netbsd-8-0-RELEASE:1.1.1.9
	phil-wifi:1.1.1.9.0.14
	phil-wifi-base:1.1.1.9
	pgoyette-compat-0625:1.1.1.9
	netbsd-8-0-RC2:1.1.1.9
	pgoyette-compat-0521:1.1.1.9
	pgoyette-compat-0502:1.1.1.9
	pgoyette-compat-0422:1.1.1.9
	netbsd-8-0-RC1:1.1.1.9
	pgoyette-compat-0415:1.1.1.9
	pgoyette-compat-0407:1.1.1.9
	pgoyette-compat-0330:1.1.1.9
	pgoyette-compat-0322:1.1.1.9
	pgoyette-compat-0315:1.1.1.9
	netbsd-7-1-2-RELEASE:1.1.1.6.2.1
	pgoyette-compat:1.1.1.9.0.12
	pgoyette-compat-base:1.1.1.9
	netbsd-7-1-1-RELEASE:1.1.1.6.2.1
	clang-319952:1.1.1.9
	matt-nb8-mediatek:1.1.1.9.0.10
	matt-nb8-mediatek-base:1.1.1.9
	clang-309604:1.1.1.9
	perseant-stdc-iso10646:1.1.1.9.0.8
	perseant-stdc-iso10646-base:1.1.1.9
	netbsd-8:1.1.1.9.0.6
	netbsd-8-base:1.1.1.9
	prg-localcount2-base3:1.1.1.9
	prg-localcount2-base2:1.1.1.9
	prg-localcount2-base1:1.1.1.9
	prg-localcount2:1.1.1.9.0.4
	prg-localcount2-base:1.1.1.9
	pgoyette-localcount-20170426:1.1.1.9
	bouyer-socketcan-base1:1.1.1.9
	pgoyette-localcount-20170320:1.1.1.9
	netbsd-7-1:1.1.1.6.2.1.0.6
	netbsd-7-1-RELEASE:1.1.1.6.2.1
	netbsd-7-1-RC2:1.1.1.6.2.1
	clang-294123:1.1.1.9
	netbsd-7-nhusb-base-20170116:1.1.1.6.2.1
	bouyer-socketcan:1.1.1.9.0.2
	bouyer-socketcan-base:1.1.1.9
	clang-291444:1.1.1.9
	pgoyette-localcount-20170107:1.1.1.8
	netbsd-7-1-RC1:1.1.1.6.2.1
	pgoyette-localcount-20161104:1.1.1.8
	netbsd-7-0-2-RELEASE:1.1.1.6.2.1
	localcount-20160914:1.1.1.8
	netbsd-7-nhusb:1.1.1.6.2.1.0.4
	netbsd-7-nhusb-base:1.1.1.6.2.1
	clang-280599:1.1.1.8
	pgoyette-localcount-20160806:1.1.1.8
	pgoyette-localcount-20160726:1.1.1.8
	pgoyette-localcount:1.1.1.8.0.2
	pgoyette-localcount-base:1.1.1.8
	netbsd-7-0-1-RELEASE:1.1.1.6.2.1
	clang-261930:1.1.1.8
	netbsd-7-0:1.1.1.6.2.1.0.2
	netbsd-7-0-RELEASE:1.1.1.6.2.1
	netbsd-7-0-RC3:1.1.1.6.2.1
	netbsd-7-0-RC2:1.1.1.6.2.1
	netbsd-7-0-RC1:1.1.1.6.2.1
	clang-237755:1.1.1.7
	clang-232565:1.1.1.7
	clang-227398:1.1.1.7
	tls-maxphys-base:1.1.1.6
	tls-maxphys:1.1.1.6.0.4
	netbsd-7:1.1.1.6.0.2
	netbsd-7-base:1.1.1.6
	clang-215315:1.1.1.6
	clang-209886:1.1.1.5
	yamt-pagecache:1.1.1.4.0.4
	yamt-pagecache-base9:1.1.1.4
	tls-earlyentropy:1.1.1.4.0.2
	tls-earlyentropy-base:1.1.1.5
	riastradh-xf86-video-intel-2-7-1-pre-2-21-15:1.1.1.4
	riastradh-drm2-base3:1.1.1.4
	clang-202566:1.1.1.4
	clang-201163:1.1.1.3
	clang-199312:1.1.1.2
	clang-198450:1.1.1.1
	clang-196603:1.1.1.1
	clang-195771:1.1.1.1
	LLVM:1.1.1;
locks; strict;
comment	@// @;


1.1
date	2013.11.28.14.14.49;	author joerg;	state Exp;
branches
	1.1.1.1;
next	;
commitid	ow8OybrawrB1f3fx;

1.1.1.1
date	2013.11.28.14.14.49;	author joerg;	state Exp;
branches;
next	1.1.1.2;
commitid	ow8OybrawrB1f3fx;

1.1.1.2
date	2014.01.15.21.26.19;	author joerg;	state Exp;
branches;
next	1.1.1.3;
commitid	NQXlzzA0SPkc5glx;

1.1.1.3
date	2014.02.14.20.07.06;	author joerg;	state Exp;
branches;
next	1.1.1.4;
commitid	annVkZ1sc17rF6px;

1.1.1.4
date	2014.03.04.19.53.38;	author joerg;	state Exp;
branches
	1.1.1.4.2.1
	1.1.1.4.4.1;
next	1.1.1.5;
commitid	29z1hJonZISIXprx;

1.1.1.5
date	2014.05.30.18.14.39;	author joerg;	state Exp;
branches;
next	1.1.1.6;
commitid	8q0kdlBlCn09GACx;

1.1.1.6
date	2014.08.10.17.08.26;	author joerg;	state Exp;
branches
	1.1.1.6.2.1
	1.1.1.6.4.1;
next	1.1.1.7;
commitid	N85tXAN6Ex9VZPLx;

1.1.1.7
date	2015.01.29.19.57.32;	author joerg;	state Exp;
branches;
next	1.1.1.8;
commitid	mlISSizlPKvepX7y;

1.1.1.8
date	2016.02.27.22.11.52;	author joerg;	state Exp;
branches
	1.1.1.8.2.1;
next	1.1.1.9;
commitid	tIimz3oDlh1NpBWy;

1.1.1.9
date	2017.01.11.10.35.31;	author joerg;	state Exp;
branches
	1.1.1.9.14.1;
next	1.1.1.10;
commitid	CNnUNfII1jgNmxBz;

1.1.1.10
date	2019.11.13.22.19.19;	author joerg;	state dead;
branches;
next	;
commitid	QD8YATxuNG34YJKB;

1.1.1.4.2.1
date	2014.08.10.07.08.06;	author tls;	state Exp;
branches;
next	;
commitid	t01A1TLTYxkpGMLx;

1.1.1.4.4.1
date	2014.03.04.19.53.38;	author yamt;	state dead;
branches;
next	1.1.1.4.4.2;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.4.4.2
date	2014.05.22.16.18.25;	author yamt;	state Exp;
branches;
next	;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.6.2.1
date	2015.06.04.20.04.26;	author snj;	state Exp;
branches;
next	;
commitid	yRnjq9fueSo6n9oy;

1.1.1.6.4.1
date	2014.08.10.17.08.26;	author tls;	state dead;
branches;
next	1.1.1.6.4.2;
commitid	jTnpym9Qu0o4R1Nx;

1.1.1.6.4.2
date	2014.08.19.23.47.25;	author tls;	state Exp;
branches;
next	;
commitid	jTnpym9Qu0o4R1Nx;

1.1.1.8.2.1
date	2017.03.20.06.52.35;	author pgoyette;	state Exp;
branches;
next	;
commitid	jjw7cAwgyKq7RfKz;

1.1.1.9.14.1
date	2020.04.13.07.46.29;	author martin;	state dead;
branches;
next	;
commitid	X01YhRUPVUDaec4C;


desc
@@


1.1
log
@Initial revision
@
text
@//===--- FileRemapper.cpp - File Remapping Helper -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/ARCMigrate/FileRemapper.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <fstream>

using namespace clang;
using namespace arcmt;

FileRemapper::FileRemapper() {
  FileMgr.reset(new FileManager(FileSystemOptions()));
}

FileRemapper::~FileRemapper() {
  clear();
}

void FileRemapper::clear(StringRef outputDir) {
  for (MappingsTy::iterator
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I)
    resetTarget(I->second);
  FromToMappings.clear();
  assert(ToFromMappings.empty());
  if (!outputDir.empty()) {
    std::string infoFile = getRemapInfoFile(outputDir);
    bool existed;
    llvm::sys::fs::remove(infoFile, existed);
  }
}

std::string FileRemapper::getRemapInfoFile(StringRef outputDir) {
  assert(!outputDir.empty());
  SmallString<128> InfoFile = outputDir;
  llvm::sys::path::append(InfoFile, "remap");
  return InfoFile.str();
}

bool FileRemapper::initFromDisk(StringRef outputDir, DiagnosticsEngine &Diag,
                                bool ignoreIfFilesChanged) {
  std::string infoFile = getRemapInfoFile(outputDir);
  return initFromFile(infoFile, Diag, ignoreIfFilesChanged);
}

bool FileRemapper::initFromFile(StringRef filePath, DiagnosticsEngine &Diag,
                                bool ignoreIfFilesChanged) {
  assert(FromToMappings.empty() &&
         "initFromDisk should be called before any remap calls");
  std::string infoFile = filePath;
  bool fileExists = false;
  llvm::sys::fs::exists(infoFile, fileExists);
  if (!fileExists)
    return false;

  std::vector<std::pair<const FileEntry *, const FileEntry *> > pairs;
  
  OwningPtr<llvm::MemoryBuffer> fileBuf;
  if (llvm::MemoryBuffer::getFile(infoFile.c_str(), fileBuf))
    return report("Error opening file: " + infoFile, Diag);
  
  SmallVector<StringRef, 64> lines;
  fileBuf->getBuffer().split(lines, "\n");

  for (unsigned idx = 0; idx+3 <= lines.size(); idx += 3) {
    StringRef fromFilename = lines[idx];
    unsigned long long timeModified;
    if (lines[idx+1].getAsInteger(10, timeModified))
      return report("Invalid file data: '" + lines[idx+1] + "' not a number",
                    Diag);
    StringRef toFilename = lines[idx+2];
    
    const FileEntry *origFE = FileMgr->getFile(fromFilename);
    if (!origFE) {
      if (ignoreIfFilesChanged)
        continue;
      return report("File does not exist: " + fromFilename, Diag);
    }
    const FileEntry *newFE = FileMgr->getFile(toFilename);
    if (!newFE) {
      if (ignoreIfFilesChanged)
        continue;
      return report("File does not exist: " + toFilename, Diag);
    }

    if ((uint64_t)origFE->getModificationTime() != timeModified) {
      if (ignoreIfFilesChanged)
        continue;
      return report("File was modified: " + fromFilename, Diag);
    }

    pairs.push_back(std::make_pair(origFE, newFE));
  }

  for (unsigned i = 0, e = pairs.size(); i != e; ++i)
    remap(pairs[i].first, pairs[i].second);

  return false;
}

bool FileRemapper::flushToDisk(StringRef outputDir, DiagnosticsEngine &Diag) {
  using namespace llvm::sys;

  bool existed;
  if (fs::create_directory(outputDir, existed) != llvm::errc::success)
    return report("Could not create directory: " + outputDir, Diag);

  std::string infoFile = getRemapInfoFile(outputDir);
  return flushToFile(infoFile, Diag);
}

bool FileRemapper::flushToFile(StringRef outputPath, DiagnosticsEngine &Diag) {
  using namespace llvm::sys;

  std::string errMsg;
  std::string infoFile = outputPath;
  llvm::raw_fd_ostream infoOut(infoFile.c_str(), errMsg,
                               llvm::sys::fs::F_Binary);
  if (!errMsg.empty())
    return report(errMsg, Diag);

  for (MappingsTy::iterator
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) {

    const FileEntry *origFE = I->first;
    SmallString<200> origPath = StringRef(origFE->getName());
    fs::make_absolute(origPath);
    infoOut << origPath << '\n';
    infoOut << (uint64_t)origFE->getModificationTime() << '\n';

    if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) {
      SmallString<200> newPath = StringRef(FE->getName());
      fs::make_absolute(newPath);
      infoOut << newPath << '\n';
    } else {

      SmallString<64> tempPath;
      int fd;
      if (fs::createTemporaryFile(path::filename(origFE->getName()),
                                  path::extension(origFE->getName()), fd,
                                  tempPath))
        return report("Could not create file: " + tempPath.str(), Diag);

      llvm::raw_fd_ostream newOut(fd, /*shouldClose=*/true);
      llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>();
      newOut.write(mem->getBufferStart(), mem->getBufferSize());
      newOut.close();
      
      const FileEntry *newE = FileMgr->getFile(tempPath);
      remap(origFE, newE);
      infoOut << newE->getName() << '\n';
    }
  }

  infoOut.close();
  return false;
}

bool FileRemapper::overwriteOriginal(DiagnosticsEngine &Diag,
                                     StringRef outputDir) {
  using namespace llvm::sys;

  for (MappingsTy::iterator
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) {
    const FileEntry *origFE = I->first;
    assert(I->second.is<llvm::MemoryBuffer *>());
    bool fileExists = false;
    fs::exists(origFE->getName(), fileExists);
    if (!fileExists)
      return report(StringRef("File does not exist: ") + origFE->getName(),
                    Diag);

    std::string errMsg;
    llvm::raw_fd_ostream Out(origFE->getName(), errMsg,
                             llvm::sys::fs::F_Binary);
    if (!errMsg.empty())
      return report(errMsg, Diag);

    llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>();
    Out.write(mem->getBufferStart(), mem->getBufferSize());
    Out.close();
  }

  clear(outputDir);
  return false;
}

void FileRemapper::applyMappings(PreprocessorOptions &PPOpts) const {
  for (MappingsTy::const_iterator
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) {
    if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) {
      PPOpts.addRemappedFile(I->first->getName(), FE->getName());
    } else {
      llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>();
      PPOpts.addRemappedFile(I->first->getName(), mem);
    }
  }

  PPOpts.RetainRemappedFileBuffers = true;
}

void FileRemapper::transferMappingsAndClear(PreprocessorOptions &PPOpts) {
  for (MappingsTy::iterator
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) {
    if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) {
      PPOpts.addRemappedFile(I->first->getName(), FE->getName());
    } else {
      llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>();
      PPOpts.addRemappedFile(I->first->getName(), mem);
    }
    I->second = Target();
  }

  PPOpts.RetainRemappedFileBuffers = false;
  clear();
}

void FileRemapper::remap(StringRef filePath, llvm::MemoryBuffer *memBuf) {
  remap(getOriginalFile(filePath), memBuf);
}

void FileRemapper::remap(const FileEntry *file, llvm::MemoryBuffer *memBuf) {
  assert(file);
  Target &targ = FromToMappings[file];
  resetTarget(targ);
  targ = memBuf;
}

void FileRemapper::remap(const FileEntry *file, const FileEntry *newfile) {
  assert(file && newfile);
  Target &targ = FromToMappings[file];
  resetTarget(targ);
  targ = newfile;
  ToFromMappings[newfile] = file;
}

const FileEntry *FileRemapper::getOriginalFile(StringRef filePath) {
  const FileEntry *file = FileMgr->getFile(filePath);
  // If we are updating a file that overriden an original file,
  // actually update the original file.
  llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
    I = ToFromMappings.find(file);
  if (I != ToFromMappings.end()) {
    file = I->second;
    assert(FromToMappings.find(file) != FromToMappings.end() &&
           "Original file not in mappings!");
  }
  return file;
}

void FileRemapper::resetTarget(Target &targ) {
  if (!targ)
    return;

  if (llvm::MemoryBuffer *oldmem = targ.dyn_cast<llvm::MemoryBuffer *>()) {
    delete oldmem;
  } else {
    const FileEntry *toFE = targ.get<const FileEntry *>();
    ToFromMappings.erase(toFE);
  }
}

bool FileRemapper::report(const Twine &err, DiagnosticsEngine &Diag) {
  SmallString<128> buf;
  unsigned ID = Diag.getDiagnosticIDs()->getCustomDiagID(DiagnosticIDs::Error,
                                                         err.toStringRef(buf));
  Diag.Report(ID);
  return true;
}
@


1.1.1.1
log
@Import Clang 3.4rc1 r195771.
@
text
@@


1.1.1.2
log
@Import Clang 3.5svn r199312
@
text
@d39 2
a40 1
    llvm::sys::fs::remove(infoFile);
@


1.1.1.3
log
@Import Clang 3.5svn r201163.
@
text
@d274 4
a277 2
  Diag.Report(Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
      << err.str();
@


1.1.1.4
log
@Import Clang 3.5svn r202566.
@
text
@d114 2
a115 1
  if (fs::create_directory(outputDir) != llvm::errc::success)
d127 2
a128 1
  llvm::raw_fd_ostream infoOut(infoFile.c_str(), errMsg, llvm::sys::fs::F_None);
d184 2
a185 1
    llvm::raw_fd_ostream Out(origFE->getName(), errMsg, llvm::sys::fs::F_None);
@


1.1.1.4.2.1
log
@Rebase.
@
text
@d67 2
a68 2

  std::unique_ptr<llvm::MemoryBuffer> fileBuf;
@


1.1.1.5
log
@Import Clang 3.5svn r209886.
@
text
@d67 2
a68 2

  std::unique_ptr<llvm::MemoryBuffer> fileBuf;
@


1.1.1.6
log
@Import clang 3.6svn r215315.
@
text
@d68 2
a69 3
  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> fileBuf =
      llvm::MemoryBuffer::getFile(infoFile.c_str());
  if (!fileBuf)
d73 1
a73 1
  fileBuf.get()->getBuffer().split(lines, "\n");
d114 1
a114 1
  if (fs::create_directory(outputDir))
d209 16
@


1.1.1.6.2.1
log
@Update LLVM to 3.6.1, requested by joerg in ticket 824.
@
text
@d61 3
a63 1
  if (!llvm::sys::fs::exists(infoFile))
d125 1
a125 1
  std::error_code EC;
d127 3
a129 3
  llvm::raw_fd_ostream infoOut(infoFile, EC, llvm::sys::fs::F_None);
  if (EC)
    return report(EC.message(), Diag);
d176 3
a178 1
    if (!fs::exists(origFE->getName()))
d182 4
a185 4
    std::error_code EC;
    llvm::raw_fd_ostream Out(origFE->getName(), EC, llvm::sys::fs::F_None);
    if (EC)
      return report(EC.message(), Diag);
d210 2
a211 3
void FileRemapper::remap(StringRef filePath,
                         std::unique_ptr<llvm::MemoryBuffer> memBuf) {
  remap(getOriginalFile(filePath), std::move(memBuf));
d214 1
a214 2
void FileRemapper::remap(const FileEntry *file,
                         std::unique_ptr<llvm::MemoryBuffer> memBuf) {
d218 1
a218 1
  targ = memBuf.release();
@


1.1.1.7
log
@Import Clang 3.6RC1 r227398.
@
text
@d61 3
a63 1
  if (!llvm::sys::fs::exists(infoFile))
d125 1
a125 1
  std::error_code EC;
d127 3
a129 3
  llvm::raw_fd_ostream infoOut(infoFile, EC, llvm::sys::fs::F_None);
  if (EC)
    return report(EC.message(), Diag);
d176 3
a178 1
    if (!fs::exists(origFE->getName()))
d182 4
a185 4
    std::error_code EC;
    llvm::raw_fd_ostream Out(origFE->getName(), EC, llvm::sys::fs::F_None);
    if (EC)
      return report(EC.message(), Diag);
d210 2
a211 3
void FileRemapper::remap(StringRef filePath,
                         std::unique_ptr<llvm::MemoryBuffer> memBuf) {
  remap(getOriginalFile(filePath), std::move(memBuf));
d214 1
a214 2
void FileRemapper::remap(const FileEntry *file,
                         std::unique_ptr<llvm::MemoryBuffer> memBuf) {
d218 1
a218 1
  targ = memBuf.release();
@


1.1.1.8
log
@Import Clang 3.8.0rc3 r261930.
@
text
@d147 1
a147 1
                                  path::extension(origFE->getName()).drop_front(), fd,
@


1.1.1.8.2.1
log
@Sync with HEAD
@
text
@d67 1
a67 1
      llvm::MemoryBuffer::getFile(infoFile);
@


1.1.1.9
log
@Import Clang pre-4.0.0 r291444.
@
text
@d67 1
a67 1
      llvm::MemoryBuffer::getFile(infoFile);
@


1.1.1.9.14.1
log
@Mostly merge changes from HEAD upto 20200411
@
text
@@


1.1.1.10
log
@Mark old LLVM instance as dead.
@
text
@@


1.1.1.6.4.1
log
@file FileRemapper.cpp was added on branch tls-maxphys on 2014-08-19 23:47:25 +0000
@
text
@d1 259
@


1.1.1.6.4.2
log
@Rebase to HEAD as of a few days ago.
@
text
@a0 259
//===--- FileRemapper.cpp - File Remapping Helper -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/ARCMigrate/FileRemapper.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <fstream>

using namespace clang;
using namespace arcmt;

FileRemapper::FileRemapper() {
  FileMgr.reset(new FileManager(FileSystemOptions()));
}

FileRemapper::~FileRemapper() {
  clear();
}

void FileRemapper::clear(StringRef outputDir) {
  for (MappingsTy::iterator
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I)
    resetTarget(I->second);
  FromToMappings.clear();
  assert(ToFromMappings.empty());
  if (!outputDir.empty()) {
    std::string infoFile = getRemapInfoFile(outputDir);
    llvm::sys::fs::remove(infoFile);
  }
}

std::string FileRemapper::getRemapInfoFile(StringRef outputDir) {
  assert(!outputDir.empty());
  SmallString<128> InfoFile = outputDir;
  llvm::sys::path::append(InfoFile, "remap");
  return InfoFile.str();
}

bool FileRemapper::initFromDisk(StringRef outputDir, DiagnosticsEngine &Diag,
                                bool ignoreIfFilesChanged) {
  std::string infoFile = getRemapInfoFile(outputDir);
  return initFromFile(infoFile, Diag, ignoreIfFilesChanged);
}

bool FileRemapper::initFromFile(StringRef filePath, DiagnosticsEngine &Diag,
                                bool ignoreIfFilesChanged) {
  assert(FromToMappings.empty() &&
         "initFromDisk should be called before any remap calls");
  std::string infoFile = filePath;
  bool fileExists = false;
  llvm::sys::fs::exists(infoFile, fileExists);
  if (!fileExists)
    return false;

  std::vector<std::pair<const FileEntry *, const FileEntry *> > pairs;

  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> fileBuf =
      llvm::MemoryBuffer::getFile(infoFile.c_str());
  if (!fileBuf)
    return report("Error opening file: " + infoFile, Diag);
  
  SmallVector<StringRef, 64> lines;
  fileBuf.get()->getBuffer().split(lines, "\n");

  for (unsigned idx = 0; idx+3 <= lines.size(); idx += 3) {
    StringRef fromFilename = lines[idx];
    unsigned long long timeModified;
    if (lines[idx+1].getAsInteger(10, timeModified))
      return report("Invalid file data: '" + lines[idx+1] + "' not a number",
                    Diag);
    StringRef toFilename = lines[idx+2];
    
    const FileEntry *origFE = FileMgr->getFile(fromFilename);
    if (!origFE) {
      if (ignoreIfFilesChanged)
        continue;
      return report("File does not exist: " + fromFilename, Diag);
    }
    const FileEntry *newFE = FileMgr->getFile(toFilename);
    if (!newFE) {
      if (ignoreIfFilesChanged)
        continue;
      return report("File does not exist: " + toFilename, Diag);
    }

    if ((uint64_t)origFE->getModificationTime() != timeModified) {
      if (ignoreIfFilesChanged)
        continue;
      return report("File was modified: " + fromFilename, Diag);
    }

    pairs.push_back(std::make_pair(origFE, newFE));
  }

  for (unsigned i = 0, e = pairs.size(); i != e; ++i)
    remap(pairs[i].first, pairs[i].second);

  return false;
}

bool FileRemapper::flushToDisk(StringRef outputDir, DiagnosticsEngine &Diag) {
  using namespace llvm::sys;

  if (fs::create_directory(outputDir))
    return report("Could not create directory: " + outputDir, Diag);

  std::string infoFile = getRemapInfoFile(outputDir);
  return flushToFile(infoFile, Diag);
}

bool FileRemapper::flushToFile(StringRef outputPath, DiagnosticsEngine &Diag) {
  using namespace llvm::sys;

  std::string errMsg;
  std::string infoFile = outputPath;
  llvm::raw_fd_ostream infoOut(infoFile.c_str(), errMsg, llvm::sys::fs::F_None);
  if (!errMsg.empty())
    return report(errMsg, Diag);

  for (MappingsTy::iterator
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) {

    const FileEntry *origFE = I->first;
    SmallString<200> origPath = StringRef(origFE->getName());
    fs::make_absolute(origPath);
    infoOut << origPath << '\n';
    infoOut << (uint64_t)origFE->getModificationTime() << '\n';

    if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) {
      SmallString<200> newPath = StringRef(FE->getName());
      fs::make_absolute(newPath);
      infoOut << newPath << '\n';
    } else {

      SmallString<64> tempPath;
      int fd;
      if (fs::createTemporaryFile(path::filename(origFE->getName()),
                                  path::extension(origFE->getName()), fd,
                                  tempPath))
        return report("Could not create file: " + tempPath.str(), Diag);

      llvm::raw_fd_ostream newOut(fd, /*shouldClose=*/true);
      llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>();
      newOut.write(mem->getBufferStart(), mem->getBufferSize());
      newOut.close();
      
      const FileEntry *newE = FileMgr->getFile(tempPath);
      remap(origFE, newE);
      infoOut << newE->getName() << '\n';
    }
  }

  infoOut.close();
  return false;
}

bool FileRemapper::overwriteOriginal(DiagnosticsEngine &Diag,
                                     StringRef outputDir) {
  using namespace llvm::sys;

  for (MappingsTy::iterator
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) {
    const FileEntry *origFE = I->first;
    assert(I->second.is<llvm::MemoryBuffer *>());
    bool fileExists = false;
    fs::exists(origFE->getName(), fileExists);
    if (!fileExists)
      return report(StringRef("File does not exist: ") + origFE->getName(),
                    Diag);

    std::string errMsg;
    llvm::raw_fd_ostream Out(origFE->getName(), errMsg, llvm::sys::fs::F_None);
    if (!errMsg.empty())
      return report(errMsg, Diag);

    llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>();
    Out.write(mem->getBufferStart(), mem->getBufferSize());
    Out.close();
  }

  clear(outputDir);
  return false;
}

void FileRemapper::applyMappings(PreprocessorOptions &PPOpts) const {
  for (MappingsTy::const_iterator
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) {
    if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) {
      PPOpts.addRemappedFile(I->first->getName(), FE->getName());
    } else {
      llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>();
      PPOpts.addRemappedFile(I->first->getName(), mem);
    }
  }

  PPOpts.RetainRemappedFileBuffers = true;
}

void FileRemapper::remap(StringRef filePath, llvm::MemoryBuffer *memBuf) {
  remap(getOriginalFile(filePath), memBuf);
}

void FileRemapper::remap(const FileEntry *file, llvm::MemoryBuffer *memBuf) {
  assert(file);
  Target &targ = FromToMappings[file];
  resetTarget(targ);
  targ = memBuf;
}

void FileRemapper::remap(const FileEntry *file, const FileEntry *newfile) {
  assert(file && newfile);
  Target &targ = FromToMappings[file];
  resetTarget(targ);
  targ = newfile;
  ToFromMappings[newfile] = file;
}

const FileEntry *FileRemapper::getOriginalFile(StringRef filePath) {
  const FileEntry *file = FileMgr->getFile(filePath);
  // If we are updating a file that overriden an original file,
  // actually update the original file.
  llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
    I = ToFromMappings.find(file);
  if (I != ToFromMappings.end()) {
    file = I->second;
    assert(FromToMappings.find(file) != FromToMappings.end() &&
           "Original file not in mappings!");
  }
  return file;
}

void FileRemapper::resetTarget(Target &targ) {
  if (!targ)
    return;

  if (llvm::MemoryBuffer *oldmem = targ.dyn_cast<llvm::MemoryBuffer *>()) {
    delete oldmem;
  } else {
    const FileEntry *toFE = targ.get<const FileEntry *>();
    ToFromMappings.erase(toFE);
  }
}

bool FileRemapper::report(const Twine &err, DiagnosticsEngine &Diag) {
  Diag.Report(Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
      << err.str();
  return true;
}
@


1.1.1.4.4.1
log
@file FileRemapper.cpp was added on branch yamt-pagecache on 2014-05-22 16:18:25 +0000
@
text
@d1 274
@


1.1.1.4.4.2
log
@sync with head.

for a reference, the tree before this commit was tagged
as yamt-pagecache-tag8.

this commit was splitted into small chunks to avoid
a limitation of cvs.  ("Protocol error: too many arguments")
@
text
@a0 274
//===--- FileRemapper.cpp - File Remapping Helper -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/ARCMigrate/FileRemapper.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <fstream>

using namespace clang;
using namespace arcmt;

FileRemapper::FileRemapper() {
  FileMgr.reset(new FileManager(FileSystemOptions()));
}

FileRemapper::~FileRemapper() {
  clear();
}

void FileRemapper::clear(StringRef outputDir) {
  for (MappingsTy::iterator
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I)
    resetTarget(I->second);
  FromToMappings.clear();
  assert(ToFromMappings.empty());
  if (!outputDir.empty()) {
    std::string infoFile = getRemapInfoFile(outputDir);
    llvm::sys::fs::remove(infoFile);
  }
}

std::string FileRemapper::getRemapInfoFile(StringRef outputDir) {
  assert(!outputDir.empty());
  SmallString<128> InfoFile = outputDir;
  llvm::sys::path::append(InfoFile, "remap");
  return InfoFile.str();
}

bool FileRemapper::initFromDisk(StringRef outputDir, DiagnosticsEngine &Diag,
                                bool ignoreIfFilesChanged) {
  std::string infoFile = getRemapInfoFile(outputDir);
  return initFromFile(infoFile, Diag, ignoreIfFilesChanged);
}

bool FileRemapper::initFromFile(StringRef filePath, DiagnosticsEngine &Diag,
                                bool ignoreIfFilesChanged) {
  assert(FromToMappings.empty() &&
         "initFromDisk should be called before any remap calls");
  std::string infoFile = filePath;
  bool fileExists = false;
  llvm::sys::fs::exists(infoFile, fileExists);
  if (!fileExists)
    return false;

  std::vector<std::pair<const FileEntry *, const FileEntry *> > pairs;
  
  OwningPtr<llvm::MemoryBuffer> fileBuf;
  if (llvm::MemoryBuffer::getFile(infoFile.c_str(), fileBuf))
    return report("Error opening file: " + infoFile, Diag);
  
  SmallVector<StringRef, 64> lines;
  fileBuf->getBuffer().split(lines, "\n");

  for (unsigned idx = 0; idx+3 <= lines.size(); idx += 3) {
    StringRef fromFilename = lines[idx];
    unsigned long long timeModified;
    if (lines[idx+1].getAsInteger(10, timeModified))
      return report("Invalid file data: '" + lines[idx+1] + "' not a number",
                    Diag);
    StringRef toFilename = lines[idx+2];
    
    const FileEntry *origFE = FileMgr->getFile(fromFilename);
    if (!origFE) {
      if (ignoreIfFilesChanged)
        continue;
      return report("File does not exist: " + fromFilename, Diag);
    }
    const FileEntry *newFE = FileMgr->getFile(toFilename);
    if (!newFE) {
      if (ignoreIfFilesChanged)
        continue;
      return report("File does not exist: " + toFilename, Diag);
    }

    if ((uint64_t)origFE->getModificationTime() != timeModified) {
      if (ignoreIfFilesChanged)
        continue;
      return report("File was modified: " + fromFilename, Diag);
    }

    pairs.push_back(std::make_pair(origFE, newFE));
  }

  for (unsigned i = 0, e = pairs.size(); i != e; ++i)
    remap(pairs[i].first, pairs[i].second);

  return false;
}

bool FileRemapper::flushToDisk(StringRef outputDir, DiagnosticsEngine &Diag) {
  using namespace llvm::sys;

  if (fs::create_directory(outputDir) != llvm::errc::success)
    return report("Could not create directory: " + outputDir, Diag);

  std::string infoFile = getRemapInfoFile(outputDir);
  return flushToFile(infoFile, Diag);
}

bool FileRemapper::flushToFile(StringRef outputPath, DiagnosticsEngine &Diag) {
  using namespace llvm::sys;

  std::string errMsg;
  std::string infoFile = outputPath;
  llvm::raw_fd_ostream infoOut(infoFile.c_str(), errMsg, llvm::sys::fs::F_None);
  if (!errMsg.empty())
    return report(errMsg, Diag);

  for (MappingsTy::iterator
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) {

    const FileEntry *origFE = I->first;
    SmallString<200> origPath = StringRef(origFE->getName());
    fs::make_absolute(origPath);
    infoOut << origPath << '\n';
    infoOut << (uint64_t)origFE->getModificationTime() << '\n';

    if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) {
      SmallString<200> newPath = StringRef(FE->getName());
      fs::make_absolute(newPath);
      infoOut << newPath << '\n';
    } else {

      SmallString<64> tempPath;
      int fd;
      if (fs::createTemporaryFile(path::filename(origFE->getName()),
                                  path::extension(origFE->getName()), fd,
                                  tempPath))
        return report("Could not create file: " + tempPath.str(), Diag);

      llvm::raw_fd_ostream newOut(fd, /*shouldClose=*/true);
      llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>();
      newOut.write(mem->getBufferStart(), mem->getBufferSize());
      newOut.close();
      
      const FileEntry *newE = FileMgr->getFile(tempPath);
      remap(origFE, newE);
      infoOut << newE->getName() << '\n';
    }
  }

  infoOut.close();
  return false;
}

bool FileRemapper::overwriteOriginal(DiagnosticsEngine &Diag,
                                     StringRef outputDir) {
  using namespace llvm::sys;

  for (MappingsTy::iterator
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) {
    const FileEntry *origFE = I->first;
    assert(I->second.is<llvm::MemoryBuffer *>());
    bool fileExists = false;
    fs::exists(origFE->getName(), fileExists);
    if (!fileExists)
      return report(StringRef("File does not exist: ") + origFE->getName(),
                    Diag);

    std::string errMsg;
    llvm::raw_fd_ostream Out(origFE->getName(), errMsg, llvm::sys::fs::F_None);
    if (!errMsg.empty())
      return report(errMsg, Diag);

    llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>();
    Out.write(mem->getBufferStart(), mem->getBufferSize());
    Out.close();
  }

  clear(outputDir);
  return false;
}

void FileRemapper::applyMappings(PreprocessorOptions &PPOpts) const {
  for (MappingsTy::const_iterator
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) {
    if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) {
      PPOpts.addRemappedFile(I->first->getName(), FE->getName());
    } else {
      llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>();
      PPOpts.addRemappedFile(I->first->getName(), mem);
    }
  }

  PPOpts.RetainRemappedFileBuffers = true;
}

void FileRemapper::transferMappingsAndClear(PreprocessorOptions &PPOpts) {
  for (MappingsTy::iterator
         I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) {
    if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) {
      PPOpts.addRemappedFile(I->first->getName(), FE->getName());
    } else {
      llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>();
      PPOpts.addRemappedFile(I->first->getName(), mem);
    }
    I->second = Target();
  }

  PPOpts.RetainRemappedFileBuffers = false;
  clear();
}

void FileRemapper::remap(StringRef filePath, llvm::MemoryBuffer *memBuf) {
  remap(getOriginalFile(filePath), memBuf);
}

void FileRemapper::remap(const FileEntry *file, llvm::MemoryBuffer *memBuf) {
  assert(file);
  Target &targ = FromToMappings[file];
  resetTarget(targ);
  targ = memBuf;
}

void FileRemapper::remap(const FileEntry *file, const FileEntry *newfile) {
  assert(file && newfile);
  Target &targ = FromToMappings[file];
  resetTarget(targ);
  targ = newfile;
  ToFromMappings[newfile] = file;
}

const FileEntry *FileRemapper::getOriginalFile(StringRef filePath) {
  const FileEntry *file = FileMgr->getFile(filePath);
  // If we are updating a file that overriden an original file,
  // actually update the original file.
  llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
    I = ToFromMappings.find(file);
  if (I != ToFromMappings.end()) {
    file = I->second;
    assert(FromToMappings.find(file) != FromToMappings.end() &&
           "Original file not in mappings!");
  }
  return file;
}

void FileRemapper::resetTarget(Target &targ) {
  if (!targ)
    return;

  if (llvm::MemoryBuffer *oldmem = targ.dyn_cast<llvm::MemoryBuffer *>()) {
    delete oldmem;
  } else {
    const FileEntry *toFE = targ.get<const FileEntry *>();
    ToFromMappings.erase(toFE);
  }
}

bool FileRemapper::report(const Twine &err, DiagnosticsEngine &Diag) {
  Diag.Report(Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
      << err.str();
  return true;
}
@


