Search code examples
gooverwriteself

How to make program to overwrite itself during execution in go


I tried to write a program that open itself, reads itself and looks for a certain address or bytes to substitute with an other value.

My objective is to make a program that understands if it's the first time that it's running or not by modifying some bytes the first time it runs (and I don't really like to create a file outside of my program)

The executable can read itself but when it tryes to self-overwrite it throws an error (file used by an other process... As expected)

Is there a way for the program to overwrite itself? If not maybe I can modify just a part of the program that contains just data? Is there an other simple solution I am not aware of?

(I'm using both Linux and windows as OS.)


Solution

  • A workaround can be (because it doesn't overwrite itself, it just creates an other file):

    1. copy all content of the original executable
    2. modify what I need
    3. rename di original executable to a fixed name "old version"
    4. write the modified bytes to "original name" (the modified executable)
    5. launch the new executable just created
    6. either have the original executable self delete or delete it from the modified executable just created

    I think this gets the job done even if not on the cleanest way (the program has to start from beginning but i guess this is unavoidable)...

    If someone still know a better way you are more the welcome to write your idea.