RGroppa
RGroppa

Reputation: 325

How can I use GCC to prefix assembly code onto programs?

Suppose I write some c code, and it generates some assembly that looks like this:


.text 

main:
    mvs $r3, $sp
    addi  $r3, $r3, -16
    mvs $sp, $r3
    mvs $r3, $sp
    addi  $r3, $r3, 3
    shri $r3, $r3, 2
    shai $r3, $r3, 2
    call __main
    sti 8($r3), 25
    sti 4($r3), 23
    sti ($r3), 43
L2: ld  $r4, 8($r3)
    ld  $r5, 4($r3)
    add  $r4, $r4, $r5
    st 8($r3), $r4
    ld  $r4, 8($r3)
    ld  $r5, 4($r3)
    sub  $r4, $r4, $r5
    st ($r3), $r4
    jmp L2

How can I inject more assembly code, right in between main: and the first line? The goal is to set all the registers to 0, before running any assembly code that was generated via gas from c code. This is done to default the values of the register, which is required by the particular processor I'm working with.

I've thought about using the gcc linker and a custom object file to assemble the project with my custom code in front, but I don't know if I have that sort of capability with the linker.

I've considered using crtbegin.asm, but I think that's actually meant for supporting C++ constructors/deconstructors. So that won't help me at all.

Any ideas?

Upvotes: 0

Views: 579

Answers (2)

RGroppa
RGroppa

Reputation: 325

I figure out exactly how to do this:

http://www.dis.com/gnu/gccint/Function-Entry.html

TARGET_ASM_FUNCTION_PROLOGUE will stick any code you want right there inside main, before any other code is emitted. I'm leaving this answer here so anyone else who searches for this question can have an answer. :)

Upvotes: 2

kcbanner
kcbanner

Reputation: 4078

You can use inline assembly, asm(" ... "), right after your main() definition. However, this may actually show up after GCC sets up the stack pointer.

Another option would be passing an assembly file to your linker. Make sure you pass it as the first object when linking.

Put something like this in it:

// Clear registers
move 0, $r0
move 0, $r1

// Jump to main
jsr main

Upvotes: 0

Related Questions