I need to call some syscalls in my newlib stubs and the current implementation uses C macros which got unreadable and awful looking over time. (And I hate macros...) However, my implementation with C++ templates does only work for one parameter:
template <int nr, typename RETTYPE, typename PARAM1>
inline RETTYPE syscall(PARAM1 p1)
{
register PARAM1 r0 asm("r0") = p1;
asm volatile("svc %[nr]\n"
: "=r" (r0)
: [nr] "i" (nr), "r" (r0)
: "memory", "r1", "r2", "r3", "r12", "lr");
return (RETTYPE) r0;
}
Now I can call e.g. malloc using
void *ptr = syscall<SYS_MALLOC, void*>(0x1000);
to allocate 0x1000 bytes.
My implementation for four parameters:
template <int nr, typename RETTYPE, typename PARAM1, typename PARAM2, typename PARAM3, typename PARAM4>
inline RETTYPE syscall(PARAM1 p1, PARAM2 p2, PARAM3 p3, PARAM4 p4)
{
register PARAM1 r0 asm("r0") = p1;
register PARAM2 r1 asm("r1") = p2;
register PARAM3 r2 asm("r2") = p3;
register PARAM4 r3 asm("r3") = p4;
asm volatile("svc %[nr]\n"
: "=r" (r0)
: [nr] "i" (nr), "r" (r0), "r" (r1), "r" (r2), "r" (r3)
: "memory", "r12", "lr");
return (RETTYPE) r0;
}
doesn't work, the content of the registers at the "swi" instruction is arbitrary. Somehow GCC doesn't respect the "register" variables anymore. Example: I set a breakpoint at the svc instruction and execute
syscall<FWRITE, int>(ptr, 1, len, f)
But somehow r0 is set to 1 and r1 to ptr... I also tried compiling without optimizations, just the order of the registers changed a bit, but it's still the wrong order. I know I could do "mov r0, %[param1]" etc. but that would prevent optimizations and therefore result in slower code.
Is it a bug in GCC (4.8.2) or did I overlooking something?