2

I'm trying to understand why should I dereference functions while making a self-modifying code in C.

Even though it works this way, I would like to know why!

Here's an example of what I was dealing with: http://nmav.gnutls.org/2011/12/self-modifying-code-using-gcc.html

I asked the guy from the blog but he never answered :(

  • 3
    Provide a specific example of code you are working on, with a specific question about what you are trying to do, and where your results are not what you expect and you will get a much better response. – ryyker Nov 08 '13 at 21:04
  • 1
    Self-modifying code is evil. Just say no. – mah Nov 08 '13 at 21:07
  • Yes, evil, but bad boys and girls have all the fun... – hyde Nov 08 '13 at 21:23
  • Interesting, the only thing that comes to my mind is to avoid function inlining by the compiler. But that's just a guess. My other thought is that this is just an example and it's not necessary to dereference functions. Have you tried running the code with regular function calls? – ciamej Nov 08 '13 at 21:14
  • Inlining prevention seems obvious necessity. – hyde Nov 08 '13 at 21:29
  • I wonder if it depends on the optimization level... with -O0 it wight work. Using -O0 with self modifying code seems reasonable anyway. – ciamej Nov 08 '13 at 21:35
  • Well, there are command line switches to stop just inlining, without disabling other optimizations, but I think you'd generally want normal functions to be inlineable. – hyde Nov 08 '13 at 21:54
  • I tried with the regular function but it doesn't work properly. It printed garbage. Anyway it usually produces a segmentation fault in larger programs – federicoferriff Nov 09 '13 at 02:13
  • I found the answer! In x86, there are indirect, absolute and relative calls to the next instruction pointer. if you write printf(sth); then it is solved as a relative call. This means that the opcode generated by gcc has incrusted the direction where to call. But when the code changes its place in memory, the opcode doesn't update, so the next instruction pointer points anywhere because the direction already changed. However, the call is made by the pointer to function, as it is indirect, it doesn't matter if the code has moved or not. – federicoferriff Apr 16 '14 at 00:39

0 Answers0