#include "clang/APINotes/APINotesManager.h"
#include "clang/APINotes/APINotesReader.h"
#include "clang/APINotes/APINotesYAMLCompiler.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/SourceMgrAdapter.h"
#include "clang/Basic/Version.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
using namespace clang;
using namespace api_notes;
#define DEBUG_TYPE "API Notes"
STATISTIC(NumHeaderAPINotes, "non-framework API notes files loaded");
STATISTIC(NumPublicFrameworkAPINotes, "framework public API notes loaded");
STATISTIC(NumPrivateFrameworkAPINotes, "framework private API notes loaded");
STATISTIC(NumFrameworksSearched, "frameworks searched");
STATISTIC(NumDirectoriesSearched, "header directories searched");
STATISTIC(NumDirectoryCacheHits, "directory cache hits");
namespace {
class PrettyStackTraceDoubleString : public llvm::PrettyStackTraceEntry {
StringRef First, Second;
public:
PrettyStackTraceDoubleString(StringRef First, StringRef Second)
: First(First), Second(Second) {}
void print(raw_ostream &OS) const override { OS << First << Second; }
};
}
APINotesManager::APINotesManager(SourceManager &SM, const LangOptions &LangOpts)
: SM(SM), ImplicitAPINotes(LangOpts.APINotes) {}
APINotesManager::~APINotesManager() {
for (const auto &Entry : Readers) {
if (auto Reader = Entry.second.dyn_cast<APINotesReader *>())
delete Reader;
}
delete CurrentModuleReaders[ReaderKind::Public];
delete CurrentModuleReaders[ReaderKind::Private];
}
std::unique_ptr<APINotesReader>
APINotesManager::loadAPINotes(FileEntryRef APINotesFile) {
PrettyStackTraceDoubleString Trace("Loading API notes from ",
APINotesFile.getName());
auto SourceFileID = SM.getOrCreateFileID(APINotesFile, SrcMgr::C_User);
auto SourceBuffer = SM.getBufferOrNone(SourceFileID, SourceLocation());
if (!SourceBuffer)
return nullptr;
llvm::SmallVector<char, 1024> APINotesBuffer;
std::unique_ptr<llvm::MemoryBuffer> CompiledBuffer;
{
SourceMgrAdapter SMAdapter(
SM, SM.getDiagnostics(), diag::err_apinotes_message,
diag::warn_apinotes_message, diag::note_apinotes_message, APINotesFile);
llvm::raw_svector_ostream OS(APINotesBuffer);
if (api_notes::compileAPINotes(
SourceBuffer->getBuffer(), SM.getFileEntryForID(SourceFileID), OS,
SMAdapter.getDiagHandler(), SMAdapter.getDiagContext()))
return nullptr;
CompiledBuffer = llvm::MemoryBuffer::getMemBufferCopy(
StringRef(APINotesBuffer.data(), APINotesBuffer.size()));
}
auto Reader = APINotesReader::Create(std::move(CompiledBuffer), SwiftVersion);
assert(Reader && "Could not load the API notes we just generated?");
return Reader;
}
std::unique_ptr<APINotesReader>
APINotesManager::loadAPINotes(StringRef Buffer) {
llvm::SmallVector<char, 1024> APINotesBuffer;
std::unique_ptr<llvm::MemoryBuffer> CompiledBuffer;
SourceMgrAdapter SMAdapter(
SM, SM.getDiagnostics(), diag::err_apinotes_message,
diag::warn_apinotes_message, diag::note_apinotes_message, std::nullopt);
llvm::raw_svector_ostream OS(APINotesBuffer);
if (api_notes::compileAPINotes(Buffer, nullptr, OS,
SMAdapter.getDiagHandler(),
SMAdapter.getDiagContext()))
return nullptr;
CompiledBuffer = llvm::MemoryBuffer::getMemBufferCopy(
StringRef(APINotesBuffer.data(), APINotesBuffer.size()));
auto Reader = APINotesReader::Create(std::move(CompiledBuffer), SwiftVersion);
assert(Reader && "Could not load the API notes we just generated?");
return Reader;
}
bool APINotesManager::loadAPINotes(const DirectoryEntry *HeaderDir,
FileEntryRef APINotesFile) {
assert(!Readers.contains(HeaderDir));
if (auto Reader = loadAPINotes(APINotesFile)) {
Readers[HeaderDir] = Reader.release();
return false;
}
Readers[HeaderDir] = nullptr;
return true;
}
OptionalFileEntryRef
APINotesManager::findAPINotesFile(DirectoryEntryRef Directory,
StringRef Basename, bool WantPublic) {
FileManager &FM = SM.getFileManager();
llvm::SmallString<128> Path(Directory.getName());
StringRef Suffix = WantPublic ? "" : "_private";
llvm::sys::path::append(Path, llvm::Twine(Basename) + Suffix + "." +
SOURCE_APINOTES_EXTENSION);
return FM.getOptionalFileRef(Path, true);
}
OptionalDirectoryEntryRef APINotesManager::loadFrameworkAPINotes(
llvm::StringRef FrameworkPath, llvm::StringRef FrameworkName, bool Public) {
FileManager &FM = SM.getFileManager();
llvm::SmallString<128> Path(FrameworkPath);
unsigned FrameworkNameLength = Path.size();
StringRef Suffix = Public ? "" : "_private";
llvm::sys::path::append(Path, "APINotes");
llvm::sys::path::append(Path, (llvm::Twine(FrameworkName) + Suffix + "." +
SOURCE_APINOTES_EXTENSION));
auto APINotesFile = FM.getOptionalFileRef(Path);
if (!APINotesFile)
return std::nullopt;
Path.resize(FrameworkNameLength);
llvm::sys::path::append(Path, Public ? "Headers" : "PrivateHeaders");
auto HeaderDir = FM.getOptionalDirectoryRef(Path);
if (!HeaderDir)
return std::nullopt;
if (loadAPINotes(*HeaderDir, *APINotesFile))
return std::nullopt;
if (Public)
++NumPublicFrameworkAPINotes;
else
++NumPrivateFrameworkAPINotes;
return *HeaderDir;
}
static void checkPrivateAPINotesName(DiagnosticsEngine &Diags,
const FileEntry *File, const Module *M) {
if (File->tryGetRealPathName().empty())
return;
StringRef RealFileName =
llvm::sys::path::filename(File->tryGetRealPathName());
StringRef RealStem = llvm::sys::path::stem(RealFileName);
if (RealStem.ends_with("_private"))
return;
unsigned DiagID = diag::warn_apinotes_private_case;
if (M->IsSystem)
DiagID = diag::warn_apinotes_private_case_system;
Diags.Report(SourceLocation(), DiagID) << M->Name << RealFileName;
}
static bool hasPrivateSubmodules(const Module *M) {
return llvm::any_of(M->submodules(), [](const Module *Submodule) {
return Submodule->ModuleMapIsPrivate;
});
}
llvm::SmallVector<FileEntryRef, 2>
APINotesManager::getCurrentModuleAPINotes(Module *M, bool LookInModule,
ArrayRef<std::string> SearchPaths) {
FileManager &FM = SM.getFileManager();
auto ModuleName = M->getTopLevelModuleName();
auto ExportedModuleName = M->getTopLevelModule()->ExportAsModule;
llvm::SmallVector<FileEntryRef, 2> APINotes;
if (LookInModule && M->Directory) {
auto tryAPINotes = [&](DirectoryEntryRef Dir, bool WantPublic) {
if (auto File = findAPINotesFile(Dir, ModuleName, WantPublic)) {
if (!WantPublic)
checkPrivateAPINotesName(SM.getDiagnostics(), *File, M);
APINotes.push_back(*File);
}
if (!ExportedModuleName.empty())
if (auto File = findAPINotesFile(Dir, ExportedModuleName, WantPublic))
APINotes.push_back(*File);
};
if (M->IsFramework) {
llvm::SmallString<128> Path(M->Directory->getName());
if (!M->ModuleMapIsPrivate) {
unsigned PathLen = Path.size();
llvm::sys::path::append(Path, "Headers");
if (auto APINotesDir = FM.getOptionalDirectoryRef(Path))
tryAPINotes(*APINotesDir, true);
Path.resize(PathLen);
}
if (M->ModuleMapIsPrivate || hasPrivateSubmodules(M)) {
llvm::sys::path::append(Path, "PrivateHeaders");
if (auto PrivateAPINotesDir = FM.getOptionalDirectoryRef(Path))
tryAPINotes(*PrivateAPINotesDir,
M->ModuleMapIsPrivate);
}
} else {
tryAPINotes(*M->Directory, true);
if (!M->ModuleMapIsPrivate && hasPrivateSubmodules(M))
tryAPINotes(*M->Directory, false);
}
if (!APINotes.empty())
return APINotes;
}
for (const auto &SearchPath : SearchPaths) {
if (auto SearchDir = FM.getOptionalDirectoryRef(SearchPath)) {
if (auto File = findAPINotesFile(*SearchDir, ModuleName)) {
APINotes.push_back(*File);
return APINotes;
}
}
}
return APINotes;
}
bool APINotesManager::loadCurrentModuleAPINotes(
Module *M, bool LookInModule, ArrayRef<std::string> SearchPaths) {
assert(!CurrentModuleReaders[ReaderKind::Public] &&
"Already loaded API notes for the current module?");
auto APINotes = getCurrentModuleAPINotes(M, LookInModule, SearchPaths);
unsigned NumReaders = 0;
for (auto File : APINotes) {
CurrentModuleReaders[NumReaders++] = loadAPINotes(File).release();
if (!getCurrentModuleReaders().empty())
M->APINotesFile = File.getName().str();
}
return NumReaders > 0;
}
bool APINotesManager::loadCurrentModuleAPINotesFromBuffer(
ArrayRef<StringRef> Buffers) {
unsigned NumReader = 0;
for (auto Buf : Buffers) {
auto Reader = loadAPINotes(Buf);
assert(Reader && "Could not load the API notes we just generated?");
CurrentModuleReaders[NumReader++] = Reader.release();
}
return NumReader;
}
llvm::SmallVector<APINotesReader *, 2>
APINotesManager::findAPINotes(SourceLocation Loc) {
llvm::SmallVector<APINotesReader *, 2> Results;
if (!getCurrentModuleReaders().empty()) {
Results.append(getCurrentModuleReaders().begin(),
getCurrentModuleReaders().end());
return Results;
}
if (!ImplicitAPINotes)
return Results;
if (Loc.isInvalid())
return Results;
SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
FileID ID = SM.getFileID(ExpansionLoc);
if (ID.isInvalid())
return Results;
OptionalFileEntryRef File = SM.getFileEntryRefForID(ID);
if (!File)
return Results;
OptionalDirectoryEntryRef Dir = File->getDir();
FileManager &FileMgr = SM.getFileManager();
llvm::SetVector<const DirectoryEntry *,
SmallVector<const DirectoryEntry *, 4>,
llvm::SmallPtrSet<const DirectoryEntry *, 4>>
DirsVisited;
do {
auto Known = Readers.find(*Dir);
if (Known != Readers.end()) {
++NumDirectoryCacheHits;
if (Known->second && Known->second.is<DirectoryEntryRef>()) {
DirsVisited.insert(*Dir);
Dir = Known->second.get<DirectoryEntryRef>();
continue;
}
if (auto Reader = Known->second.dyn_cast<APINotesReader *>())
Results.push_back(Reader);
break;
}
StringRef Path = Dir->getName();
if (llvm::sys::path::extension(Path) == ".framework") {
auto FrameworkName = llvm::sys::path::stem(Path);
++NumFrameworksSearched;
OptionalDirectoryEntryRef PublicDir =
loadFrameworkAPINotes(Path, FrameworkName, true);
OptionalDirectoryEntryRef PrivateDir =
loadFrameworkAPINotes(Path, FrameworkName, false);
if (PublicDir || PrivateDir) {
Readers[*Dir] = nullptr;
if (!DirsVisited.empty()) {
if (PublicDir && DirsVisited.back() == *PublicDir) {
DirsVisited.pop_back();
Dir = *PublicDir;
} else if (PrivateDir && DirsVisited.back() == *PrivateDir) {
DirsVisited.pop_back();
Dir = *PrivateDir;
}
}
if (auto Reader = Readers[*Dir].dyn_cast<APINotesReader *>())
Results.push_back(Reader);
break;
}
} else {
llvm::SmallString<128> APINotesPath(Dir->getName());
llvm::sys::path::append(
APINotesPath, (llvm::Twine("APINotes.") + SOURCE_APINOTES_EXTENSION));
++NumDirectoriesSearched;
if (auto APINotesFile = FileMgr.getOptionalFileRef(APINotesPath)) {
if (!loadAPINotes(*Dir, *APINotesFile)) {
++NumHeaderAPINotes;
if (auto Reader = Readers[*Dir].dyn_cast<APINotesReader *>())
Results.push_back(Reader);
break;
}
}
}
if (!DirsVisited.insert(*Dir)) {
Dir = std::nullopt;
break;
}
StringRef ParentPath = llvm::sys::path::parent_path(Path);
while (llvm::sys::path::stem(ParentPath) == "..")
ParentPath = llvm::sys::path::parent_path(ParentPath);
Dir = ParentPath.empty() ? std::nullopt
: FileMgr.getOptionalDirectoryRef(ParentPath);
} while (Dir);
for (const auto Visited : DirsVisited)
Readers[Visited] = Dir ? ReaderEntry(*Dir) : ReaderEntry();
return Results;
}