A program which reads itself using the LPM instruction.
In the days of Commodore 8 bit computers, I created a little assembler/disassembler program. So I was driven to know exactly what the instructions look like in memory, and exactly what gets stored in program memory when a program is uploaded to the microcontroller.
I suppose I’m thinking about trying to upload my own code my own way using my own assembler.
I’m using AVR Studio version 4.15 Build 623. You can use Atmel Studio, but my computer was too slow for the newer version, and this old version really flies, has debugging, shows ports and registers too.
The code is in the description. The secret sauce is the LPM instruction. Here it is in the datasheet Instruction Set Summary:
The data sheet shows what happens during this LPM instruction:
Which means the contents at address Z get put into a register. Then Address Z is incremented. Here is the description:
To use this, we must load register Z with address 0, the first location of our program on an Arduino chip.
To load register Z with an address, we can load its low byte and then its high byte. Remember memory addresses are 2 bytes long, which is of course needed because there are so many of them.
The clr instruction is possible because we are setting both values to zero, it’s possible to use LDI but this seems more succinct.
Now there are two things to do, and they are in the following links:
1. AVR Asembler: Reading From Program Memory Using AVR Studio Debugger and Assembler
2. AVR Assembler: Comparing The Contents of Program Memory with the Hex Output File, and the Documentation.