Implementing a flow “(1) if {…} else if {…} … (2)” in Assembly

五迷三道 提交于 2021-02-17 05:57:57

问题


I have the following flow in C:

// some stuff1
//................


if (something1) {
    func1();
    func2();
} else if (something2) {
    func3();
    func4();
}

// some stuff2

I wonder, how can I encode that in Assembly? I mean, not exact intructions, but the flow. Should I use labels for jumping to what's inside if (something1) { ...} and "else if (something2)"? How would I return then to "// some stuff2"?

  ; some stuff1
  ; and then 

  cmp [some_struc], SOME_CONST
  je .... ????

  cmp [some_struc], SOME_CONST2
  je .... ????


  ; some stuff2
  ; how to better get back here?
  cmp rax, 0 

Or should I call them as functions? Then how would I skip the 2nd "else if (something2) {" if the 1st one is true?

I can implement somehow, but I want to know how to better do that.


回答1:


I would say that it largely depends on how much code you have in these {...} blocks.
If there's limited code in them use:

    cmp  [some_struc], SOME_CONST
    jne  Else
    {...}
    jmp  EndIf
Else:
    cmp  [some_struc], SOME_CONST2
    jne  EndIf
    {...}
EndIf:
    cmp  rax, 0

If there's more code:

    cmp  [some_struc], SOME_CONST
    jne  Else
    call Part1
    jmp  EndIf
Else:
    cmp  [some_struc], SOME_CONST2
    jne  EndIf
    call Part2
EndIf:
    cmp  rax, 0

Part1:
    {...}
    ret
Part2:
    {...}
    ret

Best use call. I would not advice to jump to Part1 or Part2 and then jump back to EndIf.
This creates spaghetti code. Less readable and quickly becomes less maintainable.




回答2:


As i see it you have two options:

  1. Use functions like you said. then all you need to do is call func. the advantage is readability and more slick code as well as automatic jump back to where you called the function, but it will cost you the overhead of using a function (setting up the registers and pushing and popping the stack pointer).
  2. Use labels. this is straightforward. But you will need to declare a label for getting back to the function, or save the return address somewhere, which affects readability.

Anyway your conditional piece of code :

cmp [some_struc], SOME_CONST2 

seems OK.



来源:https://stackoverflow.com/questions/42188685/implementing-a-flow-1-if-else-if-2-in-assembly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!