私のプログラムにデータを実行させるための最良のアプローチは何ですか。たとえば、 x86_64マシン用の(いわゆる)コンパイラを作成しました。
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cstdint>
struct compiler
{
void op() const { return; }
template< typename ...ARGS >
void op(std::uint8_t const _opcode, ARGS && ..._tail)
{
code_.push_back(_opcode);
return op(std::forward< ARGS >(_tail)...);
}
void clear() { code_.clear(); }
long double operator () () const
{
// ?
}
private :
std::vector< std::uint8_t > code_;
};
int main()
{
compiler compiler_; // long double (*)();
compiler_.op(0xD9, 0xEE); // FLDZ
compiler_.op(0xC3); // ret
std::cout << compiler_() << std::endl;
return EXIT_SUCCESS;
}
operator ()
しかし、正しく実装する方法がわかりません。のすべての内容code_
を連続したメモリチャンクに入れてから、これにキャストしlong double (*)();
て呼び出す必要があるのではないかと思います。しかし、いくつかの困難があります:
- Windowsで
VirtualProtect(Ex)
(+ )を使用する必要がありますか?FlushInstructionCache
Linuxでも似たようなものはありますか? - バイトを適切な方法で(つまり1つずつ)メモリに確実に配置するコンテナとは何ですか?また、メモリチャンクへのポインタを取得することもできます。