CpuX8086 module

class CpuX8086.TraceRecord(opcode: str, operands: List[str], pseudo_bytes: Optional[List[int]] = None, regs_before: Dict[str, int] = <factory>, regs_after: Dict[str, int] = <factory>, flags_before: Dict[str, int] = <factory>, flags_after: Dict[str, int] = <factory>, mem_accesses: List[Tuple[str, int, int, int]] = <factory>)[source]

Bases: object

opcode: str
operands: List[str]
pseudo_bytes: List[int] | None = None
regs_before: Dict[str, int]
regs_after: Dict[str, int]
flags_before: Dict[str, int]
flags_after: Dict[str, int]
mem_accesses: List[Tuple[str, int, int, int]]
class CpuX8086.TracedMemory(base_memory)[source]

Bases: object

Envueltura de Memory que registra accesos R/W para la traza.

peek(page: int, addr: int) int[source]
poke(page: int, addr: int, val: int) None[source]
class CpuX8086.Icons(value)[source]

Bases: Enum

Icons used in the terminal interface.

MACHINE_CODE: str = '🖥️  '
class CpuX8086.RegisterSet[source]

Bases: object

Represents a set of processor registers and flags. Provides methods to get, set, and display registers, as well as update flag values based on assembly operations.

__init__() None[source]

Initializes processor registers and flags. Sets up a dictionary to track the previous values of registers before any changes.

get

Dispatch methods based on type signature

See also

Dispatcher

set

Dispatch methods based on type signature

See also

Dispatcher

update_flags(result: int, operation: str | None = None, carry: bool | None = None) None[source]

Updates ZF, SF, PF and (optionally) CF on a 16-bit result.

  • ZF/SF: computed over 16 bits

  • PF: even parity of the low 8 bits (8086 semantics)

  • CF: updated only when the operation defines it and carry is provided

print_changed_registers(out: Callable[[str], None] | None = None, use_colors: bool = True) None[source]

Emite solo los registros cuyo valor cambió desde la última ejecución. - out: función para emitir líneas (por defecto: print) - use_colors: si False, quita códigos ANSI (útil para web que no los renderiza)

print_registers() None[source]

Prints all registers and flags in decimal, hexadecimal, and binary formats.

Returns:

None

set_register_upper(reg: int, value: int) int[source]

Set the upper 8 bits of a 16-bit register to a new value.

Parameters:
  • reg (int) – 16bit value

  • value (int) – 8bit value

Returns:

16bit value with the upper 8 bits set to the new value.

Return type:

int

set_register_lower(reg: int, value: int) int[source]

Set the lower 8 bits of a 16-bit register to a new value.

Parameters:
  • reg (int) – 16bit value

  • value (int) – 8bit value

Returns:

16bit value with the lower 8 bits set to the new value.

Return type:

int

class CpuX8086.InstructionParser[source]

Bases: object

Parses and executes assembly instructions, handling arithmetic and bitwise operations on registers, and providing detailed error messages.

__init__() None[source]

Configures the lexer and parser to analyze assembly instructions. Initializes the maps of instruction methods and machine codes.

load_program(lines: List[str], base_addr: int = 0) None[source]

Carga un listado de instrucciones (cada línea) y extrae labels ‘mi_label:’ al inicio de línea.

add_breakpoint(target: str | int) None[source]
remove_breakpoint(target: str | int) None[source]
clear_breakpoints() None[source]
step(memory) str | None[source]

Ejecuta 1 instrucción del programa cargado (step_mode) respetando breakpoints. Devuelve la línea ejecutada o None si terminó.

cont(memory, max_steps: int = 10000) None[source]
disassemble_line(line: str, addr: int | None = None) str[source]
disassemble_program(base_addr: int | None = None) List[str][source]
assemble_line(line: str) List[int][source]

Ensambla UNA línea ASM → lista de bytes (educativo, subset). No ejecuta la instrucción ni toca registros.

monitor(cmd: str, memory) None[source]

Comandos: - trace on|off - bp <label|addr> - delbp <label|addr> - watch <expr> - unwatch <expr> - step - cont - disas

handle_instruction(p: list) None[source]

Calls the appropriate operation method based on the opcode.

Parameters:

p (list) – List of instruction tokens.

Returns:

None

operands_multiple(p: list) list[source]

Converts a list of operands into a manageable list of two elements.

Parameters:

p (list) – List of operand tokens.

Returns:

List containing the first and third tokens.

Return type:

list

operand_register(p: list) str[source]

Gets the register name in uppercase.

Parameters:

p (list) – Register token.

Returns:

Register name in uppercase.

Return type:

str

operand_number(p: list) int | None[source]

Converts a number from binary, hexadecimal, or decimal to decimal format.

Parameters:

p (list) – Number token in binary, hexadecimal, or decimal format.

Returns:

Decimal value of the number.

Return type:

int

handle_parse_error(token) None[source]

Displays an error message when a syntax error occurs in the parser.

Parameters:

token (Token) – Token that caused the syntax error.

Returns:

None

parse(instruction: str, memory: Memory, dry_run: bool = False) dict | None[source]

Parses a single assembly instruction, executes it, and returns its details.

Parameters:
  • instruction (str) – Assembly instruction as a text string.

  • memory (Memory) – Memory object representing the system’s memory.

Returns:

Parsed tokens including opcode and operands.

Return type:

dict

Raises:
  • ValueError – If the instruction format is invalid.

  • KeyError – If the opcode is not supported.

add_watch(expr: str) None[source]
remove_watch(expr: str) None[source]
asm_int(operands: List[str], memory) None[source]

INT <vector> Soporta INT 0x21 con servicios: AH=09h, 0Ah, 4Ch. - 09h: imprime cadena en DS:DX hasta ‘$’ - 0Ah: lee buffer en DS:DX (long máx en [DS:DX], long real en [DS:DX+1], datos a partir de [DS:DX+2], termina con 0x00) - 4Ch: termina con código en AL

clear_watches() None[source]
int_0x21(ah: int, memory: dict, registers: dict) None[source]

Simula la interrupción 0x21 para servicios básicos de DOS.

Parameters:
  • ah (int) – El registro AH contiene el número del servicio.

  • memory (dict) – Simulación de la memoria del sistema.

  • registers (dict) – Registros del procesador (AX, BX, CX, etc.).

Returns:

None

enable_trace(enabled: bool = True, out: Callable[[str], None] | None = None, color: bool | None = None) None[source]

Activa/desactiva la traza. Si ‘out’ es None, se imprime con Terminal. En ese caso, si ‘colored’ es True (o self.trace_color ya es True), se agregan colores ANSI. Si se pasa ‘out’, no se colorea para no contaminar salidas de tests/logging.

_encode_pseudo_bytes(opcode: str, operands: List[str]) List[int] | None[source]

Mini codificador educativo (NO 8086 real). Solo para mostrar ‘bytes (pseudo)’ en la traza. Reg mapa: AX=0,BX=3,CX=1,DX=2,SP=4,BP=5,SI=6,DI=7

service_09(memory: Memory, registers: dict) None[source]
service_0a(memory: Memory, registers: dict) None[source]
service_4c(registers: dict) None[source]
asm_push

Dispatch methods based on type signature

See also

Dispatcher

asm_pop

Dispatch methods based on type signature

See also

Dispatcher

asm_mov

Dispatch methods based on type signature

See also

Dispatcher

asm_add

Dispatch methods based on type signature

See also

Dispatcher

asm_sub

Dispatch methods based on type signature

See also

Dispatcher

asm_and

Dispatch methods based on type signature

See also

Dispatcher

asm_or

Dispatch methods based on type signature

See also

Dispatcher

asm_xor

Dispatch methods based on type signature

See also

Dispatcher

asm_not

Dispatch methods based on type signature

See also

Dispatcher

asm_neg

Dispatch methods based on type signature

See also

Dispatcher

asm_inc

Dispatch methods based on type signature

See also

Dispatcher

asm_dec

Dispatch methods based on type signature

See also

Dispatcher

asm_shl

Dispatch methods based on type signature

See also

Dispatcher

asm_shr

Dispatch methods based on type signature

See also

Dispatcher

asm_rol

Dispatch methods based on type signature

See also

Dispatcher

asm_ror

Dispatch methods based on type signature

See also

Dispatcher

assemble(asm_code: str, memory: Memory) List[int][source]

Ensambla un bloque multilínea usando parse(…, dry_run=True) para tokenizar y luego codifica a bytes (subset educativo).

execute_and_print(instruction: str, memory: Memory) None[source]

Executes an assembly instruction and shows only the registers that changed.

Parameters:

instruction (str) – Assembly instruction as a text string.

Returns:

None

class CpuX8086.CpuX8086[source]

Bases: object

Class emulating a 8086 CPU.

parse_instruction(cmd: str, memory: Memory) None[source]

Parse the assembler instructions affecting the registers if necesary.

Parameters:

{str} (cmd) – Assembler instruction.

Returns:

None.

_find_matches(d: Dict[str, str], item: str)[source]
Parameters:
  • {str} (d) – Regex Dictionary

  • item (str) – Item to be look for.

Returns:

Item found, or None if not.

Return type:

Dict[str]

_16to8(hl: int) Tuple[int][source]

Decode a 16-bit number in 2 8-bit numbers (high, low).

get_bin

Dispatch methods based on type signature

See also

Dispatcher

get_hex

Dispatch methods based on type signature

See also

Dispatcher

assemble(memory: Memory, code: str) str[source]

Assemble the code into machine code.

Parameters:
  • memory (Memory) – Memory object class.

  • code (str) – Code to be assembled.

Returns:

Machine code.

Return type:

str

print_registers() None[source]

Print the CPU registers and it’s value.

move(memory: Memory, from_begin: int, from_end: int, destination: int) bool[source]

Copy a memory region to other memory region.

Parameters:
  • memory (Memory) – A Memory class object.

  • from_begin (int) – Source’s begin.

  • from_end (int) – Source’s end.

  • destination (int) – Destination’s begin.

Returns:

Operation result.

Return type:

bool

fill(memory: Memory, start: int, end: int, pattern: str) bool[source]

Fill a memory region with a specified pattern.

Parameters:
  • memory (Memory) – A Memory class object.

  • start (int) – Source’s begin.

  • end (int) – Source’s end.

  • pattern (str) – Pattern.

Returns:

Operation result. Always true.

Return type:

bool

search(memory: Memory, start: int, pattern: str) List[str][source]

Search a pattern in the memory. Staring from <start> to the end of the page.

Parameters:
  • memory (Memory) – Memory class object.

  • start (int) – Starting point from the search.

  • pattern (str) – Pattern to search for.

Returns:

[str]

load_into(memory: Memory, start: int, text: str) None[source]

Load a text into memory, starting from an address.

Parameters:
  • memory (Memory) – Memory object class.

  • start (int) – Address memory where to begin.

  • text (str) – Text to be load into.

Returns:

None

compare(memory: Memory, cfrom: int, cend: int, cto: int) List[str][source]

Compares two memory regions.

Parameters:
  • memory (Memory) – Memory object class.

  • cfrom (int) – Source address memory where to start.

  • cend (int) – Source address memory where to end.

  • cto (int) – Destination address memory.

Returns:

The differences between regions.

Return type:

[str]

cat(disk: Disk, addrb: int, addrn: int) None[source]

Shows the content of the vdisk region.

Parameters:
  • disk – A Disk class type object.

  • addrb – Start address.

  • addrn – End address.

Returns:

display(memory: Memory, addrb: int, addrn: int) None[source]

Displays a memory region.

Parameters:
  • memory – A Memory class type object.

  • addrb – Start address.

  • addrn – End address.

Returns:

None.

write_to_vdisk(memory: Memory, disk: Disk, address: int, firstsector: int, number: int) None[source]

Writes onto vdisk a memory block.

Parameters:
  • memory (Memory) – A Memory type class object.

  • disk (Disk) – A Disk type class object.

  • address (int) – Source memory address.

  • firstsector (int) – Destination sector address.

  • number (int) – Number of bytes to be copied.

Returns:

None.

read_from_vdisk(memory: Memory, disk: Disk, address: int, firstsector: int, number: int) None[source]

Loads into memory a vdisk block.

Parameters:
  • memory (Memory) – A Memory type class object.

  • disk (Disk) – A Disk type class object.

  • address (int) – Destination memory address.

  • firstsector (int) – Source sector address.

  • number (int) – Number of bytes to be copied.

Returns:

None.