3

Following up on this question, is it possible for llvm to generate code that may jump to an arbitrary address within a function in the same address space? i.e.

      void func1() {
       ...
       <code that jumps to addr2>
       ...
       }

       void func2() {
       ...
addr2:
       <some code in func2()>
       ...
       }
Community
  • 1
  • 1
Sebi
  • 4,262
  • 13
  • 60
  • 116
  • 1
    This is considered bad practice, because it may cause "spaghetti code" (http://en.wikipedia.org/wiki/Spaghetti_code). Write instead a new function func3, that you invoke from func1 and func2 – Brainless Apr 01 '15 at 09:19
  • 2
    @Brainless: "Spaghetti code" is a risk to maintainability. Since generated code doesn't need to be maintained (instead, you maintain the source from which it was generated), it doesn't matter how spaghettified it is. – MSalters Apr 01 '15 at 10:07
  • @MSalters The question is more about the possibility of emitting such code, not actually writing it. – Sebi Apr 01 '15 at 10:31

1 Answers1

3

Yes,No,Yes,No,(yes) - It depends on the level you look at and what you mean with possible:

  • Yes, as the llvm backend will produce target specific assembler instructions and those assembler instructions allow to set the program counter to an abitrary value.
  • No, because - as far as I know - the llvm ir (the intermediate representation into which a frontend like clang compiles your c code) hasn't any instructions that would allow abitrary jumps between (llvm-ir) functions.
  • Yes, because the frontend COULD certainly produce code, that simulates that behaviour (breaking up func2 into multiple separate functions).
  • No, because C and C++ don't allow such jumps to ARBITRARY positions and so clang will not compile any program that tries to do that (e.g. via goto)
  • (yes) the c longjmp macro jumps back to a place in the control flow that you have already visited (where you called setjmp) but also restores (most) of the system state. EDIT: However, this is UB if func2 isn't somewhere up in the current callstack from where you jump.
MikeMB
  • 20,029
  • 9
  • 57
  • 102