First I want to ask whether is it possible for an application to update itself at runtime on same address space? If yes, what's the best way to implement the logic? Usecase : My application is running on a board which is connected to network. At runtime if it detects a new version of same application, then how to update the application on same memory address, where previous one is stored. As per my understanding first we should take the backup of update and at the time of boot load, main application should be updated with backup and then launch the application normally. Am I right?
-
1could you better explain? perhaps with an example usecase – Arjun Sreedharan Jun 11 '15 at 07:30
2 Answers
Usually you can replace the file containing the executable while it's running without problems.
After you update the file, you can start the application like always, and close your running instance.
If you however want to do it at runtime (i.e. without forking or starting new process), I don't think it's possible without extremely weird hacks:
- if you plan to "rebase" your program memory with new executable's code, you'd need to figure the stack, memory and instruction pointers for each thread. You'd need to become a disassembler.
- if you plan to call a stub in your program after loading it into auxilliary memory segment, that's fine, but you need to figure where the target function is, and what happens if it's gone in your next update. Plus it's totally platform-specific.
- if you plan to standardize the above approach by using shared libraries that are dynamically loaded and unloaded, I see no problem - it's very similar to the approach where you restart entire process.
I'd go with replacing just the executable, or the third option if I have a very good reason for this. The last option is nice since it lets you update your application's components separately (but at the same time this might cause you maintenance headaches later on.)

- 14,303
- 6
- 45
- 67
What you need is something akin to a bootloader. In this case: you will have two programs on the device, hereafter referred to as the Loader and the App.
On your initial install of the system: write the App to the beginning of memory and the Loader somewhere further down to give space if the App grows in size in the future. (Keep note of the beginning memory address of the Loader)
The App will run normally as if it was the only program, periodically checking for updates to itself. If it finds an update on the network, use a GOTO to go to the first memory location of your Loader, which will then begin running and can write over the original App with the new App found on the network. At the end of your Loader, GOTO back to the (new) App.
See this Stack Overflow question for ideas on how to GOTO to specific memory addresses. Goto a specific Address in C