1

Is it generated by some kind of algorithm or mathematical procedure that tests whether or not the code produces the desired results and there are no runtime/stack errors? Or is there some other kind of heuristic process to decide what changes are to be made.

Mr X
  • 336
  • 1
  • 6
  • 22
  • No; it's just written to produce _valid_ code; in the same way that your programs are (presumably) written to produce valid output. – SLaks May 22 '13 at 19:25
  • Well you could have another program that monitors the program that's running and then modifies it when it produces an invalid output. Modifying code by human involves examining it and quite often trying different things until you produce the desired result. But how does it know WHAT to try and how to recognize what each line of code does? I do wonder if error-correcting techniques are used. – Mr X May 22 '13 at 19:32

1 Answers1

1

Just to be accurate - any type of write into executable code is basically self-modifying-code, even if it doesn't produce anything useful :)

But i'm assuming you mean the useful use-cases such as JIT or binary-translators (we'll leave the manual ones as they're almost only useful as exam questions). Consider the work of a compiler - at some point it handles a flow of code (usually in intermediate representation, a kind of pseudo assembly with additional info). It then analyzes it and builds data-flow and control-flow graphs, and runs various algorithms to optimize them. Now consider that instead of performing this statically at compile-time, you have some driver or runtime kernel that does this on the fly (with the benefit of additional runtime data, such as sampling of branch history). This agent could then modify the code (or usually just produce a new and improved one), and switch the program to run that instead. It could further go back there and improve it on future passes. The code correctness is guaranteed just as a normal compiler would guarantee it. There an additional risk of confusing old and new code (what if a third party changes the old code while you run your optimized version? what if a TLB page is cleared? etc..). There are also some optimizations that are not fully guaranteed, and could be protected by adding assertions in the generated code (and an abort+unwind flow).

Leeor
  • 19,260
  • 5
  • 56
  • 87