Почему эмуляция процессора медленная

1090
user2543574

Различные операции ЦП (IA-32, ARM9 и т. Д.) Должны быть эквивалентны по своей природе (перемещение, чтение, запись данных и т. Д.). Разным процессорам не должно быть так больно подражать друг другу. Но кажется, что это не так просто, поскольку эмулированное программное обеспечение работает слишком медленно. Можем ли мы просто преобразовать исполняемый файл, а затем выполнить его? В любом случае, почему он так зависит от ресурсов (зачем мне нужен мощный процессор для эмуляции других процессоров)? Должен сказать, что у меня нет больших навыков программирования низкого уровня. Большое спасибо.

3

2 ответа на вопрос

5
LawrenceC

Different CPU (IA-32, ARM9 etc.) operations should be equivalent in their nature (move, read, write data etc.).

They should be but they are not. A CPU architecture implements these basic operation according to how its designers envisioned - and this can be very different depending on what the designers are trying to accomplish. Things that may be done in one instruction on some CPUs may require many, many instructions on others.

Could we simply convert an executable file, then execute it? Why it's so resource dependent anyway (why do I need a powerful CPU to emulate other CPU)?

If all you want to do is emulate the CPU, then this can be done and done relatively easily. "Converting" an executable file on the fly is called "dyamic recompliation" and many emulators do that already. Typically though, one wants to emulate an entire platform. This includes hardware other than the CPU, and sometimes that hardware is difficult to emulate (the Atari 2600 TIA, for example) or poorly documented (the NES PPU video hardware or even current GPU hardware) or both. CPUs always function in the context of a platform and usually software expects the CPU + platform together to work in a certain way. The requirements for emulating a platform, and doing so with the strict timing requirements often required, is what's the hard and resource intensive part.

Да. Если бы не эта крошечная деталь периферии вокруг ЦП, например, все эти усилия по реинжинирингу IBM ROM BIOS не были бы необходимы; просто поставьте готовый 8086 на материнскую плату, и у вас будет готов клон IBM PC, который появится на полках. Очевидно, на практике это было не так просто. То же самое применимо и здесь, хотя в большем масштабе, чем микросхема ПЗУ объемом 8 КиБ с опубликованным, аннотированным и прокомментированным исходным кодом. a CVn 10 лет назад 0
@ MichaelKjörling, почему мы не можем думать в категории черного ящика, так как у нас есть некоторые входные данные и задача, которую нужно выполнить? входные данные должны быть достаточно легкими для преобразования. почему нет? user2543574 10 лет назад 0
@ user2543574 Потому что именно так, как указывает ультрасоволок, действительно полезная эмуляция платформы намного больше, чем простая передача двоичных кодов операций ЦП с одного ЦП на другой. Написание полезного (хотя, может быть, и не очень полезного) базового эмулятора Altair 8800 довольно легко, поскольку он на самом деле был немногим больше, чем процессор 8080, набор физических операций ввода-вывода (индикаторы и переключатели), кусок оперативной памяти и Шина S-100, соединяющая периферию с процессором. Написание полезного эмулятора NES - это * совершенно * другое дело, хотя процессор 6502 находится на том же уровне, что и 8080. a CVn 10 лет назад 0
4
user55325

First, although there certainly are instructions that are very similar, it's not the case that there is some set of instructions that always behaves the same way on different CPU architectures. For accurate emulation it's (usually) not enough to translate each instruction - you have to handle memory accesses, timing, interrupts... and that's just for the CPU.

It seems that what you're thinking of is static recompilation, but it's very difficult to do (in fact, I think it boils down to the halting problem, making it actually impossible in theory). In practice we can sometimes do it for a subset of programs, but you can't write a general purpose compiler that takes object code for one architecture as input and outputs perfectly equivalent code for another. For example, it would be hard to handle self-modifying code using this method.

Dynamic recompilation (which generates code on-the-fly as the program executes) is more successful (still non-trivial to do right). The specific issues will depend on the architecture, though. In many cases emulating the CPU is not the problem, but emulating various peripheral devices, maintaining accurate timing, is (see e.g. byuu's article on emulating the SNES).

Sometimes you can ignore a lot of these constraints and still emulate hardware well enough to get a subset of the software working, but it's never possible (as far as I know) to have 100% accuracy with zero overhead unless you have the actual hardware.

Чем статическая перекомпиляция отличается от динамической, поскольку код все равно будет перекомпилирован (преобразован)? user2543574 10 лет назад 0
Разница в том, что динамическая перекомпиляция происходит во время выполнения кода, поэтому можно узнать состояние системы в любой момент времени. Это позволяет переводить код по-разному в зависимости от текущих условий, что невозможно при статическом перекомпиляторе. user55325 10 лет назад 0

Похожие вопросы