Skip to content

Instantly share code, notes, and snippets.

@stevenjohnstone
Created January 12, 2019 21:56
Show Gist options
  • Save stevenjohnstone/5d8e6a2c7ab64613bb585856b52ac271 to your computer and use it in GitHub Desktop.
Save stevenjohnstone/5d8e6a2c7ab64613bb585856b52ac271 to your computer and use it in GitHub Desktop.
Embedding 0x03 in C
#include <stdio.h>
static int x3(int a, int b) {
int out;
asm(
// it's not stated in xchg rax,rax but it's
// intel syntax. Note the noprefix means we
// don't need % before registers
".intel_syntax noprefix;"
// a bit of preamble to get registers
// set up correctly. We're okay with just working
// with int rather than long int
"mov eax, %1;"
"mov edx, %2;"
// 0x03 code below
"sub rdx, rax;"
"sbb rcx,rcx;"
"and rcx,rdx;"
"add rax,rcx;"
// put the result into out
"mov %0, eax;"
// tell the compiler that out is in memory
: "=m" (out)
// tell the compiler that a and b are inputs
: "m" (a) , "m" (b)
// this is the list of registers which are clobbered
: "rax","rdx","rcx");
return out;
}
struct input {
int a;
int b;
};
int main(int argc, const char **argv) {
struct input inputs[] = {
{0x0, 0x1},
{0x1, 0x1},
{0xf, 0xe},
{0xe, 0xf},
{~0, 0x00},
};
for (int i = 0; i < sizeof(inputs)/sizeof(inputs[0]); i++) {
printf("%d (rax: %016x rdx %016x) -> rax: %016x\n",
i, inputs[i].a, inputs[i].b, x3(inputs[i].a, inputs[i].b));
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment