Disclaimer 2024-05-07
Although PIC was a very interesting trek in the deep embedded territory, I’m not that confident about the benefits as of today, 2024-05-07. See the comment below from “manne”. He discovered that even though some aspects of my solution works, it is basically unusable in the comprehensive scale. Therefore, for the time being, I am discouraging people from using PIC in real-world applications, and only exploring the subject for academic interest. I will write later more in-depth analysis of shortcomings and will also propose some compiler changes to tackle the main issue and also some some generic PIC optimizations.
Rest of the text is kept for posterity.
How to implement Position-Independent Code for microcontroller (MCUs) is a question which has been asked countless and countless of times all over the Internet. The answers and “solutions” are usually whippersnappering comments dropping a couple of key terms they probably just googled up without any kind of intrinsic knowledge about how the system should be working.
Sometimes the answer is “OK I got it working” followed by eternal silence from people asking clarifications. In other words, it looks like the task is very difficult and once people get it to work, it is so valuable they want to hide the details. In a way I cannot blame them much; it took me 6 months of half-time work every now and then to understand everything.
So, some 6 months ago I set myself a goal: “Create a portable solution where an intelligent bootloader can boot firmware images from any address in flash on Cortex-M0 or Cortex-M4 platform.” Finally, as of today 2022-01-16, I consider I have solved the problem in an intelligent and understandable way.
Funnily, I think I am the only person on planet Earth who has made available readily working example code and documented the code in a way I am doing now in this post.
Those impatient can explore the fully working STM32CubeIde codes at GitHub, for Cortex-M0: https://github.com/usvi/F070RB-BL-FW and for Cortex-M4: https://github.com/usvi/L432KC-BL-FW . (One might ask why one would use this kind of bloated stock configuration for developing on MCUs. Believe me, I’m doing it here only for pedagogical reasons. This way it is easier for noobs having the needed evaluation boards to verify that the code is working.)
The set of code I have created is a proof-of-concept, working for the C language. There might, and I underline, might be unforeseen problems when amount of global variable gets absurdly high. In any case, comments and criticism is more than welcome.
If you are ready to dive into the deep end of Cortex-M boot process, PIC constructs, esoteric debugging and linker script optimizations, continue reading…