FileManager leaking file descriptors when overriding the contents of a file


I'm trying to find a way to instruct clang to skip some includes
during parsing. The way I currently do it is to write a PPCallbacks
that overrides the InclusionDirective method and if the fileName
matches some criteria I just go:

llvm::MemoryBuffer::getNewMemBuffer(0), false);

(with file being the "const FileEntry*" passed to the
InclusionDirective method and m_sourceManager the SourceManager

This works well except that I noticed that it leaks the file
descriptor. I can see it because just after clang::ParseAST returns I
can see that the process has still the exact list of files I excluded
open (using lsof or equivalent utilities). I found a workaround which
is calling just before overriding the file contents:


This triggers the read from disk + close file handle. This works fine
but does an unnecessary read from disk which I find quite unfortunate.

So I was wondering:

- Should overrideFileContents be fixed to never leak that FD? Even
though in this case I know I'm not supposed to call it during parsing.
- Would there be a better way of doing this which would avoid reading
from the disk at all?