Search code examples
cpseudocode

Converting pseudo-code into C/C++ source code


I've been learning a lot about de-compiling functions and some other things but I got stuck on a particular situation; I was playing with my C code and I got a pseudo code from a particular function.

This function is called

int seekANDReplace(char *string, int size,
                          const char *seek, const char *replace)

And from the previous function I got something like this using HEXRAY Decompiler:

__int64 __fastcall seekANDReplace(_BYTE *a1, int a2, _BYTE *a3, _BYTE *a4)
{
  char v4; // al
  _BYTE *v6; // r12
  char v7; // r8
  _BYTE *v8; // rbx
  int v9; // ebx
  __int64 v10; // r14
  _BYTE *v11; // rbx
  unsigned int i; // esi
  int v13; // er13
  int v14; // ebx
  _BYTE *v15; // rax
  int v16; // edi
  __int64 v17; // r10
  __int64 v18; // r11
  __int64 v19; // rax
  __int64 v20; // r10
  __int64 v21; // rdx
  _BYTE *v22; // r8
  __int64 v23; // r8

  v4 = *a3;
  v6 = a4;
  v7 = *a4;
  if ( v4 )
  {
    v8 = a3;
    do
      ++v8;
    while ( *v8 );
    v9 = (_DWORD)v8 - (_DWORD)a3;
    v10 = v9;
    if ( !v7 )
    {
      v14 = -v9;
      v13 = 0;
      goto LABEL_9;
    }
  }
  else
  {
    v10 = 0i64;
    if ( !v7 )
      return 0;
  }
  v11 = a4;
  do
    ++v11;
  while ( *v11 );
  i = 0;
  if ( !v4 )
    return i;
  v13 = (_DWORD)v11 - (_DWORD)a4;
  v14 = (_DWORD)v11 - (_DWORD)a4 - v10;
LABEL_9:
  if ( *a1 )
  {
    v15 = a1;
    do
      ++v15;
    while ( *v15 );
    a2 -= (_DWORD)v15 - (_DWORD)a1;
  }
  v16 = a2 - 1;
  for ( i = 0; ; ++i )
  {
    v19 = __strstri(a1, a3);
    v20 = v19;
    if ( !v19 )
      break;
    if ( v16 < v14 )
      return ~i;
    if ( v14 )
    {
      v21 = v19 + v10;
      v16 -= v14;
      if ( *(_BYTE *)(v19 + v10) )
      {
        v22 = (_BYTE *)(v19 + v10);
        do
          ++v22;
        while ( *v22 );
        v23 = (int)v22 - (int)v21 + 1;
      }
      else
      {
        v23 = 1i64;
      }
      __memmove(v19 + v10 + v14, v21, v23);
    }
    __memmove(v20, v6, v13);
    a1 = (_BYTE *)(v17 + v18);
  }
  return i;
}

The problem is that it is not pure C or C++ source code, far from it... I would like to display a more readable code. How can I achieve something like that and get some C code in order to debug?


Solution

  • This is actually compilable C code.

    None of the variables have names because that information is not in the executable (unless it was compiled with debug settings). The types being used are typedefs for certain integer types which presumably the decompiler has available as a header file. So given that header you can recompile this source file.