1

Consider the following short program.

int main(){                      
    asm("movq 0x5F5E100, %rcx;"  
            "startofloop: ; "    
            "sub 0x1, %rcx; "    
            "jne startofloop; ");
}                                

This program compiles fine, but when it is run, it segfaults on the initial movq instruction.

I must be missing something obvious, but I hope someone here can point it out for me.

I am running on Debian 8, with kernel 3.16.0-4-amd64, in case that is relevant.


For future reference, this is what the compiler generated.

main:                                                                  
.LFB0:                                                                 
    .cfi_startproc                                                     
    pushq   %rbp                                                       
    .cfi_def_cfa_offset 16                                             
    .cfi_offset 6, -16                                                 
    movq    %rsp, %rbp                                                 
    .cfi_def_cfa_register 6                                            
#APP                                                                   
# 2 "asm_fail.c" 1                                                     
    movq 0x5F5E100, %rcx;startofloop: ; sub 0x1, %rcx; jne startofloop;
# 0 "" 2                                                               
#NO_APP                                                                
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • I don't know almost anything about assembly. But maybe you wanted to copy the value 0x5F5E100 into %rcx and swapped the operands without realizing it? – andre Jun 21 '16 at 22:28
  • Please add the compiler-generated assembly code (compile with `-S`) to your question. – user3386109 Jun 21 '16 at 22:33

1 Answers1

4

It turns out that it has been too long since I have written asm, and I had forgotten that one must preface immediate values with $ in AT&T syntax. I found the reminder here when double-checking AT&T syntax.

asm("movq $100000000, %rcx;"
        "startofloop: ; "
        "sub $0x1, %rcx; "
        "jne startofloop; ");

movq 0x5F5E100, %rcx (without a $ on the number) is a load from the absolute address 0x5F5E100

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • Disassembling in Intel syntax would have clued you in that you were using `mov r64, r/m64` instead of `mov r64, imm32`, if you know that square brackets specify a memory operand. (e.g. `objdump -Mintel -drw foo.o`) – Peter Cordes Jun 22 '16 at 14:09