Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use label in assembly from C

Tags:

c

gcc

assembly

nasm

I simply need a way to load the address of a label e.g. MyLabel: in e.g. 'src.asm' into a variable in e.g. 'src.c'. (These files will be linked together) I am using gcc and nasm to assemble these files. How can I load the label address?

like image 538
Kendall Frey Avatar asked Nov 08 '11 01:11

Kendall Frey


People also ask

Why label is used in assembly language?

In many high-level languages, the purpose of a label is to act as the destination of a GOTO statement. In assembly language, labels can be used anywhere an address can (for example, as the operand of a JMP or MOV instruction).

What is data label in assembly language?

A data label identifies the location of a variable, providing a convenient way to reference the variable in code. The following, for example, defines a variable named count: count DWORD 100. The assembler assigns a numeric address to each label.

What is difference between the function and label in assembly language?

Labels are often used for branch targets. Functions are 'exported' in the object file, and resolved by the linker - so it can be called from another object.


1 Answers

There are two steps to this. First, you must export the label as global from the assembly file using the global directive.

global MyLabel

MyLabel: dd 1234    ; data or code, in whatever section.  It doesn't matter.

Next, you must declare the label as external in C. You can do this either in the code using it, or in a header.

// It doesn't matter, and can be plain void,
// but prefer giving it a C type that matches what you put there with asm
extern void MyLabel(void);            // The label is code, even if not actually a function
extern const uint32_t MyLabel[];      // The label is data
// *not*  extern long *MyLabel, unless the memory at MyLabel *holds* a pointer.

Finally, you get the address of the label in C the same way you get the address of any variable.

doSomethingWith( &MyLabel );

Note that some compilers add an underscore to the beginning of C variable and function names. For example, GCC does this on Mac OS X, but not Linux. I don't know about other platforms/compilers. To be on the safe side, you can add an asm statement to the variable declaration to tell GCC what the assembly name for the variable is.

extern uint8_t MyLabel asm("MyLabel");
like image 64
ughoavgfhw Avatar answered Sep 22 '22 23:09

ughoavgfhw