There are no relocations in this file.
No processor specific unwind information to decode
Symbol table '.symtab' contains 8 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
1: 00000000 0 FILE LOCAL DEFAULT ABS calculator.asm
2: 0804a000 0 NOTYPE LOCAL DEFAULT 2 result_prefix
3: 0804a008 0 NOTYPE LOCAL DEFAULT 2 sum_str
4: 08049000 0 NOTYPE GLOBAL DEFAULT 1 _start
5: 0804a00b 0 NOTYPE GLOBAL DEFAULT 2 __bss_start
6: 0804a00b 0 NOTYPE GLOBAL DEFAULT 2 _edata
7: 0804a00c 0 NOTYPE GLOBAL DEFAULT 2 _end
No version information found in this file. swed@DESKTOP-K5N5PON:~$ ./calculator.elf
Result: 12
Работай с этим кодом: // Instructions.cpp
#include "Emulator.h"
#include
#include <stdint.h>
#include
// Реализация обработчиков инструкций
// MUL EAX
void Emulator::instr_MUL_EAX() {
uint8_t modrm = fetch_byte();
// Для простоты реализуем только MUL EAX
if ((modrm & 0x38) == 0x20) { // Проверяем, что это MUL r/m32
regs.EAX *= regs.EAX;
update_ZF(regs.EAX);
}
else {
std::cout << "MUL instruction with unsupported operand.\n";
// Можно установить флаг ошибки или завершить выполнение
}
}
// Zero Flag
if (result == 0)
regs.EFLAGS |= ZF;
else
regs.EFLAGS &= ~ZF;
// Carry Flag
if (*reg_ptr < imm8)
regs.EFLAGS |= CF;
else
regs.EFLAGS &= ~CF;
// Sign Flag (SF)
if (result & (1 << 31))
regs.EFLAGS |= (1 << 7); // Предполагаем, что SF находится в бит 7
else
regs.EFLAGS &= ~(1 << 7);
// Overflow Flag (OF) - необходимо корректно реализовать
// Здесь может быть упрощение, для точной реализации требуется дополнительная логика
}
else {
std::cout << "CMP instruction with unsupported register.\n";
// Можно установить флаг ошибки или завершить выполнение
}
}
// JE rel8
void Emulator::instr_JE_rel8() {
int8_t rel = fetch_byte();
if (regs.EFLAGS & ZF) {
regs.EIP += rel;
}
}
// JNE rel8
void Emulator::instr_JNE_rel8() {
int8_t rel = fetch_byte();
if (!(regs.EFLAGS & ZF)) {
regs.EIP += rel;
}
}
// CMP EAX, imm32
void Emulator::instr_CMP_EAX_imm32() {
uint32_t imm = fetch_dword();
uint32_t result = regs.EAX - imm;
if (regs.EAX == imm)
regs.EFLAGS |= ZF;
else
regs.EFLAGS &= ~ZF;
// Дополнительно можно установить другие флаги (CF, OF и т.д.)
}
// Обработчик инструкции RET
void Emulator::instr_RET() {
if (regs.ESP + 4 > memory.size()) {
std::cout << "Stack underflow on RET.\n";
error_flag = true;
running = false;
return;
}
// Pop the return address from the stack
uint32_t return_address = read_memory_dword(regs.ESP);
regs.ESP += 4;
// Jump to the return address
regs.EIP = return_address;
}
// Обработчик инструкции SUB r32, imm32
void Emulator::instr_SUB_r32_imm32() {
uint8_t modrm = fetch_byte();
uint8_t reg_opcode = (modrm >> 3) & 0x07; // Извлекаем поле reg из ModRM
if (reg_opcode != 5) { // Для инструкции SUB reg, imm32, reg_opcode должен быть 5
std::cout << "Unsupported SUB instruction with reg opcode: " << (int)reg_opcode << "\n";
return;
}
uint32_t imm32 = fetch_dword(); // Извлекаем непосредственное значение
uint8_t rm = regm_rm(modrm); // Извлекаем регистр назначения из ModRM
uint32_t* reg_ptr = get_register_by_code(rm);
if (reg_ptr) {
*reg_ptr -= imm32;
update_ZF(*reg_ptr);
}
else {
std::cout << "SUB instruction with unsupported register.\n";
}
uint32_t* src_reg = get_register_by_code(reg_code);
if (mod == 3) { // Режим регистр-регистр
uint32_t* dest_reg = get_register_by_code(rm_code);
if (src_reg && dest_reg) {
*dest_reg += *src_reg;
update_ZF(*dest_reg);
// Обновите другие флаги, если необходимо (Carry, Overflow и т.д.)
}
else {
std::cout << "Неизвестный регистр в ADD r/m32, r32.\n";
error_flag = true;
running = false;
}
}
else { // Операнд r/m32 является памятью
uint32_t address = calculate_address(modrm);
if (error_flag) return;
uint32_t value = read_memory_dword(address);
value += *src_reg;
// Записываем результат обратно в память
write_memory_dword(address, value);
update_ZF(value);
// Обновите другие флаги, если необходимо
}
}
void Emulator::instr_CMP_AL_imm8() {
uint8_t imm8 = fetch_byte();
uint8_t al = regs.EAX & 0xFF;
uint8_t result = al - imm8;
// Update Zero Flag (ZF)
if (result == 0)
regs.EFLAGS |= ZF;
else
regs.EFLAGS &= ~ZF;
// Update Sign Flag (SF)
if (result & 0x80)
regs.EFLAGS |= SF;
else
regs.EFLAGS &= ~SF;
// Update Carry Flag (CF)
if (al < imm8)
regs.EFLAGS |= CF;
else
regs.EFLAGS &= ~CF;
// Update Overflow Flag (OF)
bool overflow = ((al ^ imm8) & (al ^ result) & 0x80) != 0;
if (overflow)
regs.EFLAGS |= OF;
else
regs.EFLAGS &= ~OF;
uint32_t base_value = 0;
uint32_t index_value = 0;
// Получаем значение base
if (base == 5) {
if (mod == 0) {
// base = 0, disp32 используется вместо base
base_value = 0;
displacement += fetch_dword(); // Дополнительный disp32
}
else {
base_value = *get_register_by_code(base);
}
}
else {
base_value = *get_register_by_code(base);
}
// Получаем значение index
if (index != 4) { // Если index не равно 4 (4 означает, что index не используется)
index_value = *get_register_by_code(index) << scale;
}
uint32_t address = base_value + index_value + displacement;
return address;
// Загрузка программы из бинарного файла
std::vector<uint8_t> program = load_program_from_file(filename);
if (program.empty()) {
std::cerr << "Ошибка: Не удалось загрузить программу из файла: " << filename << "\n";
return false;
}
// Загрузка программы в память по адресу 0x0000 и установка EIP
emulator.load_program(program, 0x0000, true);
// Запуск эмулятора
emulator.run();
// Проверка на ошибки
return !emulator.has_error();
; add eax, 7 ; Добавление 7 к EAX (EAX = 12)
add eax, 7
; mov ebx, eax ; Копирование EAX в EBX
mov ebx, eax
; mov ecx, sum_str ; Установка ECX на адрес "sum_str"
mov ecx, sum_str
; xor edx, edx ; Очистка EDX перед делением
xor edx, edx
; mov esi, 10 ; Загрузка 10 в ESI
mov esi, 10
; div esi ; Деление EAX на ESI, результат в EAX, остаток в EDX
div esi
; add al, '0' ; Преобразование десятков в ASCII ('1')
add al, '0'
; mov [ecx], al ; Сохранение десятков в sum_str[0]
mov [ecx], al
; mov eax, edx ; Перемещение остатка в EAX (EAX = 2)
mov eax, edx
; add al, '0' ; Преобразование единиц в ASCII ('2')
add al, '0'
; mov [ecx+1], al ; Сохранение единиц в sum_str[1]
mov [ecx+1], al
; mov byte [ecx+2], 0x0A ; Добавление символа новой строки в sum_str[2]
mov byte [ecx+2], 0x0A
; mov eax, 4 ; Номер системного вызова sys_write
mov eax, 4
; mov ebx, 1 ; Дескриптор файла 1 (stdout)
mov ebx, 1
; mov ecx, result_prefix ; Адрес строки "Result: "
mov ecx, result_prefix
; mov edx, 8 ; Длина строки "Result: "
mov edx, 8
; int 0x80 ; Вызов системного прерывания для вывода "Result: "
int 0x80
; mov eax, 4 ; Номер системного вызова sys_write
mov eax, 4
; mov ebx, 1 ; Дескриптор файла 1 (stdout)
mov ebx, 1
; mov ecx, sum_str ; Адрес строки "sum_str" (результат)
mov ecx, sum_str
; mov edx, 3 ; Длина строки "sum_str" (2 цифры + новая строка)
mov edx, 3
; int 0x80 ; Вызов системного прерывания для вывода суммы
int 0x80
; mov eax, 1 ; Номер системного вызова sys_exit
mov eax, 1
; mov ebx, 0 ; Код выхода 0
mov ebx, 0
; int 0x80 ; Вызов системного прерывания для выхода
int 0x80
SECTION .data
; Строка "Result: " (8 байт) начинается на метке result_prefix
result_prefix db 'Result: '
; Строка для суммы "sum_str" (3 байта) инициализирована нулями
sum_str db 0x00, 0x00, 0x00
The issue you're experiencing stems from the incomplete handling of the opcode 0x81 in your emulator. Specifically, the ADD instruction with an immediate value is not being correctly executed.
Understanding the Problem
In your assembly code, the instruction add eax, 7 is being assembled into the opcode 0x81 followed by the ModRM byte and the immediate value. The encoding is as follows:
Opcode: 0x81
ModRM Byte: Determines the operation and the operands.
Immediate Value: The value 7 in your case.
The 0x81 opcode is part of the group of instructions known as Group 1 instructions in x86 architecture. The operation performed by the instruction depends on the reg field in the ModRM byte.
In your specific case, the add eax, 7 instruction is encoded as:
Looking at your emulator code, you have the following handler for the opcode 0x81:
instruction_set[0x81] = &Emulator::instr_SUB_r32_imm32; // Handler for SUB r32, imm32
However, this handler only processes the SUB operation when the reg field in the ModRM byte is 5. For other values of reg, it outputs an error message and returns without executing any operation. This means that when the reg field is 0 (which represents the ADD operation), the emulator does not perform any action.
As a result, the add eax, 7 instruction is effectively skipped, leaving EAX unchanged with the value 5. Consequently, when the division by 10 is performed later, it operates on the incorrect value, leading to the output 05 instead of 12.
Solution
To resolve this issue, you need to implement a proper handler for the opcode 0x81 that can handle all the possible operations indicated by the reg field in the ModRM byte. This includes ADD, OR, ADC, SBB, AND, SUB, XOR, and CMP.
Here's how you can modify your code:
Create a General Handler for Opcode 0x81
Instead of having a handler specific to SUB, create a general handler that can process all Group 1 operations based on the reg field:
void Emulator::instr_GROUP1_Ev_Iz() {
uint8_t modrm = fetch_byte();
uint8_t mod = modrm >> 6;
uint8_t reg_opcode = (modrm >> 3) & 0x07; // reg field in ModRM
uint8_t rm = modrm & 0x07;
uint32_t* dest_reg = nullptr;
if (mod == 3) {
dest_reg = get_register_by_code(rm);
} else {
// Handle memory operands if necessary
std::cout << "Memory operands not implemented for opcode 0x81.\n";
error_flag = true;
running = false;
return;
}
uint32_t imm32 = fetch_dword();
if (!dest_reg) {
std::cout << "Unknown destination register in opcode 0x81.\n";
error_flag = true;
running = false;
return;
}
switch (reg_opcode) {
case 0: // ADD
*dest_reg += imm32;
update_ZF(*dest_reg);
break;
case 1: // OR
*dest_reg |= imm32;
update_ZF(*dest_reg);
break;
case 2: // ADC
// Implement ADC if needed
break;
case 3: // SBB
// Implement SBB if needed
break;
case 4: // AND
*dest_reg &= imm32;
update_ZF(*dest_reg);
break;
case 5: // SUB
*dest_reg -= imm32;
update_ZF(*dest_reg);
break;
case 6: // XOR
*dest_reg ^= imm32;
update_ZF(*dest_reg);
break;
case 7: // CMP
{
uint32_t result = *dest_reg - imm32;
update_ZF(result);
// Update other flags as necessary
}
break;
default:
std::cout << "Unsupported reg opcode in opcode 0x81: " << (int)reg_opcode << "\n";
error_flag = true;
running = false;
break;
}
}
Update the Instruction Set Mapping
Change the mapping for opcode 0x81 in your initialize_instruction_set method to use the new handler:
Since you've integrated the SUB operation into the new group handler, you can remove the old instr_SUB_r32_imm32 method or refactor it accordingly.
Explanation
The opcode 0x81 uses the reg field in the ModRM byte to determine which operation to perform on the destination operand. By creating a general handler that checks the reg field and performs the appropriate operation, you ensure that all instructions using opcode 0x81 are correctly executed.
Your revised instr_GROUP1_Ev_Iz function handles the immediate operations for 32-bit registers and updates the Zero Flag (ZF) as needed. It also provides a structure to extend support for other operations like ADC and SBB if you choose to implement them.
Testing the Fix
After making these changes, recompile your emulator and run the calculator.elf program again. It should now correctly process the add eax, 7 instruction, resulting in EAX being 12 before the division. This should produce the correct output:
Result: 12
Additional Recommendations
Implement Memory Operands: The handler currently outputs an error message if a memory operand is encountered. If your programs might use memory operands with opcode 0x81, consider implementing this functionality.
Handle Other Group Instructions: Similar group handlers exist for opcodes like 0x83 (with 8-bit immediate values). Implementing these will enhance your emulator's compatibility with more instructions.
Verbose Logging: To aid in future debugging, you might want to add logging statements that output the current opcode, EIP, and register values at each step. This can help you trace the execution flow and identify issues more quickly.
Exception Handling: Ensure that your emulator gracefully handles exceptions and provides informative error messages to aid in debugging.
Testing with Other Programs: Test your emulator with other assembly programs to ensure that your implementation works correctly across various instructions and scenarios.
Conclusion
By correctly handling the ADD instruction with an immediate value, you've addressed the root cause of the incorrect output. Emulating the full set of x86 instructions can be challenging due to the complexity and variability of opcodes, but systematic debugging and incremental implementation will lead to a robust emulator.