Visual-C++ inline assembler difference of two offsets

蹲街弑〆低调 提交于 2019-12-08 04:08:02

问题


I'm porting chunk of code from MASM to C inline assembler (x86, Windows, MS VC) Foolowing is not a real code, just spoof to give an idea. Let's say I have some data defined as static array or even a code chunk between two labels, and I need to get size of it.

    label1:
    bla bla bla
    label2:
    ....
    mov eax, (offset label2 - offset label1)

Such a code works in MASM like a charm, but in C I get following error message: "error C2425: '-' : non-constant expression in 'second operand'" I can get compiled:

    mov eax, offset label1
    mov eax, offset label2

I expect compiler to evaluate (offset label1 - offset label2) at compile time, but it looks like I'm wrong. I can't add offsets as well (why? these are just two integers added during compilation...?) Sure, I can get mov eax, offset label2 mov edx, offset label1 sub eax, edx compiled, but that's an extra code just for calculating a constant. Can someone explain me please, what is wrong in my code?

Can it be something caused by relocation? How to push it through?

Looking forward to an answer, thank you.


回答1:


Yes, it can be caused by the threat of relocation but also threat of variable length instructions dealing with relative jumps. Most likely because of some minor trouble, the assembler writers took the easy way out and implemented a 1 pass or a two pass compiler that makes final decisions as soon as possible. And thus some convenient expressions are unsupported.

As already suggested in the comment, the assembler still probably supports mov + sub combination.




回答2:


The real assembler is probably running over the code in several passes before it has gotten fixed addresses for all the labels. For example, some jumps have a short and a long form depending on how far you want to jump. If you have such a jump between the labels, the distance depends on where the jump is going to.

The C compiler might leave some of that to the linker/loader and not have the values fixed at compile time.

You could very well get the addres calculation code down to two instructions

mov EAX, offset Label2
sub EAX, offset Label1

I don't think this will exactly ruin the performance of the code.



来源:https://stackoverflow.com/questions/13420744/visual-c-inline-assembler-difference-of-two-offsets

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