1

I have this simple c:

#include <stdio.h>
#include <stdlib.h>
void f1(int x, int y, int *sum, int *product){
    *sum=x+y;
    *product = x*y;
}
extern int sum, product;
void main(){
    f1(123,456,&sum,&product);
    printf("sum%i; product=%i\n",sum,product);

As can be seen, the two variables sum and product are extern, so they are accessed via RIP-relative addressing (accessing int GOF table). But I do not have any other object file with definition of those objects/variables, so I would get sigFault anyway. Unless I would make those var not extern/global-linked but local to this object file. So I have compiled it, and add a 2 symbols and definition of those variables (product and sum):

.file   "a.c"
    .text
    .globl  f1
    .type   f1, @function
product: .long 1 #THIS LINE ADDED
sum: .long 2 #THIS LINE ADDED
f1:
    pushq   %rbp
    movq    %rsp, %rbp
    movl    %edi, -4(%rbp)
    movl    %esi, -8(%rbp)
    movq    %rdx, -16(%rbp)
    movq    %rcx, -24(%rbp)
    movl    -4(%rbp), %edx
    movl    -8(%rbp), %eax
    addl    %eax, %edx
    movq    -16(%rbp), %rax
    movl    %edx, (%rax)
    movl    -4(%rbp), %eax
    imull   -8(%rbp), %eax
    movl    %eax, %edx
    movq    -24(%rbp), %rax
    movl    %edx, (%rax)
    nop
    popq    %rbp
    ret
    .size   f1, .-f1
    .section    .rodata
.LC0:
    .string "sum%i; product=%i\n"
    .text
    .globl  main
    .type   main, @function
main:
    pushq   %rbp
    movq    %rsp, %rbp
    leaq    product(%rip), %rcx
    leaq    sum(%rip), %rdx
    movl    $456, %esi
    movl    $123, %edi
    call    f1
    movl    product(%rip), %edx
    movl    sum(%rip), %eax
    movl    %eax, %esi
    leaq    .LC0(%rip), %rdi
    movl    $0, %eax
    call    printf@PLT
    nop
    popq    %rbp
    ret
    .size   main, .-main
    .ident  "GCC: (Debian 8.3.0-6) 8.3.0"
    .section    .note.GNU-stack,"",@progbits

There are only those 2 lines added to provide definition, so instructions like leaq product(%rip), %rcx could find it (from the symbol definition). But still getting segfaul. So what else Do I need to do to make those symbol visible for rip-relative addressing?

autistic456
  • 183
  • 1
  • 10
  • 3
    The `.text` section is read only; if you use a debugger you should see that it only faults when trying to store to those addresses. Put them in the `.data` section, just like the compiler would do for `int product=1, sum=1;` in C. Look at compiler output to see how to do that. – Peter Cordes Jun 15 '20 at 13:08
  • 1
    For example, [In which data segment is the C string stored?](https://stackoverflow.com/q/37902489) shows compiler output for some non-const data. (And for const data, the string literal pointed-to by a pointer.) – Peter Cordes Jun 15 '20 at 13:17

0 Answers0