Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

assembly - Why is no value returned if a function does not explicity use 'ret'

I have the following program:

SECTION .text
main:
     mov ebx, 10
     mov ecx, 50

repeat:
     inc ebx
     loop repeat

     mov eax, ebx
     ret

When this program runs, it returns 60 as expected. However, if you drop the final ret statement, the program runs fine, but then returns 0. Why is that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you leave off the "ret", the computer executes the last "move eax, ebx" and then executes whatever happens to be next in computer memory.

I'm surprised you don't get an illegal instruction/access; that would be the most common response. Somehow the garbage instruction acts like a return, after trashing the registers.

Its also a little unclear what you mean by "returns 60". You mean as a value to the command prompt? It is clear that your program has no defense against illegal instruction traps. What Windows does when you get such a trap without a defense is unclear to me; I know from experience when I do that Windows tends to just terminate my process and I get some random exit status. "0" might be such a status.

Try adding:

      mov   byte ptr[eax], 0

before the "ret" instruction; this will cause an illegal memory reference. You report what status you get. It wouldn't suprise me if you got the zero status result in this case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...