6

Linux Assembly Tutorial states:

there is one very important thing to remember: If you are planning to return from a procedure (with the RET instruction), don't jump to it! As in "never!" Doing that will cause a segmentation fault on Linux (which is OK – all your program does is terminate), but in DOS it may blow up in your face with various degrees of terribleness.

But I cannot understand why does it causes a segmentation fault. it sounds just like returning from a function.

I have a situation where I need to implement the logic "If X happens, call procedure A. Otherwise, call procedure B." Is there any other way than jumping around like a kangaroo weaving spaghetti code?

InvalidBrainException
  • 2,312
  • 8
  • 32
  • 41
  • 1
    Just a note: there's nothing specifically preventing you from doing this, but what it does is not always obvious to new assembly programmers. The most common case of this is called a "tail call", and it's common in functional languages. The effect is to return to the caller of the function containing the jump (bypassing the rest of that function), *if* you've cleaned up your little part of the stack. If you haven't, that's when you see segfaults. – cHao Mar 23 '12 at 23:31
  • 2
    Make sure you understand the difference of `jmp` and `call`. – Gunther Piez Mar 24 '12 at 10:23

2 Answers2

10

Because CALL pushes the current instruction address onto the stack, and RET pulls it off in order to get back to the call-site. JMP (and related instructions) don't push anything onto the stack.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
-1

I think that this advice may have to do with the pipeline, but I'm not sure.

I believe that the question you are asking is:

... subroutine entrypoint ...
... various instructions in a routine ...
jmp label
... move instructions in a routine...
label:
ret

What's the problem, if any, with this? First, I'm not sure that this is a problem at all. But if it is, it's the pipeline. On some processors, one or more instructions after the jmp will be executed before control moves to the label.

Mostly, I fear that you've misunderstood what you've read, or I've misunderstood what you've written. jmp-ing from one point in your subroutine to the ret instruction should be fine. jmp-ing instead of executing ret is, as other people pointed out, is a dumb idea.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
  • 2
    I think the question refers to why you can't use a naive `jmp` to call a function, instead of using the `call` instruction. Of course you can, if you set up the stack yourself, but otherwise this is doomed to failure because `ret` will return to nowhere. – Niklas B. Mar 23 '12 at 23:35
  • 1
    I think the OP's quote means "don't jump to a subroutine, always call it", rather than "don't jump to the ret instruction". – Oliver Charlesworth Mar 23 '12 at 23:36