Files

721 lines
28 KiB
C++

// cupti_trace.cpp - thin CUPTI Activity tracer, loadable into ANY CUDA process without modifying it.
//
// CUDA_INJECTION64_PATH=/path/libleleka_cupti_trace.so (the driver loads it at cuInit and calls InitializeInjection)
// LD_PRELOAD=/path/libleleka_cupti_trace.so (the constructor does the same)
// libcupti.so.13 is found through the library's RUNPATH (see build.sh) or LD_LIBRARY_PATH. Tracing is OFF until a window
// is triggered; armed-but-idle cost is one thread that stat()s the trigger path every 50 ms.
//
// Windows (any number per process, one at a time; each writes its own output directory):
// 1. Trigger file (long-lived daemons). LELEKA_CUPTI_TRIGGER=<path> (alias LCT_TRIGGER). Write one JSON line atomically
// (tmp + rename): {"seconds": 8, "out": "/abs/prefix", "label": "free text"}
// The library renames it to <path>.active, records until `seconds` (hard cap LCT_MAX_SECONDS, default 120) or until
// <path>.stop exists, writes <out>.lct/ (the data) and <out>.done (JSON: bytes, counts, unix-ms start/stop), and renames
// <path>.active to <path>.done. A trigger that arrives during a window is left in place and taken after it ends.
// A failure to initialise CUPTI never affects the process: <path>.error gets the reason.
// 2. Environment (one window): LCT_START_AFTER_S=<sec since load>, LCT_START_FILE=<path exists>,
// LCT_START_API=<driver api name or prefix>:<N> (Nth call), LCT_START_SYM=<kernel-name substring>:<N>,
// LCT_DURATION_S, LCT_STOP_FILE, LCT_STOP_API=<name>:<N> (counted after the start). With none of the start triggers and
// no LELEKA_CUPTI_TRIGGER, recording starts at once. Output: $LCT_OUT/lct.<pid>/.
// 3. LCT_SIGNALS=1: SIGUSR1 starts and SIGUSR2 stops the environment window.
// Other: LCT_API=0 (no API records) | 1 (selected: launch/copy/sync/event/graph/alloc, default) | 2 (all);
// LCT_BUF_MB (activity buffer, default 32); LCT_MAX_MB (cap per window, default 3072); LCT_VERBOSE=1.
//
// Window directory (fixed-size little-endian records, one file per kind, multi-MB stdio buffers, no per-record syscalls):
// kernel.bin CONCURRENT_KERNEL incl. graph-launched (graphId/graphNodeId) KRec memcpy.bin MEMCPY + MEMCPY2 CRec
// memset.bin MEMSET MRec sync.bin SYNCHRONIZATION (stream/event/context sync, stream wait) YRec
// api.bin DRIVER/RUNTIME API ARec graph.bin GRAPH_TRACE GRec strings.tsv id<TAB>name threads.tsv tid<TAB>comm
// meta.txt clocks (CUPTI ns <-> CLOCK_REALTIME), label, window marks.
#include <cupti.h>
#include <cupti_callbacks.h>
#include <cupti_driver_cbid.h>
#include <cupti_runtime_cbid.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <atomic>
#include <cerrno>
#include <chrono>
#include <csignal>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#pragma pack(push, 1)
struct KRec { // 80 bytes
uint64_t start, end;
uint32_t dev, stream, corr, graphId;
uint64_t graphNodeId;
uint32_t nameId;
int32_t gx, gy, gz, bx, by, bz;
int32_t sshm, dshm;
uint16_t regs;
uint8_t launchType, pad;
};
struct CRec { // 56 bytes
uint64_t start, end, bytes;
uint32_t dev, stream, corr, graphId;
uint64_t graphNodeId;
uint8_t copyKind, srcKind, dstKind, flags;
uint32_t apiCorr;
};
struct MRec { // 48 bytes
uint64_t start, end, bytes;
uint32_t dev, stream, corr, graphId;
uint16_t memKind, pad;
};
struct YRec { // 40 bytes
uint64_t start, end;
uint32_t corr, stream, eventId, type, ctx, ret;
};
struct ARec { // 40 bytes
uint64_t start, end;
uint32_t corr, thread, nameId, ret;
uint8_t domain, pad[3];
};
struct GRec { // 40 bytes
uint64_t start, end;
uint32_t corr, graphId, dev, stream;
};
#pragma pack(pop)
namespace {
struct Out {
FILE* f = nullptr;
std::vector<char> buf;
void open(const std::string& path, size_t bytes) {
f = fopen(path.c_str(), "wb");
if (f) {
buf.assign(bytes, 0);
setvbuf(f, buf.data(), _IOFBF, bytes);
}
}
void put(const void* p, size_t n) {
if (f) fwrite(p, 1, n, f);
}
void flush() {
if (f) fflush(f);
}
void close() {
if (f) fclose(f);
f = nullptr;
std::vector<char>().swap(buf);
}
};
struct Window {
std::string out; // directory
std::string prefix; // for <prefix>.done ("" for env windows)
std::string label, trigger;
double seconds = -1;
bool fromTrigger = false;
};
struct State {
std::mutex mu; // protects the writers, string table and counters
Out kern, copy, mset, sync, api, graph, strs, meta;
std::unordered_map<std::string, uint32_t> strId;
std::unordered_map<uint32_t, uint32_t> apiName[2];
bool winOpen = false;
uint64_t bytesOut = 0, maxBytes = 0;
uint64_t counts[6] = {0, 0, 0, 0, 0, 0};
std::atomic<bool> inited{false}, recording{false}, finished{false}, cuptiOk{false};
std::atomic<bool> reqStart{false}, reqStop{false};
std::atomic<uint64_t> startCnt{0}, stopCnt{0}, startTarget{0}, stopTarget{0}, symCnt{0}, symTarget{0};
std::string symSubstr;
std::vector<CUpti_CallbackId> startIds, stopIds;
CUpti_SubscriberHandle sub = nullptr;
uint64_t winStart = 0;
uint64_t offReal = 0; // CLOCK_REALTIME ns - CUPTI ns
int apiLevel = 1;
bool verbose = false;
size_t bufBytes = 32u << 20;
int winSeq = 0;
std::string trigger, errPath;
};
// leaked on purpose: the watcher thread may still be closing a window while the process exits and static destructors run
State& S = *new State;
const char* envs(const char* k) {
const char* v = getenv(k);
return (v && *v) ? v : nullptr;
}
#define CK(call) \
do { \
CUptiResult _r = (call); \
if (_r != CUPTI_SUCCESS) { \
const char* _m = nullptr; \
cuptiGetResultString(_r, &_m); \
fprintf(stderr, "[lct] %s failed: %s (%d)\n", #call, _m ? _m : "?", (int)_r); \
} \
} while (0)
void writeFile(const std::string& path, const std::string& body) {
FILE* f = fopen(path.c_str(), "w");
if (!f) return;
fwrite(body.data(), 1, body.size(), f);
fclose(f);
}
void mkdirs(const std::string& p) {
for (size_t i = 1; i <= p.size(); ++i)
if (i == p.size() || p[i] == '/') mkdir(p.substr(0, i).c_str(), 0755);
}
uint32_t intern(const std::string& s) { // caller holds S.mu
auto it = S.strId.find(s);
if (it != S.strId.end()) return it->second;
uint32_t id = (uint32_t)S.strId.size() + 1;
S.strId.emplace(s, id);
std::string line = std::to_string(id) + "\t" + s + "\n";
S.strs.put(line.data(), line.size());
return id;
}
uint32_t apiNameId(int domain, uint32_t cbid) { // caller holds S.mu
auto& m = S.apiName[domain];
auto it = m.find(cbid);
if (it != m.end()) return it->second;
const char* name = nullptr;
cuptiGetCallbackName(domain == 0 ? CUPTI_CB_DOMAIN_DRIVER_API : CUPTI_CB_DOMAIN_RUNTIME_API, cbid, &name);
uint32_t id = intern(name ? name : ("cbid" + std::to_string(cbid)));
m[cbid] = id;
return id;
}
void note(const char* fmt, ...) __attribute__((format(printf, 1, 2)));
void note(const char* fmt, ...) { // caller holds S.mu or is single-threaded
char b[768];
va_list ap;
va_start(ap, fmt);
vsnprintf(b, sizeof b, fmt, ap);
va_end(ap);
S.meta.put(b, strlen(b));
if (S.verbose) fputs(b, stderr);
}
void handleRecord(CUpti_Activity* rec) { // caller holds S.mu, S.winOpen
switch (rec->kind) {
case CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL:
case CUPTI_ACTIVITY_KIND_KERNEL: {
auto* k = (CUpti_ActivityKernel11*)rec;
KRec r{};
r.start = k->start; r.end = k->end; r.dev = k->deviceId; r.stream = k->streamId; r.corr = k->correlationId;
r.graphId = k->graphId; r.graphNodeId = k->graphNodeId;
r.nameId = intern(k->name ? k->name : "?");
r.gx = k->gridX; r.gy = k->gridY; r.gz = k->gridZ; r.bx = k->blockX; r.by = k->blockY; r.bz = k->blockZ;
r.sshm = k->staticSharedMemory; r.dshm = k->dynamicSharedMemory; r.regs = k->registersPerThread;
r.launchType = k->launchType;
S.kern.put(&r, sizeof r); S.counts[0]++; S.bytesOut += sizeof r;
break;
}
case CUPTI_ACTIVITY_KIND_MEMCPY: {
auto* m = (CUpti_ActivityMemcpy6*)rec;
CRec r{};
r.start = m->start; r.end = m->end; r.bytes = m->bytes; r.dev = m->deviceId; r.stream = m->streamId;
r.corr = m->correlationId; r.graphId = m->graphId; r.graphNodeId = m->graphNodeId;
r.copyKind = m->copyKind; r.srcKind = m->srcKind; r.dstKind = m->dstKind; r.flags = m->flags;
r.apiCorr = m->runtimeCorrelationId;
S.copy.put(&r, sizeof r); S.counts[1]++; S.bytesOut += sizeof r;
break;
}
case CUPTI_ACTIVITY_KIND_MEMCPY2: {
auto* m = (CUpti_ActivityMemcpyPtoP4*)rec;
CRec r{};
r.start = m->start; r.end = m->end; r.bytes = m->bytes; r.dev = m->deviceId; r.stream = m->streamId;
r.corr = m->correlationId; r.graphId = m->graphId; r.graphNodeId = m->graphNodeId;
r.copyKind = m->copyKind; r.srcKind = m->srcKind; r.dstKind = m->dstKind; r.flags = 0x80;
r.apiCorr = 0;
S.copy.put(&r, sizeof r); S.counts[1]++; S.bytesOut += sizeof r;
break;
}
case CUPTI_ACTIVITY_KIND_MEMSET: {
auto* m = (CUpti_ActivityMemset4*)rec;
MRec r{};
r.start = m->start; r.end = m->end; r.bytes = m->bytes; r.dev = m->deviceId; r.stream = m->streamId;
r.corr = m->correlationId; r.graphId = m->graphId; r.memKind = m->memoryKind;
S.mset.put(&r, sizeof r); S.counts[2]++; S.bytesOut += sizeof r;
break;
}
case CUPTI_ACTIVITY_KIND_SYNCHRONIZATION: {
auto* m = (CUpti_ActivitySynchronization2*)rec;
YRec r{};
r.start = m->start; r.end = m->end; r.corr = m->correlationId; r.stream = m->streamId; r.eventId = m->cudaEventId;
r.type = (uint32_t)m->type; r.ctx = m->contextId; r.ret = m->returnValue;
S.sync.put(&r, sizeof r); S.counts[3]++; S.bytesOut += sizeof r;
break;
}
case CUPTI_ACTIVITY_KIND_DRIVER:
case CUPTI_ACTIVITY_KIND_RUNTIME: {
auto* m = (CUpti_ActivityAPI*)rec;
ARec r{};
r.start = m->start; r.end = m->end; r.corr = m->correlationId; r.thread = m->threadId;
r.domain = rec->kind == CUPTI_ACTIVITY_KIND_DRIVER ? 0 : 1;
r.nameId = apiNameId(r.domain, m->cbid);
r.ret = m->returnValue;
S.api.put(&r, sizeof r); S.counts[4]++; S.bytesOut += sizeof r;
break;
}
case CUPTI_ACTIVITY_KIND_GRAPH_TRACE: {
auto* m = (CUpti_ActivityGraphTrace2*)rec;
GRec r{};
r.start = m->start; r.end = m->end; r.corr = m->correlationId; r.graphId = m->graphId; r.dev = m->deviceId;
r.stream = m->streamId;
S.graph.put(&r, sizeof r); S.counts[5]++; S.bytesOut += sizeof r;
break;
}
default:
break;
}
}
void CUPTIAPI bufferRequested(uint8_t** buffer, size_t* size, size_t* maxNumRecords) {
*size = S.bufBytes;
*maxNumRecords = 0;
void* p = nullptr;
if (posix_memalign(&p, 8, *size) != 0) p = nullptr;
*buffer = (uint8_t*)p;
}
void CUPTIAPI bufferCompleted(CUcontext, uint32_t, uint8_t* buffer, size_t, size_t validSize) {
if (validSize > 0) {
std::lock_guard<std::mutex> g(S.mu);
if (S.winOpen) {
CUpti_Activity* rec = nullptr;
while (cuptiActivityGetNextRecord(buffer, validSize, &rec) == CUPTI_SUCCESS)
if (S.bytesOut < S.maxBytes) handleRecord(rec);
size_t dropped = 0;
cuptiActivityGetNumDroppedRecords(nullptr, 0, &dropped);
if (dropped) note("dropped_records %zu\n", dropped);
}
}
free(buffer);
}
bool selectedApi(const char* n) {
static const char* const want[] = {"Launch", "Memcpy", "Memset", "Synchronize", "Event", "StreamWait", "Graph", "MemAlloc",
"MemFree", "MemHost", "StreamCreate", "StreamDestroy", "StreamBeginCapture",
"StreamEndCapture", "StreamWriteValue", "StreamWaitValue", "MemMap", "Malloc", "Free"};
for (const char* w : want)
if (strstr(n, w)) return !strstr(n, "Query"); // polling loops would drown everything
return false;
}
void enableKinds(bool on) {
const CUpti_ActivityKind kinds[] = {CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL, CUPTI_ACTIVITY_KIND_MEMCPY,
CUPTI_ACTIVITY_KIND_MEMCPY2, CUPTI_ACTIVITY_KIND_MEMSET,
CUPTI_ACTIVITY_KIND_SYNCHRONIZATION};
// GRAPH_TRACE records a graph launch as ONE item and hides its nodes (CUPTI docs): opt-in only (LCT_GRAPH_TRACE=1).
if (envs("LCT_GRAPH_TRACE")) {
CUptiResult r = on ? cuptiActivityEnable(CUPTI_ACTIVITY_KIND_GRAPH_TRACE) : cuptiActivityDisable(CUPTI_ACTIVITY_KIND_GRAPH_TRACE);
(void)r;
}
for (auto k : kinds) {
CUptiResult r = on ? cuptiActivityEnable(k) : cuptiActivityDisable(k);
if (on && r != CUPTI_SUCCESS) fprintf(stderr, "[lct] cuptiActivityEnable(%d) = %d\n", (int)k, (int)r);
}
if (S.apiLevel >= 1) {
if (on) {
cuptiActivityEnable(CUPTI_ACTIVITY_KIND_DRIVER);
cuptiActivityEnable(CUPTI_ACTIVITY_KIND_RUNTIME);
if (S.apiLevel == 1) { // all on, then switch the uninteresting entry points (queries, getters, pushes) off
int nd = 0, nr = 0;
for (uint32_t cb = 1; cb < CUPTI_DRIVER_TRACE_CBID_SIZE; ++cb) {
const char* n = nullptr;
if (cuptiGetCallbackName(CUPTI_CB_DOMAIN_DRIVER_API, cb, &n) == CUPTI_SUCCESS && n && !selectedApi(n)) {
cuptiActivityEnableDriverApi(cb, 0);
nd++;
}
}
for (uint32_t cb = 1; cb < CUPTI_RUNTIME_TRACE_CBID_SIZE; ++cb) {
const char* n = nullptr;
if (cuptiGetCallbackName(CUPTI_CB_DOMAIN_RUNTIME_API, cb, &n) == CUPTI_SUCCESS && n && !selectedApi(n)) {
cuptiActivityEnableRuntimeApi(cb, 0);
nr++;
}
}
if (S.verbose) fprintf(stderr, "[lct] api filter: %d driver + %d runtime cbids off\n", nd, nr);
}
} else {
cuptiActivityDisable(CUPTI_ACTIVITY_KIND_DRIVER);
cuptiActivityDisable(CUPTI_ACTIVITY_KIND_RUNTIME);
}
}
}
uint64_t cuptiNow() {
uint64_t t = 0;
cuptiGetTimestamp(&t);
return t;
}
void startWindow(const Window& w, const char* why) {
mkdirs(w.out);
{
std::lock_guard<std::mutex> g(S.mu);
const size_t B = 8u << 20;
S.strId.clear(); S.apiName[0].clear(); S.apiName[1].clear();
S.bytesOut = 0;
for (auto& c : S.counts) c = 0;
S.kern.open(w.out + "/kernel.bin", B);
S.copy.open(w.out + "/memcpy.bin", B);
S.mset.open(w.out + "/memset.bin", 1u << 20);
S.sync.open(w.out + "/sync.bin", B);
S.api.open(w.out + "/api.bin", B);
S.graph.open(w.out + "/graph.bin", 1u << 20);
S.strs.open(w.out + "/strings.tsv", 1u << 20);
S.meta.open(w.out + "/meta.txt", 1u << 12);
timespec rt{}, mono{};
uint64_t ts = cuptiNow();
clock_gettime(CLOCK_REALTIME, &rt);
clock_gettime(CLOCK_MONOTONIC, &mono);
S.offReal = (uint64_t)rt.tv_sec * 1000000000ull + rt.tv_nsec - ts;
char exe[512] = {0};
ssize_t n = readlink("/proc/self/exe", exe, sizeof exe - 1);
if (n > 0) exe[n] = 0;
note("format 1\npid %d\nexe %s\nlabel %s\ncupti_ts_ns %llu\nrealtime_ns %llu\nmonotonic_ns %lld\n", (int)getpid(), exe,
w.label.c_str(), (unsigned long long)ts, (unsigned long long)(ts + S.offReal),
(long long)mono.tv_sec * 1000000000LL + mono.tv_nsec);
note("structs KRec=%zu CRec=%zu MRec=%zu YRec=%zu ARec=%zu GRec=%zu\napi_level %d\nreason %s\n", sizeof(KRec),
sizeof(CRec), sizeof(MRec), sizeof(YRec), sizeof(ARec), sizeof(GRec), S.apiLevel, why);
S.winStart = ts;
S.winOpen = true;
}
enableKinds(true);
S.recording.store(true);
fprintf(stderr, "[lct] pid %d window '%s' started (%s) -> %s\n", (int)getpid(), w.label.c_str(), why, w.out.c_str());
}
std::string threadTable() {
std::string s;
DIR* d = opendir("/proc/self/task");
if (!d) return s;
while (dirent* e = readdir(d)) {
if (e->d_name[0] == '.') continue;
std::string p = std::string("/proc/self/task/") + e->d_name + "/comm";
FILE* f = fopen(p.c_str(), "r");
if (!f) continue;
char c[64] = {0};
if (fgets(c, sizeof c, f)) {
c[strcspn(c, "\n")] = 0;
s += std::string(e->d_name) + "\t" + c + "\n";
}
fclose(f);
}
closedir(d);
return s;
}
std::string stopWindow(const Window& w, const char* why) {
S.recording.store(false);
enableKinds(false);
CK(cuptiActivityFlushAll(CUPTI_ACTIVITY_FLAG_FLUSH_FORCED));
uint64_t t = cuptiNow();
std::string done;
{
std::lock_guard<std::mutex> g(S.mu);
char b[640];
snprintf(b, sizeof b,
"{\"label\":\"%s\",\"reason\":\"%s\",\"dir\":\"%s\",\"pid\":%d,\"cupti_start_ns\":%llu,\"cupti_stop_ns\":%llu,"
"\"unix_ms_start\":%llu,\"unix_ms_stop\":%llu,\"bytes\":%llu,\"kernels\":%llu,\"copies\":%llu,\"memsets\":%llu,"
"\"syncs\":%llu,\"api\":%llu,\"graphs\":%llu}\n",
w.label.c_str(), why, w.out.c_str(), (int)getpid(), (unsigned long long)S.winStart, (unsigned long long)t,
(unsigned long long)((S.winStart + S.offReal) / 1000000ull), (unsigned long long)((t + S.offReal) / 1000000ull),
(unsigned long long)S.bytesOut, (unsigned long long)S.counts[0], (unsigned long long)S.counts[1],
(unsigned long long)S.counts[2], (unsigned long long)S.counts[3], (unsigned long long)S.counts[4],
(unsigned long long)S.counts[5]);
done = b;
note("window_start %llu\nwindow_stop %llu\nstop_reason %s\n", (unsigned long long)S.winStart, (unsigned long long)t, why);
S.winOpen = false;
std::string th = threadTable();
FILE* f = fopen((w.out + "/threads.tsv").c_str(), "w");
if (f) {
fwrite(th.data(), 1, th.size(), f);
fclose(f);
}
S.kern.close(); S.copy.close(); S.mset.close(); S.sync.close(); S.api.close(); S.graph.close(); S.strs.close(); S.meta.close();
}
fprintf(stderr, "[lct] pid %d window '%s' stopped (%s): %s", (int)getpid(), w.label.c_str(), why, done.c_str());
if (!w.prefix.empty()) writeFile(w.prefix + ".done", done);
else writeFile(w.out + "/done.json", done);
return done;
}
void CUPTIAPI apiCallback(void*, CUpti_CallbackDomain domain, CUpti_CallbackId cbid, const CUpti_CallbackData* d) {
if (domain != CUPTI_CB_DOMAIN_DRIVER_API || d->callbackSite != CUPTI_API_ENTER) return;
if (!S.recording.load(std::memory_order_relaxed)) {
if (S.startTarget.load() && !S.reqStart.load())
for (auto id : S.startIds)
if (id == cbid) {
if (S.startCnt.fetch_add(1) + 1 == S.startTarget.load()) S.reqStart.store(true);
break;
}
if (S.symTarget.load() && !S.reqStart.load() && d->symbolName && strstr(d->symbolName, S.symSubstr.c_str()))
if (S.symCnt.fetch_add(1) + 1 == S.symTarget.load()) S.reqStart.store(true);
} else if (S.stopTarget.load()) {
for (auto id : S.stopIds)
if (id == cbid) {
if (S.stopCnt.fetch_add(1) + 1 == S.stopTarget.load()) S.reqStop.store(true);
break;
}
}
}
std::vector<CUpti_CallbackId> findDriverIds(const std::string& name) {
std::vector<CUpti_CallbackId> ids;
for (int pass = 0; pass < 2 && ids.empty(); ++pass)
for (uint32_t cb = 1; cb < CUPTI_DRIVER_TRACE_CBID_SIZE; ++cb) {
const char* n = nullptr;
if (cuptiGetCallbackName(CUPTI_CB_DOMAIN_DRIVER_API, cb, &n) != CUPTI_SUCCESS || !n) continue;
if (pass == 0 ? name == n : strncmp(n, name.c_str(), name.size()) == 0) ids.push_back(cb);
}
return ids;
}
bool parseNameN(const char* spec, std::string& name, uint64_t& n) {
std::string s = spec;
size_t c = s.rfind(':');
if (c == std::string::npos) return false;
name = s.substr(0, c);
n = strtoull(s.c_str() + c + 1, nullptr, 10);
return n > 0;
}
// Minimal JSON field extraction for {"seconds": N, "out": "...", "label": "..."} (flat, no nested objects).
std::string jsonStr(const std::string& j, const char* key) {
std::string k = std::string("\"") + key + "\"";
size_t p = j.find(k);
if (p == std::string::npos) return "";
p = j.find(':', p);
if (p == std::string::npos) return "";
p = j.find_first_not_of(" \t\r\n", p + 1);
if (p == std::string::npos) return "";
if (j[p] == '"') {
std::string r;
for (++p; p < j.size() && j[p] != '"'; ++p) {
if (j[p] == '\\' && p + 1 < j.size()) ++p;
r += j[p];
}
return r;
}
size_t e = j.find_first_of(",} \t\r\n", p);
return j.substr(p, e == std::string::npos ? std::string::npos : e - p);
}
bool takeTrigger(Window& w) {
struct stat st;
if (S.trigger.empty() || stat(S.trigger.c_str(), &st) != 0) return false;
FILE* f = fopen(S.trigger.c_str(), "r");
if (!f) return false;
std::string j;
char b[1024];
size_t n;
while ((n = fread(b, 1, sizeof b, f)) > 0 && j.size() < 65536) j.append(b, n);
fclose(f);
const double cap = envs("LCT_MAX_SECONDS") ? atof(envs("LCT_MAX_SECONDS")) : 120.0;
std::string sec = jsonStr(j, "seconds"), out = jsonStr(j, "out");
w = Window();
w.fromTrigger = true;
w.trigger = S.trigger;
w.seconds = sec.empty() ? 10.0 : atof(sec.c_str());
if (w.seconds > cap || w.seconds <= 0) w.seconds = cap;
w.label = jsonStr(j, "label");
for (auto& c : w.label)
if (c == '"' || c == '\\' || c == '\n' || c == '\r') c = '_';
if (out.empty()) out = (envs("LCT_OUT") ? std::string(envs("LCT_OUT")) : std::string("/tmp")) + "/lct-win-" + std::to_string(++S.winSeq);
w.prefix = out;
w.out = out + ".lct";
if (rename(S.trigger.c_str(), (S.trigger + ".active").c_str()) != 0) {
writeFile(S.errPath, std::string("cannot rename trigger: ") + strerror(errno) + "\n");
return false;
}
return true;
}
void onSignal(int sig) {
if (sig == SIGUSR1) S.reqStart.store(true);
if (sig == SIGUSR2) S.reqStop.store(true);
}
void watcher() {
const double startAfter = envs("LCT_START_AFTER_S") ? atof(envs("LCT_START_AFTER_S")) : -1;
const double envDur = envs("LCT_DURATION_S") ? atof(envs("LCT_DURATION_S")) : -1;
const char* startFile = envs("LCT_START_FILE");
const char* stopFile = envs("LCT_STOP_FILE");
const bool hasEnvTrigger = startAfter >= 0 || startFile || S.startTarget.load() || S.symTarget.load() || envs("LCT_SIGNALS");
bool immediate = S.trigger.empty() && !hasEnvTrigger && !envs("LCT_WAIT");
bool envWindowPending = hasEnvTrigger || immediate;
const auto t0 = std::chrono::steady_clock::now();
auto secs = [&] { return std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count(); };
struct stat st;
Window cur;
double winT0 = 0;
bool active = false;
int tick = 0;
while (!S.finished.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
if (!S.cuptiOk.load()) continue;
if (!active) {
const char* why = nullptr;
if (takeTrigger(cur)) why = "trigger";
else if (envWindowPending) {
if (immediate) why = "immediate";
else if (S.reqStart.load()) why = "signal/api";
else if (startAfter >= 0 && secs() >= startAfter) why = "after_s";
else if (startFile && stat(startFile, &st) == 0) why = "start_file";
if (why) {
cur = Window();
cur.seconds = envDur;
cur.out = (envs("LCT_OUT") ? std::string(envs("LCT_OUT")) : std::string(".")) + "/lct." + std::to_string((int)getpid());
cur.label = "env";
envWindowPending = false;
immediate = false;
}
}
if (why) {
startWindow(cur, why);
winT0 = secs();
active = true;
S.reqStart.store(false);
S.reqStop.store(false);
S.startTarget.store(0);
S.symTarget.store(0);
tick = 0;
}
} else {
const char* why = nullptr;
if (S.reqStop.load()) why = "signal/api";
else if (cur.seconds > 0 && secs() - winT0 >= cur.seconds) why = "duration";
else if (stopFile && !cur.fromTrigger && stat(stopFile, &st) == 0) why = "stop_file";
else if (cur.fromTrigger && stat((S.trigger + ".stop").c_str(), &st) == 0) why = "stop_file";
else if (S.bytesOut >= S.maxBytes) why = "max_mb";
if (why) {
stopWindow(cur, why);
if (cur.fromTrigger) {
rename((S.trigger + ".active").c_str(), (S.trigger + ".done").c_str());
unlink((S.trigger + ".stop").c_str());
}
active = false;
S.stopTarget.store(0);
} else if (++tick % 20 == 0) { // ~ every second: complete buffers reach the file even if the process is killed
cuptiActivityFlushAll(0);
std::lock_guard<std::mutex> g(S.mu);
S.kern.flush(); S.copy.flush(); S.mset.flush(); S.sync.flush(); S.api.flush(); S.graph.flush(); S.strs.flush();
}
}
}
if (active) {
stopWindow(cur, "exit");
if (cur.fromTrigger) rename((S.trigger + ".active").c_str(), (S.trigger + ".done").c_str());
}
}
void atExit() {
if (!S.inited.load()) return;
S.finished.store(true);
// The watcher is detached and may still be inside a window: wait until it has closed the files (a 100+ MB window takes seconds
// to flush and convert), before the process tears down.
for (int i = 0; i < 6000 && (S.recording.load() || S.winOpen); ++i) std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
void init() {
bool exp = false;
if (!S.inited.compare_exchange_strong(exp, true)) return;
S.verbose = envs("LCT_VERBOSE") != nullptr;
S.apiLevel = envs("LCT_API") ? atoi(envs("LCT_API")) : 1;
if (envs("LCT_BUF_MB")) S.bufBytes = (size_t)atoi(envs("LCT_BUF_MB")) << 20;
S.maxBytes = (uint64_t)((envs("LCT_MAX_MB") ? atof(envs("LCT_MAX_MB")) : 3072.0) * 1048576.0);
const char* trig = envs("LELEKA_CUPTI_TRIGGER") ? envs("LELEKA_CUPTI_TRIGGER") : envs("LCT_TRIGGER");
if (trig) {
S.trigger = trig;
S.errPath = S.trigger + ".error";
}
// CUPTI setup; a failure only disables tracing.
bool ok = true;
auto chk = [&](CUptiResult r, const char* what) {
if (r != CUPTI_SUCCESS) {
const char* m = nullptr;
cuptiGetResultString(r, &m);
std::string e = std::string(what) + " failed: " + (m ? m : "?") + "\n";
fputs(("[lct] " + e).c_str(), stderr);
if (!S.errPath.empty()) writeFile(S.errPath, e);
ok = false;
}
};
chk(cuptiActivityRegisterCallbacks(bufferRequested, bufferCompleted), "cuptiActivityRegisterCallbacks");
if (ok) {
size_t sz = S.bufBytes, vs = sizeof sz;
cuptiActivitySetAttribute(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_SIZE, &vs, &sz);
size_t lim = 32;
vs = sizeof lim;
cuptiActivitySetAttribute(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_POOL_LIMIT, &vs, &lim);
cuptiActivityFlushPeriod(1000);
}
std::string nm;
uint64_t cnt = 0;
bool needSub = false;
std::vector<CUpti_CallbackId> all;
if (ok && envs("LCT_START_API") && parseNameN(envs("LCT_START_API"), nm, cnt)) {
S.startIds = findDriverIds(nm);
S.startTarget.store(cnt);
needSub = true;
all.insert(all.end(), S.startIds.begin(), S.startIds.end());
}
if (ok && envs("LCT_START_SYM") && parseNameN(envs("LCT_START_SYM"), nm, cnt)) {
S.symSubstr = nm;
S.symTarget.store(cnt);
needSub = true;
for (uint32_t cb = 1; cb < CUPTI_DRIVER_TRACE_CBID_SIZE; ++cb) {
const char* n = nullptr;
if (cuptiGetCallbackName(CUPTI_CB_DOMAIN_DRIVER_API, cb, &n) == CUPTI_SUCCESS && n && strncmp(n, "cuLaunchKernel", 14) == 0)
all.push_back(cb);
}
}
if (ok && envs("LCT_STOP_API") && parseNameN(envs("LCT_STOP_API"), nm, cnt)) {
S.stopIds = findDriverIds(nm);
S.stopTarget.store(cnt);
needSub = true;
all.insert(all.end(), S.stopIds.begin(), S.stopIds.end());
}
if (needSub) {
chk(cuptiSubscribe(&S.sub, (CUpti_CallbackFunc)apiCallback, nullptr), "cuptiSubscribe");
for (auto id : all) cuptiEnableCallback(1, S.sub, CUPTI_CB_DOMAIN_DRIVER_API, id);
}
if (envs("LCT_SIGNALS")) {
signal(SIGUSR1, onSignal);
signal(SIGUSR2, onSignal);
}
S.cuptiOk.store(ok);
atexit(atExit);
std::thread(watcher).detach();
fprintf(stderr, "[lct] pid %d tracer %s (trigger %s)\n", (int)getpid(), ok ? "armed" : "DISABLED (CUPTI init failed)",
S.trigger.empty() ? "env/immediate" : S.trigger.c_str());
}
} // namespace
extern "C" {
__attribute__((visibility("default"))) int InitializeInjection(void) {
init();
return 1;
}
__attribute__((constructor)) static void lctCtor() {
// Under LD_PRELOAD the constructor runs before main. Under CUDA_INJECTION64_PATH the driver calls InitializeInjection.
if (!envs("LCT_NO_CTOR") && !envs("CUDA_INJECTION64_PATH")) init();
}
}