// Non-JIT 16-bit interpreter. An instruction commits only after all data // accesses pass the mapping/watchpoint guards. Otherwise Python executes it. #include #include #include namespace { enum { AX,CX,DX,BX,SP,BP,SI,DI,ES,CS,SS,DS,IP,F }; constexpr uint32_t CF=1, PF=4, AF=16, ZF=64, SF=128, IF=512, DF=1024, OF=2048; struct Core { uint32_t r[14], saved[14], done=0, reason=0; uint32_t io_direction=0, io_port=0, io_size=0, io_value=0; const uint8_t *fast_out=nullptr; // Per-vector software INT policy (bit 0: take it here, bit 1: clear IF/TF // on entry) and a running count the harness merges into its own tally. const uint8_t *int_mode=nullptr; uint32_t *int_counts=nullptr; // Optional port model: host_ports[port] bit 0 offers IN, bit 1 OUT to // host_io, which answers 1 when it served the access (an IN's value goes // to *out). Declined accesses leave the engine for the harness as usual. typedef int (*HostIo)(void *context,int direction,uint16_t port,int size,uint16_t value,uint64_t now,uint16_t *out); uint64_t host_base=0; HostIo host_io=nullptr; void *host_context=nullptr; const uint8_t *host_ports=nullptr; uint8_t *io_events=nullptr; uint32_t io_event_count=0, io_event_capacity=0; // Optional harness poll, run here when it needs nothing from Python: at // the instruction that would retire as number `poll_next` (counting from // `poll_total`, what had retired before this batch) the engine asks // poll_fn(context, now). 1: the poll was done; the next falls due // `poll_period` later and execution carries on (4: and an interrupt was // taken, which retires one instruction without running it). Anything else leaves the // engine with reason 9 and that answer in poll_code, for the harness to run // its own poll (code 0) or finish a partly done one (codes 2, 3). typedef int (*PollFn)(void *context,uint64_t now,uint32_t flags,void *cpu); // What the poll is lent: the registers and memory (for an interrupt // entry), the guard bytes, the port writes and memory-mapped writes this // batch has logged so far, and what had retired before the batch began, // which tells one batch's logs from the next. struct PollCpu { uint32_t *regs; uint8_t *memory; std::size_t memory_size; const uint8_t *guard; uint8_t *io_events; uint32_t io_event_count; uint8_t *mmio_events; uint32_t mmio_count; uint64_t batch_total; }; PollFn poll_fn=nullptr; void *poll_context=nullptr; uint64_t poll_total=0, poll_next=0, poll_period=0; uint32_t poll_code=0, polls_elided=0; bool dirty_events=false; // Writes to bytes whose guard has bit 64 are logged here (8 bytes each: // address, value, size) instead of leaving the engine, for the harness to // replay in order before it next looks at anything. Capacity is one batch's // worst case, so there is no overflow check. uint8_t *mmio_events=nullptr; uint32_t mmio_count=0; std::jmp_buf exit; [[noreturn]] void yield(uint32_t why=1) { reason=why; std::longjmp(exit, 1); } uint8_t *mem; const uint8_t *guard; uint32_t mask; bool is386=false; int width=2; int seg=-1; struct Write { uint32_t address,value; int size; }; Write writes[8]; int nw=0; uint32_t phys(uint32_t s,uint32_t o) { return ((s&65535)*16+(o&65535))&mask; } uint32_t fetch(int n=1) { uint32_t v=0; for(int i=0;imask+1) yield(2); // Mapping regions are page-aligned. Watched bytes force a fallback, // including straddling accesses (conservative w.r.t. Python hooks). for(int i=0;i=2)v|=uint32_t(mem[a+1])<<8; if(n==4)v|=uint32_t(mem[a+2])<<16|uint32_t(mem[a+3])<<24; return v;} void store(uint32_t a,int n,uint32_t v) {check(a,n,2); if(nw==8)yield(); writes[nw++]={a,v,n};} uint32_t get(int k,int n) {return n==1?(r[k&3]>>((k&4)?8:0))&255:r[k];} void put(int k,int n,uint32_t v) {if(n==1){int sh=(k&4)?8:0; r[k&3]=(r[k&3]&~(255u<>6,rm=m&7; uint32_t o; bool bp=false; if(mod==0&&rm==6)o=fetch(2); else {switch(rm){case 0:o=r[BX]+r[SI];break;case 1:o=r[BX]+r[DI];break;case 2:o=r[BP]+r[SI];bp=true;break;case 3:o=r[BP]+r[DI];bp=true;break;case 4:o=r[SI];break;case 5:o=r[DI];break;case 6:o=r[BP];bp=true;break;default:o=r[BX];} if(mod==1)o+=int8_t(fetch());else if(mod==2)o+=int16_t(fetch(2));} return phys(seg<0?r[bp?SS:DS]:uint32_t(seg),o); } uint32_t read(int m,int n,uint32_t a){return m>=192?get(m&7,n):load(a,n);} void write(int m,int n,uint32_t a,uint32_t v){if(m>=192)put(m&7,n,v);else store(a,n,v);} uint32_t alu(int op,uint32_t l,uint32_t q,int n) { uint32_t mask=n==1?255:65535, sign=(mask+1)>>1, flags=r[F]&~(CF|PF|AF|ZF|SF|OF), v; if(op==1)v=(l|q)&mask;else if(op==4)v=(l&q)&mask;else if(op==6)v=(l^q)&mask; else {uint32_t adj=q+((op==2||op==3)?(r[F]&CF):0); bool add=op==0||op==2; v=(add?l+adj:l-adj)&mask; if(add){if(l+adj>mask)flags|=CF;if((~(l^adj)&(l^v)&sign))flags|=OF;} else {if(l=0xe4&&op<=0xe7){io_port=mem[phys(r[CS],r[IP])];r[IP]=(r[IP]+1)&65535;} else io_port=r[DX]&65535; if(io_direction==2)io_value=io_size==1?r[AX]&255:r[AX]&65535; reason=8; } void step(){ uint32_t start=r[IP];int op=fetch(),rep=0;seg=-1;nw=0;width=2; for(int prefixes=0;;++prefixes){ if(prefixes==15)yield(); if(op==0x26)seg=r[ES];else if(op==0x2e)seg=r[CS];else if(op==0x36)seg=r[SS];else if(op==0x3e)seg=r[DS];else if(op==0x66&&is386)width=4;else if(op==0xf2||op==0xf3)rep=op;else if(op!=0xf0)break;op=fetch(); } // The shared 16-bit core must not truncate live extended registers. // Wider moves and strings are supported explicitly; other mixed-width // operations stay in the reference engine until their semantics match. bool wide_move=(op>=0xb0&&op<=0xbf)||(op>=0x88&&op<=0x8b)|| op==0xc6||op==0xc7||(op>=0xa4&&op<=0xa5)||(op>=0xaa&&op<=0xad); if(width==4&&!wide_move)yield(); if(is386){ uint32_t high=0;for(int k=0;k<8;++k)high|=r[k]; if((high>>16)&&!wide_move)yield(5); if(wide_move&&(op==0xa4||op==0xa5||(op>=0xaa&&op<=0xad))&& ((r[SI]|r[DI]|r[CX])>>16))yield(); // CBW and CWD write the whole of EAX/EDX, as the reference's // reg_write does; with the upper halves zero (checked above) the // 16-bit forms below give exactly that. } if(op<0x40 && (op&7)<6){int operation=(op>>3)&7,n=(op&1)?2:1;uint32_t l,q,a=0;int m=0,k=0; if((op&7)<4){m=fetch();k=(m>>3)&7;if(m<192)a=ea(m);l=read(m,n,a);q=get(k,n);if(op&2){uint32_t t=l;l=q;q=t;}} else {l=get(0,n);q=fetch(n);} uint32_t v=alu(operation,l,q,n);if(operation!=7){if((op&7)>=4)put(0,n,v);else if(op&2)put(k,n,v);else write(m,n,a,v);}return;} if(op>=0x40&&op<=0x4f){int k=op&7;uint32_t cf=r[F]&CF;put(k,2,alu(op<0x48?0:5,r[k],1,2));r[F]=(r[F]&~CF)|cf;return;} if(op>=0x50&&op<=0x57){push(r[op&7]);return;} if(op>=0x58&&op<=0x5f){r[op&7]=pop();return;} if(op>=0x70&&op<=0x7f){int d=int8_t(fetch());if(cond(op&15))r[IP]=(r[IP]+d)&65535;return;} if(op>=0xb0&&op<=0xbf){int n=op<0xb8?1:width;put(op&7,n,fetch(n));return;} if(op>=0x90&&op<=0x97){uint32_t t=r[AX];r[AX]=r[op&7];r[op&7]=t;return;} switch(op){ case 0x80:case 0x81:case 0x83:{int m=fetch(),n=op==0x80?1:2,k=(m>>3)&7;uint32_t a=m<192?ea(m):0,q=op==0x83?uint32_t(int8_t(fetch()))&65535:fetch(n);uint32_t v=alu(k,read(m,n,a),q,n);if(k!=7)write(m,n,a,v);break;} case 0x84:case 0x85:case 0x86:case 0x87:case 0x88:case 0x89:case 0x8a:case 0x8b:{int m=fetch(),n=(op&1)?width:1,k=(m>>3)&7;uint32_t a=m<192?ea(m):0; if(op<0x86)alu(4,read(m,n,a),get(k,n),n); else if(op<0x88){uint32_t v=read(m,n,a);write(m,n,a,get(k,n));put(k,n,v);} else if(is386&&n==2&&m>=192){if(op&2)r[k]=r[m&7];else r[m&7]=r[k];} else if(op&2)put(k,n,read(m,n,a));else write(m,n,a,get(k,n));break;} case 0x8c:case 0x8e:{int m=fetch(),k=ES+((m>>3)&3);uint32_t a=m<192?ea(m):0;if(op==0x8c)write(m,2,a,r[k]);else r[k]=read(m,2,a);break;} case 0x8d:{int m=fetch();if(m>=192)yield();int oldseg=seg;seg=0;uint32_t a=ea(m);seg=oldseg;r[(m>>3)&7]=a&65535;break;} case 0xa0:case 0xa1:case 0xa2:case 0xa3:{int n=(op&1)?2:1;uint32_t a=phys(seg<0?r[DS]:seg,fetch(2));if(op&2)store(a,n,get(0,n));else put(0,n,load(a,n));break;} case 0xa4:case 0xa5:case 0xaa:case 0xab:case 0xac:case 0xad:{if(rep&&!r[CX])break;int n=(op&1)?width:1,form=(op>>1)&7,delta=(r[F]&DF)?-n:n;uint32_t v; if(form!=5){v=load(phys(seg<0?r[DS]:seg,r[SI]),n);r[SI]=(r[SI]+delta)&65535;}else v=get(0,n); if(form!=6){store(phys(r[ES],r[DI]),n,v);r[DI]=(r[DI]+delta)&65535;}else put(0,n,v); if(rep){r[CX]=(r[CX]-1)&65535;r[IP]=start;}break;} case 0xa8:case 0xa9:{int n=(op&1)?2:1;alu(4,get(0,n),fetch(n),n);break;} case 0xf6:case 0xf7:{ int m=fetch(),k=(m>>3)&7,n=(op&1)?2:1,bits=n*8;uint32_t mask=n==1?255:65535,a=m<192?ea(m):0,v=read(m,n,a); if(is386&&k>=4)yield(); if(k==0)alu(4,v,fetch(n),n); else if(k==2)write(m,n,a,~v); else if(k==3)write(m,n,a,alu(5,0,v,n)); else if(k==4||k==5){ int64_t product; if(k==4)product=int64_t(get(0,n))*v; else product=int64_t(n==1?int8_t(get(0,n)):int16_t(get(0,n)))*(n==1?int8_t(v):int16_t(v)); r[AX]=product&65535;if(n==2)r[DX]=(uint64_t(product)>>16)&65535; bool overflow=k==4?bool(uint64_t(product)>>bits):product!=(n==1?int8_t(product):int16_t(product)); r[F]=(r[F]&~(CF|OF))|(overflow?(CF|OF):0); }else if(k==6){uint32_t dividend=n==1?r[AX]:(r[DX]<<16)|r[AX];if(!v||dividend/v>mask)yield();uint32_t q=dividend/v,rem=dividend%v;if(n==1)r[AX]=q|(rem<<8);else{r[AX]=q;r[DX]=rem;}} else if(k==7){int64_t dividend=n==1?int16_t(r[AX]):int32_t((r[DX]<<16)|r[AX]);int64_t divisor=n==1?int8_t(v):int16_t(v);if(!divisor)yield();int64_t q=dividend/divisor,rem=dividend%divisor;if(q<-(1LL<<(bits-1))||q>=(1LL<<(bits-1)))yield();if(n==1)r[AX]=(q&255)|((rem&255)<<8);else{r[AX]=q&65535;r[DX]=rem&65535;}} else yield();break;} case 0xa6:case 0xa7:case 0xae:case 0xaf:{ if(rep&&!r[CX])break;int n=(op&1)?2:1,delta=(r[F]&DF)?-n:n;uint32_t left=get(0,n); if(op<0xae){left=load(phys(seg<0?r[DS]:seg,r[SI]),n);r[SI]=(r[SI]+delta)&65535;} alu(7,left,load(phys(r[ES],r[DI]),n),n);r[DI]=(r[DI]+delta)&65535; if(rep){r[CX]=(r[CX]-1)&65535;if(r[CX]&&(rep==0xf3?bool(r[F]&ZF):!(r[F]&ZF)))r[IP]=start;}break;} case 0x60:{uint32_t sp=r[SP];for(int k=AX;k<=BX;++k)push(r[k]);push(sp);for(int k=BP;k<=DI;++k)push(r[k]);break;} case 0x61:{for(int k=DI;k>=BP;--k)r[k]=pop();pop();for(int k=BX;k>=AX;--k)r[k]=pop();break;} case 0x9a:{uint32_t off=fetch(2),cs=fetch(2);push(r[CS]);push(r[IP]);r[CS]=cs;r[IP]=off;break;} case 0xc4:case 0xc5:{int m=fetch();if(m>=192)yield();uint32_t a=ea(m),v=load(a,2),s=load(a+2,2);r[(m>>3)&7]=v;r[op==0xc4?ES:DS]=s;break;} case 0xcd:{ // A vector the harness handles itself, or a null entry, leaves // the instruction to the reference engine. uint32_t n=fetch(),table=n*4; if(!int_mode||!(int_mode[n]&1))yield(); uint32_t offset=load(table,2),segment=load(table+2,2); if(!offset&&!segment)yield(); uint32_t flags=r[F]&65535; push(flags);push(r[CS]);push(r[IP]); r[F]=(int_mode[n]&2)?(flags&~(IF|0x100u)):r[F]; r[CS]=segment;r[IP]=offset; if(int_counts)++int_counts[n]; break;} case 0xcf:r[IP]=pop();r[CS]=pop();r[F]=pop()|2;break; case 0xcb:r[IP]=pop();r[CS]=pop();break; case 0xc0:case 0xc1:case 0xd0:case 0xd1:case 0xd2:case 0xd3:{ int m=fetch(),k=(m>>3)&7,n=(op&1)?2:1,bits=n*8;uint32_t a=m<192?ea(m):0,v=read(m,n,a); int count=((op==0xd0||op==0xd1)?1:(op==0xd2||op==0xd3)?r[CX]&255:fetch())&31; if(!count)break; uint32_t mask=n==1?255:65535,result=v,carry=r[F]&CF; if(k==0){int b=count%bits;result=((v<>(bits-b)))&mask;carry=result&1;} else if(k==1){int b=count%bits;result=((v>>b)|(v<<(bits-b)))&mask;carry=(result>>(bits-1))&1;} else if(k==2){for(int i=0;i>(bits-1))&1;result=((result<<1)|carry)&mask;carry=next;}} else if(k==3){for(int i=0;i>1)|(carry<<(bits-1));carry=next;}} else if(k==4||k==6){carry=count<=bits?(v>>(bits-count))&1:0;result=v<>(count-1))&1:0;result=v>>count;} else{carry=count<=bits?(v>>(count-1))&1:0;int32_t sv=n==1?int8_t(v):int16_t(v);result=uint32_t(sv>>count);} if(is386&&m>=192&&n==2)r[m&7]=result;else write(m,n,a,result);if(k>=4)alu(4,result,mask,n);r[F]=(r[F]&~CF)|carry;break;} case 0xc6:case 0xc7:{int m=fetch(),n=(op&1)?width:1;uint32_t a=m<192?ea(m):0,v=fetch(n);write(m,n,a,v);break;} case 0xc3:r[IP]=pop();break; case 0xc9:r[SP]=r[BP];r[BP]=pop();break; case 0xe8:{int d=int16_t(fetch(2));push(r[IP]);r[IP]=(r[IP]+d)&65535;break;} case 0xe9:case 0xeb:{int d=op==0xeb?int8_t(fetch()):int16_t(fetch(2));r[IP]=(r[IP]+d)&65535;break;} case 0xea:{uint32_t off=fetch(2);r[CS]=fetch(2);r[IP]=off;break;} case 0xe0:case 0xe1:case 0xe2:case 0xe3:{int d=int8_t(fetch());bool take;if(op==0xe3)take=!r[CX];else{r[CX]=(r[CX]-1)&65535;take=r[CX]&&(op==0xe2||(op==0xe0?!(r[F]&ZF):bool(r[F]&ZF)));}if(take)r[IP]=(r[IP]+d)&65535;break;} case 0xfe:case 0xff:{int m=fetch(),k=(m>>3)&7,n=op==0xfe?1:2;if(k>1&&(op==0xfe||k==7))yield();if((k==3||k==5)&&m>=192)yield();uint32_t a=m<192?ea(m):0,v=read(m,n,a); if(k<=1){uint32_t cf=r[F]&CF;v=alu(k?5:0,v,1,n);r[F]=(r[F]&~CF)|cf;write(m,n,a,v);}else if(k==2){push(r[IP]);r[IP]=v;}else if(k==3||k==5){uint32_t cs=load(a+2,2);if(k==3){push(r[CS]);push(r[IP]);}r[CS]=cs;r[IP]=v;}else if(k==4)r[IP]=v;else if(k==6)push(v);break;} case 0x06:case 0x0e:case 0x16:case 0x1e:push(r[ES+(op>>3)]);break; case 0x07:case 0x17:case 0x1f:r[ES+(op>>3)]=pop();break; case 0x68:push(fetch(2));break;case 0x6a:push(int8_t(fetch()));break; case 0x98:r[AX]=uint16_t(int16_t(int8_t(r[AX])));break; case 0x99:r[DX]=(r[AX]&0x8000)?65535:0;break; case 0x0f:{ // The 386's SETcc (the reference's _two_byte): the condition as a // byte, flags untouched. run_batch lets only these through. if(!is386)yield(); int op2=fetch();if(op2<0x90||op2>0x9f)yield(); int m=fetch();uint32_t a=m<192?ea(m):0;write(m,1,a,cond(op2&15)?1:0);break;} case 0x9b:break;case 0x9c:push(r[F]);break;case 0x9d:r[F]=pop()|2;break; case 0x9e:r[F]=(r[F]&~(CF|PF|AF|ZF|SF))|((r[AX]>>8)&(CF|PF|AF|ZF|SF))|2;break; case 0x9f:put(4,1,r[F]|2);break; case 0xf5:r[F]^=CF;break;case 0xf8:r[F]&=~CF;break;case 0xf9:r[F]|=CF;break; case 0xfa:r[F]&=~IF;break;case 0xfb:r[F]|=IF;break;case 0xfc:r[F]&=~DF;break;case 0xfd:r[F]|=DF;break; default:yield(); } } }; } static uint32_t run_batch(Core &c, uint32_t count) { // One exit target per batch; guarded data accesses can abort without the // cost of exception unwinding at every memory-mapped device instruction. if (setjmp(c.exit)) { std::memcpy(c.r, c.saved, sizeof(c.r)); return c.done; } for (c.done=0;c.done=c.poll_next) { Core::PollCpu lent{c.r,c.mem,std::size_t(c.mask)+1,c.guard, c.io_events,c.io_event_count,c.mmio_events,c.mmio_count,c.poll_total}; int code=c.dirty_events?0:c.poll_fn(c.poll_context,c.host_base+c.done+1,c.r[F],&lent); if(code==1||code==4){ c.poll_next=c.poll_total+c.done+1+c.poll_period;++c.polls_elided; // Code 4: the poll took an interrupt. The harness charges the // instruction that dispatch edge retires without executing // one, and so does the engine. if(code==4)continue; } else {c.poll_code=uint32_t(code);c.reason=9;break;} } uint32_t pc=c.phys(c.r[CS],c.r[IP]); if(c.guard[pc]&8){c.reason=6;break;} uint8_t opcode=c.mem[pc]; if(opcode==0xec||opcode==0xed||opcode==0xee||opcode==0xef|| opcode==0xe4||opcode==0xe5||opcode==0xe6||opcode==0xe7) { c.prepare_io(opcode); if(c.host_io&&(c.host_ports[c.io_port&0xffff]&c.io_direction)) { uint16_t answer=0; // `now` is the instruction count the harness would see for // this access: the one in flight counts as retired. if(c.host_io(c.host_context,int(c.io_direction),uint16_t(c.io_port), int(c.io_size),uint16_t(c.io_value), c.host_base+c.done+1,&answer)) { if(c.io_direction==1) c.r[AX]=c.io_size==1?(c.r[AX]&~0xffu)|(answer&0xffu) :(c.r[AX]&~0xffffu)|answer; c.reason=0; continue; } } // fast_out: 1 batches any width, 2 only byte writes (a port whose // replay would otherwise have to know the width). if(c.io_direction==2&&c.fast_out&&(c.fast_out[c.io_port]&3)&& ((c.fast_out[c.io_port]&3)==1||c.io_size==1)&& c.io_event_count>8; event[2]=c.io_value;event[3]=c.io_value>>8; c.reason=0; continue; } break; } if(opcode==0xcd&&c.int_mode&&(c.int_mode[c.mem[c.phys(c.r[CS],c.r[IP]+1)]]&1)) { // Handled by step() below. } else if(opcode==0x0f&&c.is386&&(c.mem[c.phys(c.r[CS],c.r[IP]+1)]&0xf0)==0x90) { // SETcc: handled by step() below. } else if(opcode==0xcd||opcode==0x0f||opcode==0xf4){c.reason=7;break;} std::memcpy(c.saved,c.r,sizeof(c.r)); c.step(); for(int j=0;j>(8*i); if(c.mmio_events&&(c.guard[w.address]&64)){ uint8_t *event=c.mmio_events+8*c.mmio_count++; event[0]=w.address;event[1]=w.address>>8;event[2]=w.address>>16;event[3]=w.address>>24; event[4]=w.value;event[5]=w.value>>8;event[6]=uint8_t(w.size);event[7]=0; }} } return c.done; } extern "C" uint32_t courier_x86_run(uint32_t *regs,uint8_t *mem,const uint8_t *guard,uint32_t mask,uint32_t count){ Core c{};std::memcpy(c.r,regs,sizeof(c.r));c.mem=mem;c.guard=guard;c.mask=mask;c.is386=mask==0xffffff; uint32_t done=run_batch(c,count); std::memcpy(regs,c.r,sizeof(c.r));return done; } #include static PyObject *run_objects(PyObject *registers, PyObject *memory, PyObject *guard, PyObject *fast_out, PyObject *io_events, unsigned int count, PyObject *int_mode, PyObject *int_counts, PyObject *host_io, PyObject *host_context, PyObject *host_ports, PyObject *host_base, PyObject *poll_fn, PyObject *poll_context, PyObject *poll_state, PyObject *mmio_events, bool extended=false, bool polling=false) { if (!PyList_Check(registers) || PyList_GET_SIZE(registers)!=14 || !PyByteArray_Check(memory) || !PyByteArray_Check(guard) || !PyByteArray_Check(fast_out) || PyByteArray_GET_SIZE(fast_out)!=65536 || !PyByteArray_Check(io_events) || (PyByteArray_GET_SIZE(io_events)&3) || PyByteArray_GET_SIZE(memory)!=PyByteArray_GET_SIZE(guard) || (PyByteArray_GET_SIZE(memory)!=0x100000 && PyByteArray_GET_SIZE(memory)!=0x1000000)) { PyErr_SetString(PyExc_ValueError,"invalid native CPU buffers"); return nullptr; } Core c{}; uint32_t original[14]; for (int i=0;i<14;++i) { original[i]=c.r[i]=PyLong_AsUnsignedLong(PyList_GET_ITEM(registers,i)); if(PyErr_Occurred())return nullptr; } c.mem=reinterpret_cast(PyByteArray_AS_STRING(memory)); c.guard=reinterpret_cast(PyByteArray_AS_STRING(guard)); c.fast_out=reinterpret_cast(PyByteArray_AS_STRING(fast_out)); c.io_events=reinterpret_cast(PyByteArray_AS_STRING(io_events)); c.io_event_capacity=uint32_t(PyByteArray_GET_SIZE(io_events)/4); c.mask=uint32_t(PyByteArray_GET_SIZE(memory)-1); c.is386=c.mask==0xffffff; if (mmio_events != Py_None) { if (!PyByteArray_Check(mmio_events) || PyByteArray_GET_SIZE(mmio_events) < 8*8*65536) { PyErr_SetString(PyExc_ValueError,"invalid native mmio buffer"); return nullptr; } c.mmio_events=reinterpret_cast(PyByteArray_AS_STRING(mmio_events)); } if (int_mode != Py_None && int_counts != Py_None) { if (!PyByteArray_Check(int_mode) || PyByteArray_GET_SIZE(int_mode)!=256 || !PyByteArray_Check(int_counts) || PyByteArray_GET_SIZE(int_counts)!=1024) { PyErr_SetString(PyExc_ValueError,"invalid native interrupt tables"); return nullptr; } c.int_mode=reinterpret_cast(PyByteArray_AS_STRING(int_mode)); c.int_counts=reinterpret_cast(PyByteArray_AS_STRING(int_counts)); } if (host_io != Py_None) { const unsigned long long function = PyLong_AsUnsignedLongLong(host_io); const unsigned long long context = PyLong_AsUnsignedLongLong(host_context); if (PyErr_Occurred()) return nullptr; if (!PyByteArray_Check(host_ports) || PyByteArray_GET_SIZE(host_ports)!=65536) { PyErr_SetString(PyExc_ValueError,"invalid native port table"); return nullptr; } c.host_io=reinterpret_cast(function); c.host_context=reinterpret_cast(context); c.host_ports=reinterpret_cast(PyByteArray_AS_STRING(host_ports)); if (host_base != Py_None) { c.host_base=PyLong_AsUnsignedLongLong(host_base); if (PyErr_Occurred()) return nullptr; } } if (poll_fn != Py_None) { // poll_state: (total retired before this batch, next poll, period) if (!PyTuple_Check(poll_state) || PyTuple_GET_SIZE(poll_state)!=3) { PyErr_SetString(PyExc_ValueError,"invalid native poll state"); return nullptr; } c.poll_fn=reinterpret_cast(PyLong_AsUnsignedLongLong(poll_fn)); c.poll_context=reinterpret_cast(PyLong_AsUnsignedLongLong(poll_context)); c.poll_total=PyLong_AsUnsignedLongLong(PyTuple_GET_ITEM(poll_state,0)); c.poll_next=PyLong_AsUnsignedLongLong(PyTuple_GET_ITEM(poll_state,1)); c.poll_period=PyLong_AsUnsignedLongLong(PyTuple_GET_ITEM(poll_state,2)); if (PyErr_Occurred()) return nullptr; } uint32_t done=run_batch(c,count); // Convert each register once on entry; publish only changed registers. // Running directly on Core also avoids two redundant full-state copies. if(done||c.reason==8||c.polls_elided)for(int i=0;i<14;++i){ if(c.r[i]!=original[i]){ PyObject *v=PyLong_FromUnsignedLong(c.r[i]);if(!v)return nullptr; PyList_SetItem(registers,i,v); } } if (extended) return Py_BuildValue("IIIIIIIKIIO",done,c.reason,c.io_direction,c.io_port, c.io_size,c.io_value,c.io_event_count, (unsigned long long)c.poll_next,c.poll_code,c.mmio_count, polling ? Py_True : Py_False); return Py_BuildValue("IIIIIIIKII",done,c.reason,c.io_direction,c.io_port, c.io_size,c.io_value,c.io_event_count, (unsigned long long)c.poll_next,c.poll_code,c.mmio_count); } static PyObject *run_python(PyObject *, PyObject *args) { PyObject *registers, *memory, *guard, *fast_out, *io_events; PyObject *int_mode = Py_None, *int_counts = Py_None; PyObject *host_io = Py_None, *host_context = Py_None, *host_ports = Py_None; PyObject *host_base = Py_None; PyObject *poll_fn = Py_None, *poll_context = Py_None, *poll_state = Py_None; PyObject *mmio_events = Py_None; unsigned int count; if (!PyArg_ParseTuple(args, "OOOOOI|OOOOOOOOOO", ®isters, &memory, &guard, &fast_out, &io_events, &count, &int_mode, &int_counts, &host_io, &host_context, &host_ports, &host_base, &poll_fn, &poll_context, &poll_state, &mmio_events)) return nullptr; return run_objects(registers, memory, guard, fast_out, io_events, count, int_mode, int_counts, host_io, host_context, host_ports, host_base, poll_fn, poll_context, poll_state, mmio_events); } // Whole Python/native call setup, not a different execution or polling policy. // Names are passed as an immutable tuple so dictionary lookups do not allocate // temporary strings on every batch. Only exact harness classes use this path. enum RunnerField { RF_REGS, RF_MEMORY, RF_HOST, RF_HOST_BASE, RF_RETIRED, RF_POLL, RF_CLOCK_CALLBACK, RF_CLOCK_NEXT, RF_CLOCK_PERIOD, RF_MMIO_CALLBACK, RF_MMIO_BATCH, RF_BEFORE, RF_AFTER, RF_INT_MODE, RF_GUARD, RF_FAST_OUT, RF_IO_EVENTS, RF_INT_COUNTS, RF_MMIO_EVENTS, RF_RUN, RF_LEGACY_RUN, RF_AFTER_GATE, RF_COUNT }; struct RunnerRef { PyObject *p; explicit RunnerRef(PyObject *value=nullptr):p(value) {} ~RunnerRef() { Py_XDECREF(p); } RunnerRef(const RunnerRef&)=delete; RunnerRef& operator=(const RunnerRef&)=delete; explicit operator bool() const { return p!=nullptr; } }; static PyObject *runner_field(PyObject *dict, PyObject *keys, int index) { PyObject *key=PyTuple_GET_ITEM(keys,index); PyObject *value=PyDict_GetItemWithError(dict,key); if (!value && !PyErr_Occurred()) PyErr_Format(PyExc_AttributeError,"missing native runner field %R",key); return Py_XNewRef(value); } static bool runner_callback(PyObject *function) { if (function==Py_None) return true; RunnerRef result(PyObject_CallNoArgs(function)); return bool(result); } // A worker request which is already false does nothing. While AT input is // queued outside data mode, _serial_receive_quiet_until is necessarily None; // timer_poll_static therefore rejects arm. _serial_started independently // rejects fast_service_static. All other cases keep the full Python checks. static int worker_before_needed(PyObject *cpu, PyObject *callback) { RunnerRef gate(PyObject_GetAttrString(cpu,"native_before_run_gate")); if (!gate) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) return -1; PyErr_Clear(); return 1; } if (!PyTuple_Check(gate.p) || PyTuple_GET_SIZE(gate.p)!=5 || PyTuple_GET_ITEM(gate.p,0)!=callback) return 1; PyObject *request=PyTuple_GET_ITEM(gate.p,1); if (!PyList_CheckExact(request) || PyList_GET_SIZE(request)!=1) return 1; if (PyList_GET_ITEM(request,0)==Py_False) return 0; if (PyList_GET_ITEM(request,0)!=Py_True) return 1; PyObject *names=PyTuple_GET_ITEM(gate.p,3); if (!PyTuple_Check(names) || PyTuple_GET_SIZE(names)!=3) return 1; RunnerRef machine(PyObject_GenericGetDict(PyTuple_GET_ITEM(gate.p,2),nullptr)); if (!machine) return -1; PyObject *started=PyDict_GetItemWithError(machine.p,PyTuple_GET_ITEM(names,0)); if (PyErr_Occurred()) return -1; bool reject=started==Py_True; if (!reject) { PyObject *online=PyDict_GetItemWithError(machine.p,PyTuple_GET_ITEM(names,1)); if (PyErr_Occurred()) return -1; if (online==Py_False) { PyObject *rx=PyDict_GetItemWithError(machine.p,PyTuple_GET_ITEM(names,2)); if (PyErr_Occurred()) return -1; PyObject *deque_type=PyTuple_GET_ITEM(gate.p,4); if (rx && reinterpret_cast(Py_TYPE(rx))==deque_type) { const Py_ssize_t length=PyObject_Length(rx); if (length<0) return -1; reject=length!=0; } } } if (reject) { // arm() begins by clearing this request, even when it rejects. PyList_SetItem(request,0,Py_NewRef(Py_False)); return 0; } return 1; } static PyObject *run_cpu_python(PyObject *, PyObject *args) { PyObject *cpu, *wrapper, *keys; unsigned int count; if (!PyArg_ParseTuple(args,"OOIO",&cpu,&wrapper,&count,&keys)) return nullptr; if (!PyTuple_Check(keys) || PyTuple_GET_SIZE(keys)!=RF_COUNT) { PyErr_SetString(PyExc_ValueError,"invalid native runner field names"); return nullptr; } RunnerRef initial(PyObject_GenericGetDict(cpu,nullptr)); if (!initial) return nullptr; RunnerRef host(runner_field(initial.p,keys,RF_HOST)); if (!host) return nullptr; RunnerRef host_parts(host.p==Py_None ? Py_NewRef(Py_None) : PySequence_Fast(host.p,"invalid native host I/O tuple")); if (!host_parts) return nullptr; if (host.p!=Py_None && PySequence_Fast_GET_SIZE(host_parts.p)!=3) { PyErr_SetString(PyExc_ValueError,"invalid native host I/O tuple"); return nullptr; } RunnerRef host_base, poll_parts, poll_values, mmio; bool polling=false, batching=false; if (host.p!=Py_None) { RunnerRef base(runner_field(initial.p,keys,RF_HOST_BASE)); RunnerRef retired(runner_field(initial.p,keys,RF_RETIRED)); if (!base || !retired) return nullptr; host_base.p=PyNumber_Add(base.p,retired.p); if (!host_base) return nullptr; RunnerRef poll(runner_field(initial.p,keys,RF_POLL)); if (!poll) return nullptr; if (poll.p!=Py_None) { RunnerRef clock(runner_field(initial.p,keys,RF_CLOCK_CALLBACK)); if (!clock) return nullptr; if (clock.p!=Py_None) { polling=true; poll_parts.p=PySequence_Fast(poll.p,"invalid native poll tuple"); if (!poll_parts) return nullptr; if (PySequence_Fast_GET_SIZE(poll_parts.p)!=2) { PyErr_SetString(PyExc_ValueError,"invalid native poll tuple"); return nullptr; } RunnerRef next(runner_field(initial.p,keys,RF_CLOCK_NEXT)); RunnerRef period(runner_field(initial.p,keys,RF_CLOCK_PERIOD)); if (!next || !period) return nullptr; poll_values.p=PyTuple_Pack(3,retired.p,next.p,period.p); if (!poll_values) return nullptr; } } } RunnerRef mmio_callback(runner_field(initial.p,keys,RF_MMIO_CALLBACK)); if (!mmio_callback) return nullptr; if (mmio_callback.p!=Py_None) { RunnerRef batch(runner_field(initial.p,keys,RF_MMIO_BATCH)); if (!batch) return nullptr; const int truth=PyObject_IsTrue(batch.p); if (truth<0) return nullptr; batching=truth; if (batching) { mmio.p=PyObject_GetAttr(wrapper,PyTuple_GET_ITEM(keys,RF_MMIO_EVENTS)); if (!mmio) return nullptr; } } // Preserve ordering: host/poll/MMIO metadata is captured before the hook; // registers, memory and interrupt buffers are obtained after it. Keep every // borrowed execution buffer alive even if a native I/O callback replaces it. RunnerRef before(PyObject_GetAttr(cpu,PyTuple_GET_ITEM(keys,RF_BEFORE))); if (!before) return nullptr; const int before_needed=before.p==Py_None ? 0 : worker_before_needed(cpu,before.p); if (before_needed<0 || (before_needed && !runner_callback(before.p))) return nullptr; RunnerRef state(PyObject_GenericGetDict(cpu,nullptr)); RunnerRef buffers(PyObject_GenericGetDict(wrapper,nullptr)); if (!state || !buffers) return nullptr; RunnerRef registers(runner_field(state.p,keys,RF_REGS)); RunnerRef memory(runner_field(state.p,keys,RF_MEMORY)); RunnerRef mode(runner_field(state.p,keys,RF_INT_MODE)); RunnerRef guard(runner_field(buffers.p,keys,RF_GUARD)); RunnerRef fast(runner_field(buffers.p,keys,RF_FAST_OUT)); RunnerRef events(runner_field(buffers.p,keys,RF_IO_EVENTS)); RunnerRef counts(runner_field(buffers.p,keys,RF_INT_COUNTS)); RunnerRef run(runner_field(buffers.p,keys,RF_RUN)); RunnerRef legacy(runner_field(buffers.p,keys,RF_LEGACY_RUN)); if (!registers || !memory || !mode || !guard || !fast || !events || !counts || !run || !legacy) return nullptr; PyObject *fn=host.p==Py_None ? Py_None : PySequence_Fast_GET_ITEM(host_parts.p,0); PyObject *context=host.p==Py_None ? Py_None : PySequence_Fast_GET_ITEM(host_parts.p,1); PyObject *ports=host.p==Py_None ? Py_None : PySequence_Fast_GET_ITEM(host_parts.p,2); PyObject *poll_fn=polling ? PySequence_Fast_GET_ITEM(poll_parts.p,0) : Py_None; PyObject *poll_context=polling ? PySequence_Fast_GET_ITEM(poll_parts.p,1) : Py_None; RunnerRef result; if (run.p==legacy.p) { result.p=run_objects(registers.p,memory.p,guard.p,fast.p,events.p,count, mode.p,counts.p,fn,context,ports,host_base.p ? host_base.p : Py_None, poll_fn,poll_context,poll_values.p ? poll_values.p : Py_None, batching ? mmio.p : Py_None,true,polling); } else { // Retain private/debug run replacements, including their original arity. const int n=batching ? 16 : polling ? 15 : host.p!=Py_None ? 12 : 8; RunnerRef budget(PyLong_FromUnsignedLong(count)); RunnerRef callargs(PyTuple_New(n)); if (!budget || !callargs) return nullptr; PyObject *values[]={registers.p,memory.p,guard.p,fast.p,events.p,budget.p, mode.p,counts.p,fn,context,ports,host_base.p ? host_base.p : Py_None, poll_fn,poll_context,poll_values.p ? poll_values.p : Py_None, batching ? mmio.p : Py_None}; for (int i=0;i(fn)(reinterpret_cast(context))!=0; } } } if (call_after && !runner_callback(after.p)) return nullptr; PyObject *answer=result.p; result.p=nullptr; return answer; } static PyObject *inject_interrupt_python(PyObject *, PyObject *args) { PyObject *registers, *memory; unsigned int vector; if (!PyArg_ParseTuple(args, "OOI", ®isters, &memory, &vector)) return nullptr; if (!PyList_Check(registers) || PyList_GET_SIZE(registers)!=14 || !PyByteArray_Check(memory) || PyByteArray_GET_SIZE(memory)<1024 || vector>255) { PyErr_SetString(PyExc_ValueError,"invalid native interrupt state"); return nullptr; } uint32_t r[14]; for (int i=0;i<14;++i) { r[i]=PyLong_AsUnsignedLong(PyList_GET_ITEM(registers,i)); if(PyErr_Occurred())return nullptr; } auto *mem=reinterpret_cast(PyByteArray_AS_STRING(memory)); const std::size_t length=std::size_t(PyByteArray_GET_SIZE(memory)); const uint32_t table=vector*4; const uint16_t offset=uint16_t(mem[table]|uint16_t(mem[table+1])<<8); const uint16_t segment=uint16_t(mem[table+2]|uint16_t(mem[table+3])<<8); if(!offset&&!segment)Py_RETURN_FALSE; uint16_t sp=uint16_t(r[SP]); const uint16_t values[]={uint16_t(r[F]),uint16_t(r[CS]),uint16_t(r[IP])}; for(uint16_t value:values) { sp=uint16_t(sp-2); const uint32_t address=((r[SS]&65535)*16+sp)%length; mem[address]=uint8_t(value);mem[(address+1)%length]=uint8_t(value>>8); } // A hardware interrupt clears both the interrupt and trap flags. Leaving // TF set would single-step the first instruction of the handler and can // recursively enter INT 1 before the device ISR has saved its context. r[SP]=sp;r[F]=uint16_t(r[F])&~(IF|0x100);r[CS]=segment;r[IP]=offset; for(int i=0;i<14;++i) { PyObject *value=PyLong_FromUnsignedLong(r[i]); if(!value)return nullptr; PyList_SetItem(registers,i,value); } Py_RETURN_TRUE; } static PyMethodDef methods[]={ {"run",run_python,METH_VARARGS,"Execute guarded interpreter instructions."}, {"run_cpu",run_cpu_python,METH_VARARGS,"Run with native argument setup and before/after hooks."}, {"inject_interrupt",inject_interrupt_python,METH_VARARGS,"Enter a real-mode interrupt."}, {nullptr,nullptr,0,nullptr} }; static PyModuleDef module={PyModuleDef_HEAD_INIT,"_x86_native",nullptr,-1,methods,nullptr,nullptr,nullptr,nullptr}; PyMODINIT_FUNC PyInit__x86_native(){return PyModule_Create(&module);}