Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   Convertir C++ a Delphi (https://www.clubdelphi.com/foros/showthread.php?t=91607)

0x90 15-03-2017 02:15:15

Convertir C++ a Delphi
 
Hola Compañeros de ClubDelphi,

Por este medio quisiera expresarme y pedir una mano de ayuda, pasa que estoy trabajando en un codigo fuente que esta hecho en C++ y ando tratando de trasladarlo / convertirlo a Delph, La version del codigo que tengo es en C++, para mi es facil de entender porque he trabajado mas con C++ que con el mismo Delphi, ahora, ya que llevo poco tiempo aprendiendo y desarrollandome en Delphi pues se me hace un poco dificil convertir solo una parte del codigo, y aqui es donde me he quedado.

Aqui les voy a dejar el codigo fuente en cuestion el cual estoy tratando de trasladar.

Código:

#include "stdafx.h"
#include "windows.h"
#include "stdio.h"

#define MemorySectionName        0x2
#define MemoryBasicVlmInformation 0x3

struct UNICODE_S
{
        unsigned short len;
        unsigned short man_len;
        wchar_t* pStr;
};
struct MEMORY_BASIC_VLM_INFORMATION
{
        unsigned long ImageBase;
        unsigned long blah[0x2];
        unsigned long SizeOfImage;
};
extern "C"
{
        int __stdcall ZwQueryVirtualMemory(HANDLE,void*,int,void*,int,unsigned long*);
}
int main(int argc, char* argv[])
{
        SYSTEM_INFO SI={0};
        GetSystemInfo(&SI);
        unsigned long min_addr=(unsigned long)(SI.lpMinimumApplicationAddress);
        unsigned long max_addr=(unsigned long)(SI.lpMaximumApplicationAddress);
        UNICODE_S* p = (UNICODE_S*) LocalAlloc(LMEM_ZEROINIT, 0x1000);  //allocate one page, to receive image file name
        for(unsigned long i = min_addr; i <= max_addr; i += (SI.dwPageSize))
        {
                MEMORY_BASIC_INFORMATION MBI={0};
                if(VirtualQuery((void*)i,&MBI,sizeof(MBI)))
                {
                        if(MBI.Type==MEM_IMAGE)
                        {
                                ZwQueryVirtualMemory(GetCurrentProcess(),(void*)i,MemorySectionName,p,0x1000,0);
                                wprintf(L"Module: %s\r\n",p->pStr);

                                unsigned long out=0;
                                      MEMORY_BASIC_VLM_INFORMATION MBVI={0};
                                ZwQueryVirtualMemory(GetCurrentProcess(),(void*)i,MemoryBasicVlmInformation,&MBVI,sizeof(MBVI),&out);
                                unsigned long IB=MBVI.ImageBase;
                                wprintf(L"  at:%X",IB);
                                unsigned long szImage=MBVI.SizeOfImage;
                                wprintf(L"  size:%X\r\n",szImage);
                                i+=szImage;
                        }
                }       
        }       
        return 0;
}

Y aqui es lo que ya tengo hecho:

Código Delphi [-]
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    cbb1: TComboBox;
    Label1: TLabel;
    ListBox1: TListBox;
    Button1: TButton;
    btn1: TButton;
    procedure btn1Click(Sender: TObject);
    procedure Button1Click(Sender: TObject);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

type
       _UNICODE_S = record
         len : Word;
         man_len  : Word;
         pStr  : PWideChar;
     end;

     type
        _MEMORY_BASIC_VLM_INFORMATION = record
          ImageBase : LongWord;
          Suits : array[$0..$2] of LongWord;
          SizeOfImage : LongWord;
      end;

     var
     UNICODE_S : _UNICODE_S;
     MEMORY_BASIC_VLM_INFORMATION : _MEMORY_BASIC_VLM_INFORMATION;

type
    NTSTATUS = LongInt;
    TProcFunction = function(ProcHandle: THandle): NTSTATUS; stdcall;

implementation

uses
  JclSysInfo, JclRegistry, JwaNative, JwaWinType, JwaPsApi;

{$R *.dfm}

const MemorySectionName         = $2;
const MemoryBasicVlmInformation = $3;
const LHND = $0042;
const LMEM_FIXED = $0000;
const LMEM_MOVEABLE = $0002;
const LMEM_ZEROINIT = $0040;
const LPTR = $0040;
const NONZEROLHND = $0002;
const NONZEROLPTR = $0000;

var
  //NTSTATUS ZwQueryVirtualMemory(HANDLE ProcessHandle, PVOID BaseAddress, MEMORY_INFORMATION_CLASS MemoryInformationClass, PVOID MemoryInformation, SIZE_T MemoryInformationLength, PSIZE_T ReturnLength);
  ZwQueryVirtualMemory: function(ProcessHandle: HANDLE; BaseAddress: PVOID; MemoryInformationClass: MEMORY_INFORMATION_CLASS; MemoryInformation: PVOID; MemoryInformationLength: ULONG; ReturnLength: PULONG): NTSTATUS; stdcall;

procedure TForm1.btn1Click(Sender: TObject);
begin
  // Processes
  cbb1.Items.BeginUpdate;
  try
    cbb1.Items.Clear;
    RunningProcessesList(cbb1.Items);
  finally
    cbb1.Items.EndUpdate;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  lpSystemInfo: _SYSTEM_INFO;
  min_addr: ULONG;
  max_addr: ULONG;
  LibHandle: THandle;
  p: _UNICODE_S;
  LocalAlloc: TProcFunction;
begin
   LibHandle := SafeLoadLibrary('Kernel32.dll');

   if LibHandle <> 0
   then
     begin
       @LocalAlloc  := GetProcAddress(LibHandle, 'LocalAlloc');
       GetSystemInfo(lpSystemInfo);
       min_addr := dword(lpSystemInfo.lpMinimumApplicationAddress);
       max_addr := dword(lpSystemInfo.lpMaximumApplicationAddress);
       //UNICODE_S* p = (UNICODE_S*) LocalAlloc(LMEM_ZEROINIT, 0x1000);
       //Aqui es donde me estoy estancando.
     end
   else
     begin
       //NIL
     end;
end;

end.

bueno hasta aqui mi peticion, quiero aclarar para que nadie se ofenda, no pretendo que me den todo en la boca con una cuchara ("spoonfeeding") o digan "vino aqui para que le hagamos el codigo", nada de eso, si ven la gran parte del codigo ya lo tengo bastante dominado (a mi parecer) lo que quisiera es una mano, en como podria implementar la siguiente parte que me resta.

Bueno hasta aqui los dejo.

Saludos,
0x90

Reasen 15-03-2017 23:23:09

No sé exactamente qué quieres ni tengo mucha práctica con C++ pero te dejo una base mas limpia para que puedas continuar haciendo pruebas. (Basandome en el código de C++)



Código Delphi [-]
uses
  System.SysUtils,
  messages,
  Winapi.Windows;

var
  Sysinfo: _SYSTEM_INFO;
  min_addr, max_addr: DWORD;
  i:Cardinal;
  MBI:MEMORY_BASIC_INFORMATION;
const
  MemorySectionName = $2;
  MemoryBasicVlmInformation = $3;
  LHND = $0042;
  LMEM_FIXED = $0000;
  LMEM_MOVEABLE = $0002;
  LMEM_ZEROINIT = $0040;
  LPTR = $0040;
  NONZEROLHND = $0002;
  NONZEROLPTR = $0000;

begin
  GetSystemInfo(Sysinfo);
  min_addr := DWORD(Sysinfo.lpMinimumApplicationAddress);
  max_addr := DWORD(Sysinfo.lpMaximumApplicationAddress);
  LocalAlloc(LMEM_ZEROINIT, $1000);

  for i := min_addr to max_addr + Sysinfo.dwPageSize do
  begin  
 if VirtualQuery(Pointer(DWORD(i)),MBI,SizeOf(MBI)) = 0 then
    if MBI.Type_9 = mem_image then


  end;
end.

0x90 16-03-2017 03:55:47

Cita:

Empezado por Reasen (Mensaje 514382)
No sé exactamente qué quieres ni tengo mucha práctica con C++ pero te dejo una base mas limpia para que puedas continuar haciendo pruebas. (Basandome en el código de C++)



Código Delphi [-]
uses
  System.SysUtils,
  messages,
  Winapi.Windows;

var
  Sysinfo: _SYSTEM_INFO;
  min_addr, max_addr: DWORD;
  i:Cardinal;
  MBI:MEMORY_BASIC_INFORMATION;
const
  MemorySectionName = $2;
  MemoryBasicVlmInformation = $3;
  LHND = $0042;
  LMEM_FIXED = $0000;
  LMEM_MOVEABLE = $0002;
  LMEM_ZEROINIT = $0040;
  LPTR = $0040;
  NONZEROLHND = $0002;
  NONZEROLPTR = $0000;

begin
  GetSystemInfo(Sysinfo);
  min_addr := DWORD(Sysinfo.lpMinimumApplicationAddress);
  max_addr := DWORD(Sysinfo.lpMaximumApplicationAddress);
  LocalAlloc(LMEM_ZEROINIT, $1000);

  for i := min_addr to max_addr + Sysinfo.dwPageSize do
  begin  
 if VirtualQuery(Pointer(DWORD(i)),MBI,SizeOf(MBI)) = 0 then
    if MBI.Type_9 = mem_image then


  end;
end.

¡Tanto tiempo Reasen!
Muchas gracias por darme una mano ^\||/

Lo que me diste funciona perfectamente (compila y no tengo errores), pues ahora toca finalizar el codigo y ver que mas puedo hacer, el codigo es inofensivo y lo que hace es enumerar los modulos (dlls) dentro de un proceso incluyendo aun los que este escondidos.

Ahora a la hora de ejecutar el proceso, y usar la funcion, no se que estoy haciendo mal, puede que si este haciendo algo mal, pero el proceso se cuelga, he aqui lo que estoy tratando de hacer...

Asi va la estructura `UNICODE_S`
Código Delphi [-]
type
       _UNICODE_S = record
         len : Word;
         man_len  : Word;
         pStr  : PWideChar;
       end;

       UNICODE_S = _UNICODE_S;

Asi va lo que tengo gracias a tu ayuda.
Código Delphi [-]
procedure TForm1.Button1Click(Sender: TObject);
var
  lpSystemInfo: _SYSTEM_INFO;
  min_addr: ULONG;
  max_addr: ULONG;
  LibHandle: THandle;
  p: ^_UNICODE_S;
  pid: NativeUInt;
begin
  GetSystemInfo(Sysinfo);
  min_addr := DWORD(Sysinfo.lpMinimumApplicationAddress);
  max_addr := DWORD(Sysinfo.lpMaximumApplicationAddress);
  p := Pointer(LocalAlloc(LMEM_ZEROINIT, $1000));

  for i := min_addr to max_addr + Sysinfo.dwPageSize do
  begin
 if VirtualQuery(PVOID(i), MBI, SizeOf(MBI)) = 0 then
    if MBI.Type_9 = mem_image
    then
    begin

       //ZwQueryVirtualMemory(GetCurrentProcess(), (void*)i , MemorySectionName, p, 0x1000, 0);
       ZwQueryVirtualMemory(GetCurrentProcess, PVOID(i), MemorySectionName, p, $1000, 0);

       // List Modules in the ListBox
       ListBox1.Items.BeginUpdate;
       try
         ListBox1.Items.Clear;
         ListBox1.Items.Add(WideCharToString(p.pStr));
       finally
         ListBox1.Items.EndUpdate;
       end;
    end
    else
    begin

    end;

  end;
end;


Saludos, Espero que estes bien :p

Reasen 16-03-2017 05:20:12

Ah, querías enumerar las DLL cargadas...

Para saber si están ocultas o no, tendras que profundizar un poco más, pero puedes guiarte con esa base.

Igualmente más vale prevenir que curar, invierte mas en métodos de anti-dll_injection y anti-hooking

Código Delphi [-]
program Project2;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  SysUtils, Windows, TlHelp32;

var
  Handle: THandle;
  ModuleEntry: TModuleEntry32;
begin
  Handle := CreateToolHelp32SnapShot(TH32CS_SNAPMODULE, 0);
  Win32Check(Handle <> INVALID_HANDLE_VALUE);
  try
    ModuleEntry.dwSize := Sizeof(ModuleEntry);
    Win32Check(Module32First(Handle, ModuleEntry));
    repeat
      Writeln(ModuleEntry.szModule);
    until not Module32Next(Handle, ModuleEntry);
  finally
    CloseHandle(Handle);
  end;
  Readln;
end.

Fuente: http://stackoverflow.com/questions/2...t-of-used-dlls

0x90 16-03-2017 06:09:01

Cita:

Empezado por Reasen (Mensaje 514387)
Ah, querías enumerar las DLL cargadas...

Para saber si están ocultas o no, tendras que profundizar un poco más, pero puedes guiarte con esa base.

Igualmente más vale prevenir que curar, invierte mas en métodos de anti-dll_injection y anti-hooking

Código Delphi [-]
program Project2;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  SysUtils, Windows, TlHelp32;

var
  Handle: THandle;
  ModuleEntry: TModuleEntry32;
begin
  Handle := CreateToolHelp32SnapShot(TH32CS_SNAPMODULE, 0);
  Win32Check(Handle <> INVALID_HANDLE_VALUE);
  try
    ModuleEntry.dwSize := Sizeof(ModuleEntry);
    Win32Check(Module32First(Handle, ModuleEntry));
    repeat
      Writeln(ModuleEntry.szModule);
    until not Module32Next(Handle, ModuleEntry);
  finally
    CloseHandle(Handle);
  end;
  Readln;
end.

Bueno sale, gracias por toda la ayuda :D


La franja horaria es GMT +2. Ahora son las 00:35:58.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi