-   Programming (
-   -   I have a partially theoretical question. (

abcde597 11-05-2012 02:42 PM

I have a partially theoretical question.
Would it be possible to write a program that writes/changes its own source code?
I mean, virus writers can do it, can't we?

hunternet93 11-05-2012 03:08 PM

Yup. If the program knows where it's own source files are, it can edit them and recompile.

abcde597 11-05-2012 03:48 PM

Can you help me find source code showing this?

sundialsvcs 11-05-2012 09:45 PM

Yes, you can compile a program if you have its source-code, but it's far more difficult to swap the image of a running process on-the-fly. Very often the executable file is locked to prevent such modification. Almost always, it's simply ignored if you try.

When a program is executing, its code-segment is almost always protected against modification, for a variety of reasons not just this one.

(And all of the foregoing comments are "not-at-all Linux-specific.")

NevemTeve 11-05-2012 10:14 PM

A famous problem: write a program that prints its source.

salasi 11-06-2012 03:52 AM

Donald Knuth, in the Art of Computer Programming (one of the early parts, if I remember correctly) considers the problem of self-modifying code and is prepared to do it and so has an example. Of course, this is in assembler for the hypothetical MIX machine, but you should be able to extrapolate from there.

hunternet93 11-06-2012 06:47 AM

I think the program would just compile itself, start the modified copy, pass the copy whatever data/parameters it needs, and exit. I'm not a C programmer, though, so I can't be sure.

abcde597 11-06-2012 04:13 PM

Thanks, all!

All times are GMT -5. The time now is 08:21 PM.