#include "llvm/ADT/Twine.h"
#include "llvm/Config/config.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/ExecutionEngine/JITEventListener.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Object/SymbolSize.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Errno.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Threading.h"
#include "llvm/Support/raw_ostream.h"
#include <mutex>
#include <sys/mman.h>
#include <time.h>
#include <unistd.h>
using namespace llvm;
using namespace llvm::object;
typedef DILineInfoSpecifier::FileLineInfoKind FileLineInfoKind;
namespace {
#define JIT_LANG "llvm-IR"
#define LLVM_PERF_JIT_MAGIC \
((uint32_t)'J' << 24 | (uint32_t)'i' << 16 | (uint32_t)'T' << 8 | \
(uint32_t)'D')
#define LLVM_PERF_JIT_VERSION 1
#define JITDUMP_FLAGS_ARCH_TIMESTAMP (1ULL << 0)
struct LLVMPerfJitHeader;
class PerfJITEventListener : public JITEventListener {
public:
PerfJITEventListener();
~PerfJITEventListener() {
if (MarkerAddr)
CloseMarker();
}
void notifyObjectLoaded(ObjectKey K, const ObjectFile &Obj,
const RuntimeDyld::LoadedObjectInfo &L) override;
void notifyFreeingObject(ObjectKey K) override;
private:
bool InitDebuggingDir();
bool OpenMarker();
void CloseMarker();
static bool FillMachine(LLVMPerfJitHeader &hdr);
void NotifyCode(Expected<llvm::StringRef> &Symbol, uint64_t CodeAddr,
uint64_t CodeSize);
void NotifyDebug(uint64_t CodeAddr, DILineInfoTable Lines);
sys::Process::Pid Pid;
std::string JitPath;
int DumpFd = -1;
std::unique_ptr<raw_fd_ostream> Dumpstream;
sys::Mutex Mutex;
void *MarkerAddr = NULL;
bool SuccessfullyInitialized = false;
uint64_t CodeGeneration = 1;
};
enum LLVMPerfJitRecordType {
JIT_CODE_LOAD = 0,
JIT_CODE_MOVE = 1, JIT_CODE_DEBUG_INFO = 2,
JIT_CODE_CLOSE = 3, JIT_CODE_UNWINDING_INFO = 4,
JIT_CODE_MAX
};
struct LLVMPerfJitHeader {
uint32_t Magic; uint32_t Version; uint32_t TotalSize; uint32_t ElfMach; uint32_t Pad1; uint32_t Pid;
uint64_t Timestamp; uint64_t Flags; };
struct LLVMPerfJitRecordPrefix {
uint32_t Id; uint32_t TotalSize;
uint64_t Timestamp;
};
struct LLVMPerfJitRecordCodeLoad {
LLVMPerfJitRecordPrefix Prefix;
uint32_t Pid;
uint32_t Tid;
uint64_t Vma;
uint64_t CodeAddr;
uint64_t CodeSize;
uint64_t CodeIndex;
};
struct LLVMPerfJitDebugEntry {
uint64_t Addr;
int Lineno; int Discrim; };
struct LLVMPerfJitRecordDebugInfo {
LLVMPerfJitRecordPrefix Prefix;
uint64_t CodeAddr;
uint64_t NrEntry;
};
static inline uint64_t timespec_to_ns(const struct timespec *ts) {
const uint64_t NanoSecPerSec = 1000000000;
return ((uint64_t)ts->tv_sec * NanoSecPerSec) + ts->tv_nsec;
}
static inline uint64_t perf_get_timestamp(void) {
struct timespec ts;
int ret;
ret = clock_gettime(CLOCK_MONOTONIC, &ts);
if (ret)
return 0;
return timespec_to_ns(&ts);
}
PerfJITEventListener::PerfJITEventListener()
: Pid(sys::Process::getProcessId()) {
if (!perf_get_timestamp()) {
errs() << "kernel does not support CLOCK_MONOTONIC\n";
return;
}
if (!InitDebuggingDir()) {
errs() << "could not initialize debugging directory\n";
return;
}
std::string Filename;
raw_string_ostream FilenameBuf(Filename);
FilenameBuf << JitPath << "/jit-" << Pid << ".dump";
using sys::fs::openFileForWrite;
if (auto EC =
openFileForReadWrite(FilenameBuf.str(), DumpFd,
sys::fs::CD_CreateNew, sys::fs::OF_None)) {
errs() << "could not open JIT dump file " << FilenameBuf.str() << ": "
<< EC.message() << "\n";
return;
}
Dumpstream = std::make_unique<raw_fd_ostream>(DumpFd, true);
LLVMPerfJitHeader Header = {0};
if (!FillMachine(Header))
return;
if (!OpenMarker())
return;
Header.Magic = LLVM_PERF_JIT_MAGIC;
Header.Version = LLVM_PERF_JIT_VERSION;
Header.TotalSize = sizeof(Header);
Header.Pid = Pid;
Header.Timestamp = perf_get_timestamp();
Dumpstream->write(reinterpret_cast<const char *>(&Header), sizeof(Header));
if (!Dumpstream->has_error())
SuccessfullyInitialized = true;
}
void PerfJITEventListener::notifyObjectLoaded(
ObjectKey K, const ObjectFile &Obj,
const RuntimeDyld::LoadedObjectInfo &L) {
if (!SuccessfullyInitialized)
return;
OwningBinary<ObjectFile> DebugObjOwner = L.getObjectForDebug(Obj);
const ObjectFile &DebugObj = *DebugObjOwner.getBinary();
std::unique_ptr<DIContext> Context = DWARFContext::create(DebugObj);
for (const std::pair<SymbolRef, uint64_t> &P : computeSymbolSizes(DebugObj)) {
SymbolRef Sym = P.first;
std::string SourceFileName;
Expected<SymbolRef::Type> SymTypeOrErr = Sym.getType();
if (!SymTypeOrErr) {
consumeError(SymTypeOrErr.takeError());
continue;
}
SymbolRef::Type SymType = *SymTypeOrErr;
if (SymType != SymbolRef::ST_Function)
continue;
Expected<StringRef> Name = Sym.getName();
if (!Name) {
consumeError(Name.takeError());
continue;
}
Expected<uint64_t> AddrOrErr = Sym.getAddress();
if (!AddrOrErr) {
consumeError(AddrOrErr.takeError());
continue;
}
uint64_t Size = P.second;
object::SectionedAddress Address;
Address.Address = *AddrOrErr;
uint64_t SectionIndex = object::SectionedAddress::UndefSection;
if (auto SectOrErr = Sym.getSection())
if (*SectOrErr != Obj.section_end())
SectionIndex = SectOrErr.get()->getIndex();
DILineInfoTable Lines = Context->getLineInfoForAddressRange(
{*AddrOrErr, SectionIndex}, Size, FileLineInfoKind::AbsoluteFilePath);
NotifyDebug(*AddrOrErr, Lines);
NotifyCode(Name, *AddrOrErr, Size);
}
std::lock_guard<sys::Mutex> Guard(Mutex);
Dumpstream->flush();
}
void PerfJITEventListener::notifyFreeingObject(ObjectKey K) {
}
bool PerfJITEventListener::InitDebuggingDir() {
time_t Time;
struct tm LocalTime;
char TimeBuffer[sizeof("YYYYMMDD")];
SmallString<64> Path;
if (const char *BaseDir = getenv("JITDUMPDIR"))
Path.append(BaseDir);
else if (!sys::path::home_directory(Path))
Path = ".";
Path += "/.debug/jit/";
if (auto EC = sys::fs::create_directories(Path)) {
errs() << "could not create jit cache directory " << Path << ": "
<< EC.message() << "\n";
return false;
}
time(&Time);
localtime_r(&Time, &LocalTime);
strftime(TimeBuffer, sizeof(TimeBuffer), "%Y%m%d", &LocalTime);
Path += JIT_LANG "-jit-";
Path += TimeBuffer;
SmallString<128> UniqueDebugDir;
using sys::fs::createUniqueDirectory;
if (auto EC = createUniqueDirectory(Path, UniqueDebugDir)) {
errs() << "could not create unique jit cache directory " << UniqueDebugDir
<< ": " << EC.message() << "\n";
return false;
}
JitPath = std::string(UniqueDebugDir.str());
return true;
}
bool PerfJITEventListener::OpenMarker() {
MarkerAddr = ::mmap(NULL, sys::Process::getPageSizeEstimate(),
PROT_READ | PROT_EXEC, MAP_PRIVATE, DumpFd, 0);
if (MarkerAddr == MAP_FAILED) {
errs() << "could not mmap JIT marker\n";
return false;
}
return true;
}
void PerfJITEventListener::CloseMarker() {
if (!MarkerAddr)
return;
munmap(MarkerAddr, sys::Process::getPageSizeEstimate());
MarkerAddr = nullptr;
}
bool PerfJITEventListener::FillMachine(LLVMPerfJitHeader &hdr) {
char id[16];
struct {
uint16_t e_type;
uint16_t e_machine;
} info;
size_t RequiredMemory = sizeof(id) + sizeof(info);
ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
MemoryBuffer::getFileSlice("/proc/self/exe",
RequiredMemory,
0);
if (auto EC = MB.getError()) {
errs() << "could not open /proc/self/exe: " << EC.message() << "\n";
return false;
}
memcpy(&id, (*MB)->getBufferStart(), sizeof(id));
memcpy(&info, (*MB)->getBufferStart() + sizeof(id), sizeof(info));
if (id[0] != 0x7f || id[1] != 'E' || id[2] != 'L' || id[3] != 'F') {
errs() << "invalid elf signature\n";
return false;
}
hdr.ElfMach = info.e_machine;
return true;
}
void PerfJITEventListener::NotifyCode(Expected<llvm::StringRef> &Symbol,
uint64_t CodeAddr, uint64_t CodeSize) {
assert(SuccessfullyInitialized);
if (CodeSize == 0)
return;
LLVMPerfJitRecordCodeLoad rec;
rec.Prefix.Id = JIT_CODE_LOAD;
rec.Prefix.TotalSize = sizeof(rec) + Symbol->size() + 1 + CodeSize; rec.Prefix.Timestamp = perf_get_timestamp();
rec.CodeSize = CodeSize;
rec.Vma = 0;
rec.CodeAddr = CodeAddr;
rec.Pid = Pid;
rec.Tid = get_threadid();
std::lock_guard<sys::Mutex> Guard(Mutex);
rec.CodeIndex = CodeGeneration++;
Dumpstream->write(reinterpret_cast<const char *>(&rec), sizeof(rec));
Dumpstream->write(Symbol->data(), Symbol->size() + 1);
Dumpstream->write(reinterpret_cast<const char *>(CodeAddr), CodeSize);
}
void PerfJITEventListener::NotifyDebug(uint64_t CodeAddr,
DILineInfoTable Lines) {
assert(SuccessfullyInitialized);
if (Lines.empty())
return;
LLVMPerfJitRecordDebugInfo rec;
rec.Prefix.Id = JIT_CODE_DEBUG_INFO;
rec.Prefix.TotalSize = sizeof(rec); rec.Prefix.Timestamp = perf_get_timestamp();
rec.CodeAddr = CodeAddr;
rec.NrEntry = Lines.size();
DILineInfoTable::iterator Begin = Lines.begin();
DILineInfoTable::iterator End = Lines.end();
for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
DILineInfo &line = It->second;
rec.Prefix.TotalSize += sizeof(LLVMPerfJitDebugEntry);
rec.Prefix.TotalSize += line.FileName.size() + 1;
}
std::lock_guard<sys::Mutex> Guard(Mutex);
Dumpstream->write(reinterpret_cast<const char *>(&rec), sizeof(rec));
for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
LLVMPerfJitDebugEntry LineInfo;
DILineInfo &Line = It->second;
LineInfo.Addr = It->first;
LineInfo.Addr += 0x40;
LineInfo.Lineno = Line.Line;
LineInfo.Discrim = Line.Discriminator;
Dumpstream->write(reinterpret_cast<const char *>(&LineInfo),
sizeof(LineInfo));
Dumpstream->write(Line.FileName.c_str(), Line.FileName.size() + 1);
}
}
}
namespace llvm {
JITEventListener *JITEventListener::createPerfJITEventListener() {
static PerfJITEventListener PerfListener;
return &PerfListener;
}
}
LLVMJITEventListenerRef LLVMCreatePerfJITEventListener(void)
{
return wrap(JITEventListener::createPerfJITEventListener());
}