CSC231 Things to Remember when Writing Assembly Programs
--D. Thiebaut 08:48, 26 September 2012 (EDT)
Contents
DT's Golden Rules
Know how to deal with Segmentation Faults
- Segmentation faults indicate that your program is trying to reach data outside the program's footprint in memory. Possible reasons are:
- You are storing a constant in a register and using it as an index in memory
- A register you are using as an index contains a constant and not an address
Document, document, document!
- If a program does not work as expected, state as much in the header
- Align your comments
- Do not say what the instruction does, explain how it makes the algorithm progress
- Show a typical output in the top header of the program
Be lazy: Make Nasm do the work!
- When changing the case of a letter: add al, 32 should be replaced by add al, 'a'-'A'
- If you have an array, make Nasm compute its length
array dd 0, 0, 0, 0
arrayLen equ ($-array)/4
- Don't try to remember by heart that the difference between uppercase and lowercase is 33... You could remember wrong and make a mistake!!! ;-) Instead make Nasm compute it!
add al, 'a'-'A'
Match the size of the data to the size of the operands
- Check the size of your array elements to the size directive you use when accessing the elements:
array db 0,1,2,3,4,5
...
mov dword[array+1], eax ; problem: you are writting 4 bytes
; in your array at once
Know how to deal with short jumps
- For example:
for: ...
...
...
loop for
mov x, y
If the code above results in an error message that your jump is too short to reach its target (loop cannot branch back to the label for), then use the method illustrated below:
for: ...
...
...
loop endLp
jmp loopDone
endlp: jmp for
loopDone:
mov x, y
Check that your listing prints correctly
- Sometimes the output of your program looks good, but contains extra characters that do not print, indicating that your program has a problem. The best is to capture the output of your program in a text file and look at the file with less:
hw4a
Programmers
Are
Playwrights
- 'looks good... but let's capture the output to file...
hw4a > dummy
less dummy
^@^@^@Programmers
^@^@^@Are
^@^@^@Playwrights
- There's something wrong!
- You could have also tried the hexdump utility:
hexdump -c dummy
0000000 \0 \0 \0 P r o g r a m m e r s \n \0
0000010 \0 \0 A r e \n \0 \0 \0 P l a y w r i
0000020 g h t s \n
0000025
- A bunch of zeros are output with the text...
- You can also generate the pdf of the listing that will be generated for the grading
enscript -2rG -o yourfile.ps yourfile.asm ps2pdf yourfile.ps yourfile.pdf
- Now take a look at the pdf file generated. That is what your listing will look like on paper.