Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding assembly .long directive

Tags:

c

assembly

In Secure programming cookbook for C and C++ from John Viega I met the following statement

asm("value_stored:    \n"
    ".long 0xFFFFFFFF \n"
);

I do not really understand the use of .long directive in assembly, but here it is used to embed a precalculated value in the executable. Can I somehow force the position of these bytes in the executable? I have tried to put it at the end of main (thinking that this way will be at the end of .text section), but I got segmentation fault. Putting it outside the main works.

like image 258
robert Avatar asked May 27 '26 11:05

robert


1 Answers

Even at the end of main the inline assembler sequence will generate code to be executed. In my environment objdump -d foo.o shows:

00000000004004b4 <main>:
  4004b4:   55                      push   %rbp
  4004b5:   48 89 e5                mov    %rsp,%rbp

00000000004004b8 <value>:
  4004b8:   ff                      (bad)  
  4004b9:   ff                      (bad)  
  4004ba:   ff                      (bad)  
  4004bb:   ff                      (bad)  
  4004bc:   b8 01 00 00 00          mov    $0x1,%eax
  4004c1:   5d                      pop    %rbp
  4004c2:   c3                      retq   

This can be mitigated by jumping over it

asm("jmp 1f"
    "value: .long 0xffffffff"
    "1:");

Keywords Nf or Nb create local temporary labels to jump forward or backwards.

Another option will be to place the variable to a named segment, which can be sorted in the linker file as the last segment in either .text or .data.

like image 139
Aki Suihkonen Avatar answered May 30 '26 04:05

Aki Suihkonen