Writing Assembly Code to an Arduino with AVRDude
I’ve been doing some Arduino CTFs lately and wanted to learn a bit more about how things work at lower levels, so I decided it’d be best to try and program my Arduino in Assembly instead of C. I don’t currently have a device for on-chip debugging/programming, so decided I’d try and program it via the USB interface using Atmel Studio 7 & avrdude.exe.
To get started we need to install two things: Atmel Studio 7, and the Arduino IDE.
Creating an Assembly Project
In order to create an Assembly project we need to go to File > New Project > Assembler > AVR Assembler Project, then fill in a name of our choosing and hit ok (I’m using the name AssemblerApplication2).
Next we’ll be asked to pick the device (For my Arduino Uno, that is the Atmega328p).
Once all is done, we’ll have a new project with a template Assembly file which’ll look like this.
Setting up the Toolchain
To flash the Arduino with our code, we’ll be using avrdude.exe (which comes with the Arduino IDE). In order for this to work, we’ll need to find and specify a couple of variables:
<path_to_avrdude.exe> – the full path to avrdude.exe (in my case this is “C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avrdude.exe”)
<path_to_avrdude.conf> – the full path to avrdude.conf (in my case this is “C:\Program Files (x86)\Arduino\hardware\tools\avr\etc\avrdude.conf”)
<device_name> – the device we picked when we created the project (in my case this is atmega328p).
<device_port> – the port used to communicate with the Arduino. On Windows you can find this by plugging in the Arduino via USB then going to Device Manager > Ports (COM & LPT), and looking to see which COM port the Arduino shows up as (in my case this is COM4).
Using all these variables, we’ll build the following command:
<path_to_avrdude.exe> -C <path_to_avrdude.conf> -v -p <device_name> -c arduino -p <device_port> -U flash:w:”$(MSBuildProjectDirectory)\$(Configuration)\$(OutputFileName).hex”:i
Giving us something which looks like this:
“C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avrdude.exe” -C “C:\Program Files (x86)\Arduino\hardware\tools\avr\etc\avrdude.conf” -v -p atmega328p -c arduino -P COM4 -D -U flash:w:”$(MSBuildProjectDirectory)\$(Configuration)\$(OutputFileName).hex”:i
Now we can go into Project > Properties, select the “Tool” tab, set the “Selected debugger/programmer” dropdown to “Custom Programming Tool”, and paste our built command into the “Command” field.
Flashing
If everything went well, when we hit the green play button the Arduino will be flashed with our template ASM file. If you want to test the flashing command with an actual program, use the Arduino IDE to compile the blink sketch and replace “$(MSBuildProjectDirectory)\$(Configuration)\$(OutputFileName).hex” with the path to the sketch’s .hex file and run the command from cmd.exe.