To write a complete source program, first define an array of variables, the length of which is the length of the program code segment, and copy the code segment into the array
Use the label to get the length of the code
In the loop instruction of assembly language, the loop instruction determines whether to execute the loop statement according to the value of the cx register. The loop is followed by a label, such as s, which represents the address of an instruction in memory. In fact, the compiler will also translate the s label into a memory address at the end.
Since the label is a memory address, we can define two labels and use the difference between the two labels to calculate the number of bytes of instructions between them. So in this program, the instruction at the beginning is set to the label "start", the last instruction is set to the label "stop", and the number of bytes of the instruction to be copied is "stop-start".
Portal
(1) preliminary code:
(2) Data in the array before running
(3) Binary value of assembly code
(4) Observe the writing situation after the operation is over
1. By comparison, it is found that the program code segment is completely written.
2. But it is found that data is written under the space I applied for in advance, why?
Debugging: It is
found that the data area below will be filled in when the program starts to initialize.
But after the program copies all the binary values of the code into the array, it should exit, but it still writes to the memory.
Because I don’t know how big my program is, the size of the array is guessed blindly, but I drag it into the OD and find that it has been calculated for me. At this time, I return to the assembly environment and change the size of the array to the OD calculation. Value.
It is found that the following value will still be modified during the execution of the program. It turns out that the program copies 4 bytes each time, but it loops 28 times. At the same time, I found a total of 27 bytes of data in the code area, so I copied a lot more. In order to ensure accurate copying, I copy one byte at a time for 27 times and modify the code.
The modified code is perfect: and because of the +1 operation, the code becomes shorter.
(1) Final code
(2) Data in the array before writing
(3) Hexadecimal code
(4) Array after writing
Found that there is no more copy, perfect! Although it's a bit slow. In fact, you can copy multiple bytes at a time, and then you need to judge in the end, and copy the rest, but I don't write that because I'm lazy.
.386
.model flat,stdcall
option casemap:none
include kernel32.inc
includelib kernel32.lib
include Stdlib.Inc
includelib Stdlib.lib
.data
myself db 23 dup(2)
.code
.startup CONSOLE
star: mov ecx , offset stop - offset star
mov eax , offset myself
mov ebx , offset star
s: mov dl , [ebx]
mov [eax] , dl
inc ebx
inc eax
loop s
stop:
.exit
end