Page 1 of 1

assembly in c file without using gcc inline asm?

Posted: Fri Feb 26, 2021 2:09 am
by clementttttttttt
I remember I've seen glibc did that before in the source code, but I forgot where.

Re: assembly in c file without using gcc inline asm?

Posted: Fri Feb 26, 2021 3:41 am
by iansjack
You can use inline assembly or link in an object file produced by a separate assembler. I can't think of any other way to get assembly code into a C program. How else do you think you could specify the instructions that you wanted?

Re: assembly in c file without using gcc inline asm?

Posted: Fri Feb 26, 2021 7:02 pm
by AndrewAPrice
You can also assemble your assembly code into machine code, then define it as a hardcoded byte array in C and call it.

Re: assembly in c file without using gcc inline asm?

Posted: Sat Feb 27, 2021 3:13 am
by iansjack
I hadn't thought of that. But wouldn't that require your data pages to be executable, which doesn't seem like a good idea to me.

Re: assembly in c file without using gcc inline asm?

Posted: Sat Feb 27, 2021 4:26 am
by nullplan
iansjack wrote:I hadn't thought of that. But wouldn't that require your data pages to be executable, which doesn't seem like a good idea to me.
Well, in my standard linker script, constant data is usually made part of the executable segment, so as long as you declare the array as constant it should work out. Though recently, binutils has shipped a new standard linker script that puts constant data into a nonexecutable segment, with the rationale of making it harder to find ROP gadgets. Of course, the additional page alignment overhead of this is pretty bad, especially for applications that try to limit memory consumption.

Re: assembly in c file without using gcc inline asm?

Posted: Sat Feb 27, 2021 7:40 am
by clementttttttttt
By the way, I think they did it by using some kind of compiler directive.

Re: assembly in c file without using gcc inline asm?

Posted: Sat Feb 27, 2021 8:38 am
by iansjack
nullplan wrote:
iansjack wrote:I hadn't thought of that. But wouldn't that require your data pages to be executable, which doesn't seem like a good idea to me.
Well, in my standard linker script, constant data is usually made part of the executable segment, so as long as you declare the array as constant it should work out. Though recently, binutils has shipped a new standard linker script that puts constant data into a nonexecutable segment, with the rationale of making it harder to find ROP gadgets. Of course, the additional page alignment overhead of this is pretty bad, especially for applications that try to limit memory consumption.
I'm sure that you are correct but, in any case, it doesn't seem to be a very useful way of including machine code into a C program unless you are looking at self-modifying code.