#!/usr/bin/env python3 """Own a PID-scoped tracefs instance and exact NVIDIA entry probes. No rebind/reset.""" import argparse,hashlib,json,os,re,time from pathlib import Path p=argparse.ArgumentParser();p.add_argument('--pid',type=int,required=True);p.add_argument('--output',type=Path,required=True);p.add_argument('--timeout',type=float,default=90);a=p.parse_args();assert os.geteuid()==0 out=a.output.resolve();out.mkdir(parents=True,exist_ok=True);base=Path('/sys/kernel/tracing');group=f'nv_rs_init_{os.getpid()}';instance=base/'instances'/group;added=[];errors=[];registered=[];created=False # GPU argument is independently verified for these original routines. Raw args # are retained as well; no unverified pointer chains or memory writes are used. symbols=['nv_open_device','nv_close_device','rm_init_adapter','rm_shutdown_adapter','_nv000790rm','_nv031364rm','_nv030235rm','_nv030241rm','_nv033663rm','_nv033665rm','_nv033300rm','_nv033662rm','_nv033231rm','_nv033664rm','_nv033298rm','_nv033685rm','_nv055403rm','_nv028309rm','_nv028308rm','_nv043609rm','_nv027753rm','_nv027729rm','_nv017686rm','_nv017682rm','_nv016741rm','_nv016753rm','_nv016953rm','_nv028470rm','_nv043236rm','_nv043182rm','_nv043215rm','_nv027605rm','_nv029864rm','_nv028607rm'] gpu_symbols=set(symbols)-{'nv_open_device','nv_close_device','rm_init_adapter','rm_shutdown_adapter','_nv000790rm','_nv031364rm'} specific={ '_nv016741rm':'acr385=+0x385(%si):u8 acr387=+0x387(%si):u8 acr392=+0x392(%si):u8 acr398=+0x398(%si):u8', '_nv016753rm':'acr385=+0x385(%si):u8 acr387=+0x387(%si):u8 acr392=+0x392(%si):u8 acr398=+0x398(%si):u8', '_nv043236rm':'lsfm190=+0x190(%si):u8 clients=+0x192(%si):u16 image_bytes=+0x194(%si):u32 excluded=+0x198(%si):x32', '_nv043182rm':'lsfm190=+0x190(%si):u8 clients=+0x192(%si):u16 falcon_id=+0x608(%dx):u32 falcon_isa=+0x650(%dx):u32', '_nv028470rm':'falcon_isa=+0x650(%si):u32 falcon_3a7=+0x3a7(%si):u8', '_nv027605rm':'netlist_slot=+0x1c8(%si):u32', '_nv029864rm':'netlist_slot=+0x1f8(%si):u32', '_nv055403rm':'interval=+0x1e18(%di):u32', } def write(path,text): with path.open('w')as f:f.write(text) def event_command(command): fd=os.open(base/'kprobe_events',os.O_WRONLY) try:os.write(fd,(command+'\n').encode()) finally:os.close(fd) def bindings(): r={} for d in Path('/sys/bus/pci/devices').iterdir(): try: if (d/'vendor').read_text().strip()=='0x10de'and int((d/'class').read_text(),16)>>16==3:r[d.name]=(d/'driver').resolve().name if(d/'driver').exists()else None except OSError:pass return r def live_identity(pid): try: s=Path(f'/proc/{pid}/stat').read_text();return s[s.rfind(')')+2:].split()[19] except OSError:return None identity=live_identity(a.pid);assert identity is not None,'selected target is gone' report={'scope':'Only selected PID and inherited threads/children through event-fork. Entry probes and declared read-only fields; no driver rebinding, GPU reset, original memory writes, or service/persistence changes. Asynchronous kernel workers not inheriting the selected PID are not covered.','pid':a.pid,'pid_starttime':identity,'probe_group':group,'bindings_before':bindings(),'clock_before':{'monotonic_ns':time.monotonic_ns(),'realtime_ns':time.time_ns()},'kernel':os.uname().release,'nvidia_version':Path('/proc/driver/nvidia/version').read_text(),'errors':errors,'registered':registered} try: instance.mkdir();created=True;write(instance/'tracing_on','0');write(instance/'current_tracer','nop');write(instance/'buffer_size_kb','8192');write(instance/'trace_clock','mono');write(instance/'set_event_pid',str(a.pid));write(instance/'options/event-fork','1') available={line.split()[2]for line in Path('/proc/kallsyms').read_text().splitlines()if len(line.split())>=4 and line.split()[3]=='[nvidia]'} for i,symbol in enumerate(symbols): if symbol not in available:errors.append({'symbol':symbol,'error':'not in current module symbol table'});continue name=f'e{i:02d}';fetch='arg1=%di:x64 arg2=%si:x64 arg3=%dx:x64 arg4=%cx:x64 arg5=%r8:x64 arg6=%r9:x64' if symbol in gpu_symbols:fetch+=' gpu_id=+0xca8(%di):x32' if symbol in specific:fetch+=' '+specific[symbol] definition=f'p:{group}/{name} {symbol} {fetch}' try:event_command(definition);added.append(name);registered.append({'event':name,'symbol':symbol,'definition':definition}) except OSError as e:errors.append({'symbol':symbol,'error':str(e)});continue write(instance/'events'/group/name/'enable','1') assert added,'no usable probes' write(instance/'tracing_on','1');report['ready_monotonic_ns']=time.monotonic_ns();(out/'kernel-ready.json').write_text(json.dumps(report,indent=2)+'\n');print('READY',a.pid,len(added),flush=True) deadline=time.monotonic()+a.timeout while live_identity(a.pid)==identity and time.monotonic()=deadline except BaseException as e:report['failure']=repr(e);print('CAPTURE_ERROR',repr(e),flush=True) finally: if created: try: write(instance/'tracing_on','0');trace=(instance/'trace').read_bytes();(out/'kernel-trace.txt').write_bytes(trace);report['trace_sha256']=hashlib.sha256(trace).hexdigest();report['trace_bytes']=len(trace);report['per_cpu_stats']={p.parent.name:p.read_text()for p in(instance/'per_cpu').glob('cpu*/stats')} for name in added:write(instance/'events'/group/name/'enable','0') except OSError as e:errors.append({'cleanup':'read/disable','error':str(e)}) for name in added: try:event_command(f'-:{group}/{name}') except OSError as e:errors.append({'cleanup':name,'error':str(e)}) if created: try:instance.rmdir() except OSError as e:errors.append({'cleanup':'instance','error':str(e)}) report['probes_removed']=not any(group+'/'in line for line in(base/'kprobe_events').read_text().splitlines());report['instance_removed']=not instance.exists();report['bindings_after']=bindings();report['clock_after']={'monotonic_ns':time.monotonic_ns(),'realtime_ns':time.time_ns()};(out/'kernel-capture.json').write_text(json.dumps(report,indent=2)+'\n');print('CLOSED',report['probes_removed'],report['instance_removed'],flush=True)