简体   繁体   中英

Visual-C++ inline assembler difference of two offsets

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 CI 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM