I wonder if there is a way to load a C function with its data at runtime to the text segment of a running microcontroller system. After the function is placed in the text segment and the data is stored in data segment the function pointer to the new loaded function becomes invoked in the main application. The functionality would be similar to a boot loader except from loading a entire binary before start up. I know that you can use the scatter-loading functions of the linker to place the function pointer at a fixed address or alter the alignment in the sections. Does anyone know if this is possible and if not why?
Many thanks
Technically it is possible. Keep in mind that any solution will be non-standard, not portable, and very tricky.
Many controllers may execute code only from a read-only memory, which makes the whole concept of dynamic loading problematic:
you'd need to erase a whole page first, making sure that no other parts of the application accesses this page during load;
you'd need to flush the instruction cache (again, many controllers rely on instruction cache being always valid).
In any case you'd need to ensure that the function being replaced has no stack frame associated with it. Very hard to enforce in a multithreaded system.
Any particular architecture may offer more traps.