Live data from Hacker News

Writing a Self-Mutating x86_64 C Program (2013)

ephemeral.cx

1–10 of 42 posts

Re: Writing a Self-Mutating x86_64 C Program (2013)

#3
post #2

I guess in OpenBSD because of W ^ X this would not work?

I was thinking the same thing. Usually, you'd want to write the new code to a page that you mark as read and write, then switch that page to read and execute. This becomes tricky if the code that's doing the modifying is in the same page as the code being modified.

Re: Writing a Self-Mutating x86_64 C Program (2013)

#4
post #2

I guess in OpenBSD because of W ^ X this would not work?

The way it's coded it wouldn't; however, you can map the same shared memory twice. Once with R|W and a second time with R|X. Then you can write into one region and execute out of it's mirrored mapping.

Re: Writing a Self-Mutating x86_64 C Program (2013)

#5
post #2

I guess in OpenBSD because of W ^ X this would not work?

In Linux it also needs mprotect() to change the permissions on the page so it can write it. The OpenBSD man page[0] indicate that it supports this as well, though notes that not all implementations are guaranteed to allow it, but my guess is it would generally work.

[0] https://man.openbsd.org/mprotect.2

Re: Writing a Self-Mutating x86_64 C Program (2013)

#6
post #2

I guess in OpenBSD because of W ^ X this would not work?

Not as is, but I think OpenBSD permits you to map the same memory twice, once as W and once as X (which would be a reasonable hoop to jump through for JITs etc., except there’s no portable way to do it). ARM64 MacOS doesn’t even permit that, and you need to use OS-specific incantations[1] that essentially prohibit two JITs coexisting in the same process.

[1] https://developer.apple.com/documentation/apple-silicon/port...

Re: Writing a Self-Mutating x86_64 C Program (2013)

#9
post #5
post #2

I guess in OpenBSD because of W ^ X this would not work?

In Linux it also needs mprotect() to change the permissions on the page so it can write it. The OpenBSD man page[0] indicate that it supports this as well, though notes that not all implementations are guaranteed to allow it, but my guess is it would generally work. [0] https://man.openbsd.org/mprotect.2

It's not required on linux, if the ELF headers are set up such that the page is mapped rwx to begin with. (but rwx mappings are generally frowned upon from a security perspective)

Re: Writing a Self-Mutating x86_64 C Program (2013)

#10
post #7

I often think this could maybe allow fantastic runtime optimisations. I realise this would be hardly debuggable but still..

I used GNU lightning library once for such optimisation. I think it was ICFPC 2006 task. I had to write an interpreter for virtual machine. Naive approach worked but was slow, so I decided to speed it up a bit using JIT. It wasn't a 100% JIT, I think I just implemented it for loops but it was enough to tremendously speed it up.
Post reply on HN