1. 程式人生 > 實用技巧 >nasm astrcat函式 x86

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;
}