Skip to content

Instantly share code, notes, and snippets.

@hzhangxyz
Created September 21, 2018 13:11
Show Gist options
  • Save hzhangxyz/2205fab239fd873637d15d8cd16ff1c0 to your computer and use it in GitHub Desktop.
Save hzhangxyz/2205fab239fd873637d15d8cd16ff1c0 to your computer and use it in GitHub Desktop.
currify
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
typedef int (*SIN)(int);
typedef int (*DOU)(int,int);
int proto(int b){
DOU fun=(DOU)'+';
int a=(int)'-';
return fun(a,b);
}
int _proto(){return 0;}
SIN currify(DOU fun,int a){
long size = (long)_proto - (long)proto;
void* this = valloc(size);
char* i;
memcpy(this,proto,size);
int err = mprotect(this, size, PROT_READ | PROT_WRITE | PROT_EXEC);
if(err){exit(1);}
for(i = (char*) this;i<(char*) this+size;i++){
if(*i=='+'){
*((DOU *)i)=fun;
}
if(*i=='-'){
*((int *)i)=a;
}
}
return (SIN)(this);
}
int add(int a,int b){return a+b;}
int times(int a,int b){return a*b;}
int divide(int a,int b){return b/a;}
int main(){
SIN add3 = currify(add,3);
printf("%d\n",add3(3));
return 0;
}
0x55555555a000 push %rbp
0x55555555a001 mov %rsp,%rbp
0x55555555a004 sub $0x20,%rsp
0x55555555a008 mov %edi,-0x14(%rbp)
0x55555555a00b movq $0x2b,-0x8(%rbp) //
0x55555555a013 movl $0x2d,-0xc(%rbp)
0x55555555a01a mov -0x14(%rbp),%ecx
0x55555555a01d mov -0xc(%rbp),%edx
0x55555555a020 mov -0x8(%rbp),%rax
0x55555555a024 mov %ecx,%esi
0x55555555a026 mov %edx,%edi
0x55555555a028 callq *%rax
0x55555555a02a leaveq
fun = 0x555555555279
a = 3
0x55555555a000 push %rbp
0x55555555a001 mov %rsp,%rbp
0x55555555a004 sub $0x20,%rsp
0x55555555a008 mov %edi,-0x14(%rbp)
0x55555555a00b movq $0x55555279,-0x8(%rbp) //
0x55555555a013 push %rbp
0x55555555a014 push %rbp
0x55555555a015 add %al,(%rax)
0x55555555a017 add %al,(%rax)
0x55555555a019 add %cl,0x558bec4d(%rbx)
0x55555555a01f hlt
0x55555555a020 mov -0x8(%rbp),%rax
0x55555555a024 mov %ecx,%esi
0x55555555a026 mov %edx,%edi
0x55555555a028 callq *%rax
0x55555555a02a leaveq
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment