nasm astrcat函数 x86

xxx.asm

%define p1 ebp+8
%define p2 ebp+12
%define p3 ebp+16

section .text
  global dllmain
  export astrcat

dllmain:
  mov eax,1
  ret 12

astrcat:
  push ebp
  mov ebp,esp

  mov ecx,[p1]	; dst char ptr
  mov eax,[p2]	; src char ptr
  
  ; get dst char end
  .dstFor:
  cmp byte [ecx],0
  je .copyFor
  inc ecx
  jmp .dstFor
  
  .copyFor:
  cmp byte [eax],0
  je .return
  mov dl,byte [eax]
  mov byte [ecx],dl
  inc eax
  inc ecx
  jmp .copyFor
  
  .return:
  mov eax,1
  mov esp,ebp
  pop ebp
  ret 8

c++:

#include <iostream>
#include <Windows.h>

typedef int (CALLBACK* astrcat_t)(char* dst, const char* src);

astrcat_t astrcat;

int main()
{
  HMODULE myDLL = LoadLibraryA("xxx.dll");
  astrcat = (astrcat_t)GetProcAddress(myDLL, "astrcat");

  const char* a = "hello";
  const char* b = " world";
  char dst[10] = { 0 };

  astrcat(dst, a);
  astrcat(dst, b);
  
  printf("%p\n", dst);

  // 很明显长度超过了申请的大小10
  // 为什么不会出问题,因为char*最后不仅有个NULL(0),还有自然对齐(align)填充的0
  // 如果超过了align,就会出问题
  printf("%s\n", dst); // hello world
  printf("%s%s\n", a, b); // hello world

  getchar();
  return 0;
}
posted @ 2020-09-23 18:52  Ajanuw  阅读(249)  评论(0编辑  收藏  举报