mir
mir copied to clipboard
Question: Inline assembly? Atomics?
I've been able to run many C libraries using C2M, but there are some corner cases that are not possible because of some platform specific feature, such use atomics or use of inline assembly (for instructions like cpuid
, rdtsc
).
I was just thinking what would take to workaround these features in pure C2M code, that is, without recurring to link an external library providing the functionality. For example I know atomics can be done with inline assembly, but I don't think having support __asm__
like GCC is worth due to the complexity that comes with it. One way I've worked around to inject assembly code in C compilers without __asm__
is to make assembly blobs like the following:
__attribute__((section(".text"))) static unsigned char _add_code[] = {
0x48, 0x8d, 0x04, 0x37, // lea (%rdi,%rsi,1),%rax
0xc3, // ret
};
#include <assert.h>
int main() {
int (*add)(int, int) = (int(*)(int, int))_add_code;
int res = add(1, 2); // adds 1 + 2
assert(res == 3);
return 0;
}
The above compiles and works under GCC/Clang/TCC in x86-64 Linux, of course there are lots of things to consider when using binary blobs of assembly due to ABI/platform differences. But using the concept like above I was able for example to implement stackful coroutines in pure C some platforms (minicoro library).
Would such thing be possible with C2M? I think this could allow me to implement atomics for x86_64 for example using just binary assembly blobs, and other stuff some libraries uses like cpuid
instruction on x86_64.
I think it can be done. It is not a big job.
I'll put it on my todo list and think how to implement better (taking all targets into account). May be it will be implemented this year.