Allocate executable ram in c on linux

前端 未结 2 1764
南旧
南旧 2020-12-02 00:16

I want to make a simple just-in-time compiler with c on Linux.

How can I allocate memory such that I can write out raw x86 code to it and execute it as any other fun

相关标签:
2条回答
  • 2020-12-02 00:24

    See mprotect(). Once you have filled a (n-)page-sized memory region (allocated with mmap()) with code, change its permissions to disallow writes and allow execution.

    0 讨论(0)
  • 2020-12-02 00:34

    In addition to using mprotect correctly to provide first write and then execute permission, on some OS/hardware operations you may need to flush the I-cache. At this moment (mid-2010), all recent x86 processors have separate level 1 caches for instructions and data, and somebody has to make sure that if you write new instructions into memory (which will update the D-cache), you don't then try to execute stale bits from the I-cache. Exactly how to flush the I-cache from userspace will depend on both your hardware and the OS. My advice would be to read Intel's documentation on "self-modifying code" for their IA-32 multiprocessors. This should be enough to get you through.

    0 讨论(0)
提交回复
热议问题