2

A minimal viable example of an assembly program that can be complied with gcc is the following:

.text
.globl main
main:
ret

We compile as follows in x86_64 mode:

$ gcc -o example example.s

In this example, we may include references to "main" or simple pointer arithmetic on "main" as .quad directives and the linker resolves them properly:

.text
.globl main
main:
ret

.quad main
.quad main + 12345

Gives the expected

0000000000001129 <main>:
    1129:   c3                      ret
    112a:   29 11                   sub    %edx,(%rcx)
[...]
    1132:   62 41                   (bad)

But how can we include bitwise expressions here? For example:

.quad main | 12345

Results in

Error: invalid operands (.text and *ABS* sections) for `|'

During runtime, this is easy to do, but is there a way to do this in gcc/gas at compile time?

  • 4
    What are you trying to achieve by doing this? Relocations only support references to symbols with a constant offset. You can't do arbitrary arithmetic. But depending on what you need, a workaround may exist. – fuz Jun 02 '23 at 11:51
  • I'm only particularly well versed in NASM, but it appears to be similar to gas in this regard. What I do when I want to shift or divide values derived from labels at build time is I do label arithmetic so that the assembler can operate on deltas. This is perhaps only really useful in a format like NASM's `-f bin` where you can reconstruct all section start/vstart/size parameters using deltas, eg `(data_label - data_start + text_end - text_start + 256 + 15) / 16` where just `(data_label + 15) / 16` would not be valid. – ecm Jun 02 '23 at 16:00
  • 2
    Generally you can't; the ELF object file format (`.o` files) doesn't have relocations that can ask the linker to do bitwise-OR. Nor do other common object-file formats like COFF or MachO. Near duplicate of [How to do computations with addresses at compile/linking time?](https://stackoverflow.com/q/31360888) / [Solution needed for building a static IDT and GDT at assemble/compile/link time](https://stackoverflow.com/q/58192042) - apparently linker scripts can get math ops done on addresses at link time, since they are link-time constants. (For non-PIE executables that can't ASLR) – Peter Cordes Jun 02 '23 at 20:14

0 Answers0