Skip to content

Instantly share code, notes, and snippets.

@Tokubara
Created July 3, 2021 09:59
Show Gist options
  • Save Tokubara/15f1708d33ca6a99314d39ba0ed491d7 to your computer and use it in GitHub Desktop.
Save Tokubara/15f1708d33ca6a99314d39ba0ed491d7 to your computer and use it in GitHub Desktop.
不用libc, 使用汇编实现的memcpy
void memcpy(void* dst, void* src, unsigned len);
int _start()
{
int a[]={1,2,3,4};
int b[4];
memcpy(b,a,sizeof(a));
asm("movl $1,%eax;"
"xorl %ebx,%ebx;"
"int $0x80"
);
}
AS = gcc
CC = gcc
LD = ld
ASFLAGS += -g -m32
CFLAGS += -g -O0
CFLAGS += -march=i386 -m32 -fno-stack-protector
CFLAGS += -fcf-protection=none # remove endbr32 in Ubuntu 20.04 with a CPU newer than Comet Lake
LDFLAGS += -melf_i386
main: main.o memcpy.o
$(LD) $(LDFLAGS) -o main $^
memcpy.o: memcpy.S
$(AS) $(ASFLAGS) -c -o $@ $<
main.o: main.c
$(CC) $(CFLAGS) -c -o $@ $<
run: main
./main
clean:
rm -rf *.o ./main
#define PARMS 12 // 因为有2个callee-saved寄存器
#define RTN PARMS
#define DEST RTN
#define SRC DEST+4
#define LEN SRC+4
.section .text
.global memcpy
memcpy:
pushl %edi
pushl %esi
movl DEST(%esp), %edi
movl SRC(%esp), %esi
movl LEN(%esp), %ecx
/* We need this in any case. */
cld
rep; movsb
popl %esi
popl %edi
ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment