Delphi从资源中释放exe到内存后加载的问题(100)

  • 主题发起人 主题发起人 百草霜
  • 开始时间 开始时间

百草霜

Unregistered / Unconfirmed
GUEST, unregistred user!
我想要实现的功能:1 把exe和bat文件放在资源文件中2 从资源文件中释放exe到内存,然后加载,不在硬盘上写文件,实现从内存中加载exe。3 从资源文件中释放DOS环境下的exe和bat到内存,然后加载,不在硬盘上写文件,实现从内存中加载exe和bat(这个exe是CMD窗口格式的),并得到返回信息。目前已经实现了 1 和 2,3尚未实现,执行3的时候,因为释放出来的exe文件不是 真正的win32程序,而是dos的exe,一闪而过,看不到返回的信息,我想要的是 如何 把 dos的exe或者bat文件释放到内存,然后加载,而且得到返回的信息,比如说我 有一个dos下的exe “jiami.exe”,CMD窗口中执行 "jiami.exe 123456" 返回加密后的字符串“ABCDE”,我想得到“ABCDE”,如何实现?我用的内存加载exe的方法是 :{ ******************************************************* }{ * 从内存中加载并运行exe * }{ ******************************************************* }{ * 参数: }{ * Buffer: 内存中的exe地址 }{ * Len: 内存中exe占用长度 }{ * CmdParam: 命令行参数(不包含exe文件名的剩余命令行参数)}{ * ProcessId: 返回的进程Id }{ * 返回值: 如果成功则返回进程的Handle(ProcessHandle), }{ 如果失败则返回INVALID_HANDLE_VALUE }{ ******************************************************* }我补上我内存中调用exe的完整代码第一部分:unit PEUnit;interfaceuses windows;function MemExecute(const ABuffer; Len: Integer; CmdParam: string; var ProcessId: Cardinal): Cardinal;implementation//{$R ExeShell.res} // 外壳程序模板(98下使用)typeTImageSectionHeaders = array [0..0] of TImageSectionHeader;PImageSectionHeaders = ^TImageSectionHeaders;{ 计算对齐后的大小 }function GetAlignedSize(Origin, Alignment: Cardinal): Cardinal;beginresult := (Origin + Alignment - 1) div Alignment * Alignment;end;{ 计算加载pe并对齐需要占用多少内存,未直接使用OptionalHeader.SizeOfImage作为结果是因为据说有的编译器生成的exe这个值会填0 }function CalcTotalImageSize(MzH: PImageDosHeader; FileLen: Cardinal; peH: PImageNtHeaders;peSecH: PImageSectionHeaders): Cardinal;vari: Integer;begin{计算pe头的大小}result := GetAlignedSize(PeH.OptionalHeader.SizeOfHeaders, PeH.OptionalHeader.SectionAlignment);{计算所有节的大小}for i := 0 to peH.FileHeader.NumberOfSections - 1 doif peSecH.PointerToRawData + peSecH.SizeOfRawData > FileLen then // 超出文件范围beginresult := 0;exit;endelse if peSecH.VirtualAddress <> 0 then //计算对齐后某节的大小if peSecH.Misc.VirtualSize <> 0 thenresult := GetAlignedSize(peSecH.VirtualAddress + peSecH.Misc.VirtualSize, PeH.OptionalHeader.SectionAlignment)elseresult := GetAlignedSize(peSecH.VirtualAddress + peSecH.SizeOfRawData, PeH.OptionalHeader.SectionAlignment)else if peSecH.Misc.VirtualSize < peSecH.SizeOfRawData thenresult := result + GetAlignedSize(peSecH.SizeOfRawData, peH.OptionalHeader.SectionAlignment)elseresult := result + GetAlignedSize(peSecH.Misc.VirtualSize, PeH.OptionalHeader.SectionAlignment);end;{ 加载pe到内存并对齐所有节 }function AlignPEToMem(const Buf; Len: Integer; var PeH: PImageNtHeaders;var PeSecH: PImageSectionHeaders; var Mem: Pointer; var ImageSize: Cardinal): Boolean;varSrcMz: PImageDosHeader; // DOS头SrcPeH: PImageNtHeaders; // PE头SrcPeSecH: PImageSectionHeaders; // 节表i: Integer;l: Cardinal;Pt: Pointer;beginresult := false;SrcMz := @Buf;if Len < sizeof(TImageDosHeader) then exit;if SrcMz.e_magic <> IMAGE_DOS_SIGNATURE then exit;if Len < SrcMz._lfanew+Sizeof(TImageNtHeaders) then exit;SrcPeH := pointer(Integer(SrcMz)+SrcMz._lfanew);if (SrcPeH.Signature <> IMAGE_NT_SIGNATURE) then exit;if (SrcPeH.FileHeader.Characteristics and IMAGE_FILE_DLL <> 0) or(SrcPeH.FileHeader.Characteristics and IMAGE_FILE_EXECUTABLE_IMAGE = 0)or (SrcPeH.FileHeader.SizeOfOptionalHeader <> SizeOf(TImageOptionalHeader)) then exit;SrcPeSecH := Pointer(Integer(SrcPeH)+SizeOf(TImageNtHeaders));ImageSize := CalcTotalImageSize(SrcMz, Len, SrcPeH, SrcPeSecH);if ImageSize = 0 thenexit;Mem := VirtualAlloc(nil, ImageSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // 分配内存if Mem <> nil thenbegin// 计算需要复制的PE头字节数l := SrcPeH.OptionalHeader.SizeOfHeaders;for i := 0 to SrcPeH.FileHeader.NumberOfSections - 1 doif (SrcPeSecH.PointerToRawData <> 0) and (SrcPeSecH.PointerToRawData < l) thenl := SrcPeSecH.PointerToRawData;Move(SrcMz^, Mem^, l);PeH := Pointer(Integer(Mem) + PImageDosHeader(Mem)._lfanew);PeSecH := Pointer(Integer(PeH) + sizeof(TImageNtHeaders));Pt := Pointer(Cardinal(Mem) + GetAlignedSize(PeH.OptionalHeader.SizeOfHeaders, PeH.OptionalHeader.SectionAlignment));for i := 0 to PeH.FileHeader.NumberOfSections - 1 dobegin// 定位该节在内存中的位置if PeSecH.VirtualAddress <> 0 thenPt := Pointer(Cardinal(Mem) + PeSecH.VirtualAddress);if PeSecH.SizeOfRawData <> 0 thenbegin// 复制数据到内存Move(Pointer(Cardinal(SrcMz) + PeSecH.PointerToRawData)^, pt^, PeSecH.SizeOfRawData);if peSecH.Misc.VirtualSize < peSecH.SizeOfRawData thenpt := pointer(Cardinal(pt) + GetAlignedSize(PeSecH.SizeOfRawData, PeH.OptionalHeader.SectionAlignment))elsept := pointer(Cardinal(pt) + GetAlignedSize(peSecH.Misc.VirtualSize, peH.OptionalHeader.SectionAlignment));// pt 定位到下一节开始位置endelsept := pointer(Cardinal(pt) + GetAlignedSize(PeSecH.Misc.VirtualSize, PeH.OptionalHeader.SectionAlignment));end;result := True;end;end;typeTVirtualAllocEx = function (hProcess: THandle; lpAddress: Pointer;dwSize, flAllocationType: DWORD; flProtect: DWORD): Pointer; stdcall;varMyVirtualAllocEx: TVirtualAllocEx = nil;function IsNT: Boolean;beginresult := Assigned(MyVirtualAllocEx);end;{ 生成外壳程序命令行 }function PrepareShellExe(CmdParam: string; BaseAddr, ImageSize: Cardinal): string;varr, h, sz: Cardinal;p: Pointer;fid, l: Integer;buf: Pointer;peH: PImageNtHeaders;peSecH: PImageSectionHeaders;beginif IsNT then{ NT 系统下直接使用自身程序作为外壳进程 }result := ParamStr(0)+CmdParamelse begin// 由于98系统下无法重新分配外壳进程占用内存,所以必须保证运行的外壳程序能容纳目标进程并且加载地址一致// 此处使用的方法是从资源中释放出一个事先建立好的外壳程序,然后通过修改其PE头使其运行时能加载到指定地址并至少能容纳目标进程r := FindResource(HInstance, 'SHELL_EXE', RT_RCDATA);h := LoadResource(HInstance, r);p := LockResource(h);l := SizeOfResource(HInstance, r);GetMem(Buf, l);Move(p^, Buf^, l); // 读到内存FreeResource(h);peH := Pointer(Integer(Buf) + PImageDosHeader(Buf)._lfanew);peSecH := Pointer(Integer(peH) + sizeof(TImageNtHeaders));peH.OptionalHeader.ImageBase := BaseAddr; // 修改PE头重的加载基址if peH.OptionalHeader.SizeOfImage < ImageSize then // 目标比外壳大,修改外壳程序运行时占用的内存beginsz := Imagesize - peH.OptionalHeader.SizeOfImage;Inc(peH.OptionalHeader.SizeOfImage, sz); // 调整总占用内存数Inc(peSecH[peH.FileHeader.NumberOfSections-1].Misc.VirtualSize, sz); // 调整最后一节占用内存数end;// 生成外壳程序文件名, 为本程序改后缀名得到的// 由于不想 uses SysUtils (一旦 use 了程序将增大80K左右), 而且偷懒,所以只支持最多运行11个进程,后缀名为.dat, .da0~.da9result := ParamStr(0);result := copy(result, 1, length(result) - 4) + '.dat';r := 0;while r < 10 dobeginfid := CreateFile(pchar(result), GENERIC_READ or GENERIC_WRITE, 0, nil, Create_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);if fid < 0 thenbeginresult := copy(result, 1, length(result)-3)+'da'+Char(r+Byte('0'));inc(r);endelse begin//SetFilePointer(fid, Imagesize, nil, 0);//SetEndOfFile(fid);//SetFilePointer(fid, 0, nil, 0);WriteFile(fid, Buf^, l, h, nil); // 写入文件CloseHandle(fid);break;end;end;result := result + CmdParam; // 生成命令行FreeMem(Buf);end;end;{ 是否包含可重定向列表 }function HasRelocationTable(peH: PImageNtHeaders): Boolean;beginresult := (peH.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress <> 0)and (peH.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size <> 0);end;typePImageBaseRelocation= ^TImageBaseRelocation;TImageBaseRelocation = packed recordVirtualAddress: cardinal;SizeOfBlock: cardinal;end;{ 重定向PE用到的地址 }procedure DoRelocation(peH: PImageNtHeaders; OldBase, NewBase: Pointer);varDelta: Cardinal;p: PImageBaseRelocation;pw: PWord;i: Integer;beginDelta := Cardinal(NewBase) - peH.OptionalHeader.ImageBase;p := pointer(cardinal(OldBase) + peH.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress);while (p.VirtualAddress + p.SizeOfBlock <> 0) dobeginpw := pointer(Integer(p) + Sizeof(p^));for i := 1 to (p.SizeOfBlock - Sizeof(p^)) div 2 dobeginif pw^ and $F000 = $3000 thenInc(PCardinal(Cardinal(OldBase) + p.VirtualAddress + (pw^ and $0FFF))^, Delta);inc(pw);end;p := Pointer(pw);end;end;typeTZwUnmapViewOfSection = function (Handle, BaseAdr: Cardinal): Cardinal; stdcall;{ 卸载原外壳占用内存 }function UnloadShell(ProcHnd, BaseAddr: Cardinal): Boolean;varM: HModule;ZwUnmapViewOfSection: TZwUnmapViewOfSection;beginresult := False;m := LoadLibrary('ntdll.dll');if m <> 0 thenbeginZwUnmapViewOfSection := GetProcAddress(m, 'ZwUnmapViewOfSection');if assigned(ZwUnmapViewOfSection) thenresult := (ZwUnmapViewOfSection(ProcHnd, BaseAddr) = 0);FreeLibrary(m);end;end;{ 创建外壳进程并获取其基址、大小和当前运行状态 }function CreateChild(Cmd: string; var Ctx: TContext; var ProcHnd, ThrdHnd, ProcId, BaseAddr, ImageSize: Cardinal): Boolean;varsi: TStartUpInfo;pi: TProcessInformation;Old: Cardinal;MemInfo: TMemoryBasicInformation;p: Pointer;beginFillChar(si, Sizeof(si), 0);FillChar(pi, SizeOf(pi), 0);si.cb := sizeof(si);result := CreateProcess(nil, PChar(Cmd), nil, nil, False, Create_SUSPENDED, nil, nil, si, pi); // 以挂起方式运行进程if result thenbeginProcHnd := pi.hProcess;ThrdHnd := pi.hThread;ProcId := pi.dwProcessId;{ 获取外壳进程运行状态,[ctx.Ebx+8]内存处存的是外壳进程的加载基址,ctx.Eax存放有外壳进程的入口地址 }ctx.ContextFlags := CONTEXT_FULL;GetThreadContext(ThrdHnd, ctx);ReadProcessMemory(ProcHnd, Pointer(ctx.Ebx+8), @BaseAddr, SizeOf(Cardinal), Old); // 读取加载基址p := Pointer(BaseAddr);{ 计算外壳进程占有的内存 }while VirtualQueryEx(ProcHnd, p, MemInfo, Sizeof(MemInfo)) <> 0 dobeginif MemInfo.State = MEM_FREE thenbreak;p := Pointer(Cardinal(p) + MemInfo.RegionSize);end;ImageSize := Cardinal(p) - Cardinal(BaseAddr);end;end;{ 创建外壳进程并用目标进程替换它然后执行 }function AttachPE(CmdParam: string; peH: PImageNtHeaders; peSecH: PImageSectionHeaders;Ptr: Pointer; ImageSize: Cardinal; var ProcId: Cardinal): Cardinal;vars: string;Addr, Size: Cardinal;ctx: TContext;Old: Cardinal;p: Pointer;Thrd: Cardinal;beginresult := INVALID_HANDLE_VALUE;s := PrepareShellExe(CmdParam, peH.OptionalHeader.ImageBase, ImageSize);if CreateChild(s, ctx, result, Thrd, ProcId, Addr, Size) thenbeginp := nil;if (peH.OptionalHeader.ImageBase = Addr) and (Size >= ImageSize) then // 外壳进程可以容纳目标进程并且加载地址一致beginp := Pointer(Addr);VirtualProtectEx(result, p, Size, PAGE_EXECUTE_READWRITE, Old);endelse if IsNT then // 98 下失败beginif UnloadShell(result, Addr) then // 卸载外壳进程占有内存// 重新按目标进程加载基址和大小分配内存p := MyVirtualAllocEx(Result, Pointer(peH.OptionalHeader.ImageBase), ImageSize, MEM_RESERVE or MEM_COMMIT, PAGE_EXECUTE_READWRITE);if (p = nil) and hasRelocationTable(peH) then // 分配内存失败并且目标进程支持重定向begin// 按任意基址分配内存p := MyVirtualAllocEx(result, nil, ImageSize, MEM_RESERVE or MEM_COMMIT, PAGE_EXECUTE_READWRITE);if p <> nil thenDoRelocation(peH, Ptr, p); // 重定向end;end;if p <> nil thenbeginWriteProcessMemory(Result, Pointer(ctx.Ebx+8), @p, Sizeof(DWORD), Old); // 重置目标进程运行环境中的基址peH.OptionalHeader.ImageBase := Cardinal(p);if WriteProcessMemory(Result, p, Ptr, ImageSize, Old) then // 复制PE数据到目标进程beginctx.ContextFlags := CONTEXT_FULL;if Cardinal(p) = Addr thenctx.Eax := peH.OptionalHeader.ImageBase + peH.OptionalHeader.AddressOfEntryPoint // 重置运行环境中的入口地址elsectx.Eax := Cardinal(p) + peH.OptionalHeader.AddressOfEntryPoint;SetThreadContext(Thrd, ctx); // 更新运行环境ResumeThread(Thrd); // 执行CloseHandle(Thrd);endelse begin // 加载失败,杀掉外壳进程TerminateProcess(Result, 0);CloseHandle(Thrd);CloseHandle(Result);Result := INVALID_HANDLE_VALUE;end;endelse begin // 加载失败,杀掉外壳进程TerminateProcess(Result, 0);CloseHandle(Thrd);CloseHandle(Result);Result := INVALID_HANDLE_VALUE;end;end;end;function MemExecute(const ABuffer; Len: Integer; CmdParam: string; var ProcessId: Cardinal): Cardinal;varpeH: PImageNtHeaders;peSecH: PImageSectionHeaders;Ptr: Pointer;peSz: Cardinal;beginresult := INVALID_HANDLE_VALUE;if alignPEToMem(ABuffer, Len, peH, peSecH, Ptr, peSz) then beginresult := AttachPE(CmdParam, peH, peSecH, Ptr, peSz, ProcessId);VirtualFree(Ptr, peSz, MEM_DECOMMIT);//VirtualFree(Ptr, 0, MEM_RELEASE);end;end;initializationMyVirtualAllocEx := GetProcAddress(GetModuleHandle('Kernel32.dll'), 'VirtualAllocEx');end.-----------------------------------------------------------实例:{$R jiami.RES}uses PEUnit;procedure TForm1.Button1Click(Sender: TObject);varABuffer: array of byte;Stream: TResourceStream;ProcessId: Cardinal;beginStream:=TResourceStream.Create(hinstance,'jiami','exefile');trySetLength(ABuffer, Stream.Size);Stream.ReadBuffer(ABuffer[0], Stream.Size);MemExecute(ABuffer[0], Stream.Size, ' 12345', ProcessId);finallyStream.Free;end;end;如果是win32的exe程序,运行正常,但DOS下的exe,会一闪而过,得不到返回信息。请各位高手指点,谢谢
 
CMD窗口中执行 "jiami.exe 123456" 返回加密后的字符串“ABCDE”,我想得到“ABCDE”,如何实现?用管道得到cmd运行后的返回信息获得IPconfig代码:unit Unit1;interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;type TForm1 = class(TForm) btn1: TButton; mmo1: TMemo; procedure btn1Click(Sender: TObject); private { Private declarations } public { Public declarations } end;var Form1: TForm1;implementation{$R *.dfm}procedure _WriteLogEx(F1,S1: string;T:Boolean=False);var FHandle: THandle; i: Integer;begin try if T then F1:=ExtractFilePath(ParamStr(0))+'Log/'+FormatDateTime('YYYY-MM-DD',Date)+'/'+F1+'_'+FormatDateTime('HH-MM-SS',Now)+'.log'; if not DirectoryExists(ExtractFileDir(F1)) then ForceDirectories(ExtractFileDir(F1)); FHandle := CreateFile(PChar(F1), GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (FHandle = 0) or (FHandle = INVALID_HANDLE_VALUE) then begin FHandle := CreateFile(PChar(F1), GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (FHandle = 0) or (FHandle = INVALID_HANDLE_VALUE) then begin Exit; end; end; SetFilePointer(FHandle, 0, nil, FILE_END); //S1 := FormatDateTime('yyyy-mm-dd hh:nn:ss ', NOW)+S1 + #13#10; S1 := S1 + #13#10; WriteFile(FHandle, S1[1], Length(S1), LongWord(i), nil); CloseHandle(FHandle); except end;end;function WinExecWithPipe(const CmdLine, Dir: string; var Output: string; var dwExitCode: Cardinal): Boolean; function WinExecWithPipe_(const CmdLine, Dir: string; slOutput: TStrings; var dwExitCode: Cardinal): Boolean; var HOutRead, HOutWrite: THandle; StartInfo: TStartupInfo; ProceInfo: TProcessInformation; sa: TSecurityAttributes; InStream: THandleStream; strTemp: string; PDir: PChar; procedure ReadLinesFromPipe(IsEnd: Boolean); var s: string; ls: TStringList; i: Integer; begin if InStream.Position < InStream.Size then begin SetLength(s, InStream.Size - InStream.Position); InStream.Read(PChar(s)^, InStream.Size - InStream.Position); strTemp := strTemp + s; ls := TStringList.Create; try ls.Text := strTemp; for i := 0 to ls.Count - 2 do slOutput.Add(ls); strTemp := ls[ls.Count - 1]; finally ls.Free; end; end; if IsEnd and (strTemp <> '') then begin slOutput.Add(strTemp); strTemp := ''; end; end; begin dwExitCode := 0; Result := False; try FillChar(sa, sizeof(sa), 0); sa.nLength := sizeof(sa); sa.bInheritHandle := True; sa.lpSecurityDescriptor := nil; InStream := nil; strTemp := ''; HOutRead := INVALID_HANDLE_VALUE; HOutWrite := INVALID_HANDLE_VALUE; try Win32Check(CreatePipe(HOutRead, HOutWrite, @sa, 0)); FillChar(StartInfo, SizeOf(StartInfo), 0); StartInfo.cb := SizeOf(StartInfo); StartInfo.wShowWindow := SW_HIDE; StartInfo.dwFlags := STARTF_USESTDHANDLES + STARTF_USESHOWWINDOW; StartInfo.hStdError := HOutWrite; StartInfo.hStdInput := GetStdHandle(STD_INPUT_HANDLE); StartInfo.hStdOutput := HOutWrite; InStream := THandleStream.Create(HOutRead); if Dir <> '' then PDir := PChar(Dir) else PDir := nil; Win32Check(CreateProcess(nil, //lpApplicationName: PChar PChar(CmdLine), //lpCommandLine: PChar nil, //lpProcessAttributes: PSecurityAttributes nil, //lpThreadAttributes: PSecurityAttributes True, //bInheritHandles: BOOL NORMAL_PRIORITY_CLASS, //CREATE_NEW_CONSOLE, nil, PDir, StartInfo, ProceInfo)); while WaitForSingleObject(ProceInfo.hProcess, 100) = WAIT_TIMEOUT do begin ReadLinesFromPipe(False); Application.ProcessMessages; //if Application.Terminated then break; end; ReadLinesFromPipe(True); GetExitCodeProcess(ProceInfo.hProcess, dwExitCode); CloseHandle(ProceInfo.hProcess); CloseHandle(ProceInfo.hThread); Result := True; finally if InStream <> nil then InStream.Free; if HOutRead <> INVALID_HANDLE_VALUE then CloseHandle(HOutRead); if HOutWrite <> INVALID_HANDLE_VALUE then CloseHandle(HOutWrite); end; except ; end; end;var slOutput: TStringList;begin slOutput := TStringList.Create; try Result := WinExecWithPipe_(CmdLine, Dir, slOutput, dwExitCode); Output := slOutput.Text; finally slOutput.Free; end;end;procedure TForm1.btn1Click(Sender: TObject);var FileName,dir: string; OutPut: string; ExitCode: Cardinal;begin FileName:='ipconfig'; WinExecWithPipe(FileName, dir, OutPut, ExitCode); mmo1.Text:=OutPut;end;end.
 
额,刚发现赠送了段写log文件的代码
 
谢谢这个老兄的代码,但还是无法实现我要的。我要是是再内存中加载CMD,并不是释放到硬盘后再运行,而是直接从资源文件中调用。也就是说 WinExecWithPipe(FileName, dir, OutPut, ExitCode);我的FileName不是一个文件名称,而是释放到内存中的文件,无法用FileName来定义的那种。帮我想想办法。再次谢谢
 
你释放到内存后怎么运行的呢?
 
我补上我内存中调用exe的完整代码第一部分:unit PEUnit;interfaceuses windows;function MemExecute(const ABuffer; Len: Integer; CmdParam: string; var ProcessId: Cardinal): Cardinal;implementation//{$R ExeShell.res} // 外壳程序模板(98下使用)typeTImageSectionHeaders = array [0..0] of TImageSectionHeader;PImageSectionHeaders = ^TImageSectionHeaders;{ 计算对齐后的大小 }function GetAlignedSize(Origin, Alignment: Cardinal): Cardinal;beginresult := (Origin + Alignment - 1) div Alignment * Alignment;end;{ 计算加载pe并对齐需要占用多少内存,未直接使用OptionalHeader.SizeOfImage作为结果是因为据说有的编译器生成的exe这个值会填0 }function CalcTotalImageSize(MzH: PImageDosHeader; FileLen: Cardinal; peH: PImageNtHeaders;peSecH: PImageSectionHeaders): Cardinal;vari: Integer;begin{计算pe头的大小}result := GetAlignedSize(PeH.OptionalHeader.SizeOfHeaders, PeH.OptionalHeader.SectionAlignment);{计算所有节的大小}for i := 0 to peH.FileHeader.NumberOfSections - 1 doif peSecH.PointerToRawData + peSecH.SizeOfRawData > FileLen then // 超出文件范围beginresult := 0;exit;endelse if peSecH.VirtualAddress <> 0 then //计算对齐后某节的大小if peSecH.Misc.VirtualSize <> 0 thenresult := GetAlignedSize(peSecH.VirtualAddress + peSecH.Misc.VirtualSize, PeH.OptionalHeader.SectionAlignment)elseresult := GetAlignedSize(peSecH.VirtualAddress + peSecH.SizeOfRawData, PeH.OptionalHeader.SectionAlignment)else if peSecH.Misc.VirtualSize < peSecH.SizeOfRawData thenresult := result + GetAlignedSize(peSecH.SizeOfRawData, peH.OptionalHeader.SectionAlignment)elseresult := result + GetAlignedSize(peSecH.Misc.VirtualSize, PeH.OptionalHeader.SectionAlignment);end;{ 加载pe到内存并对齐所有节 }function AlignPEToMem(const Buf; Len: Integer; var PeH: PImageNtHeaders;var PeSecH: PImageSectionHeaders; var Mem: Pointer; var ImageSize: Cardinal): Boolean;varSrcMz: PImageDosHeader; // DOS头SrcPeH: PImageNtHeaders; // PE头SrcPeSecH: PImageSectionHeaders; // 节表i: Integer;l: Cardinal;Pt: Pointer;beginresult := false;SrcMz := @Buf;if Len < sizeof(TImageDosHeader) then exit;if SrcMz.e_magic <> IMAGE_DOS_SIGNATURE then exit;if Len < SrcMz._lfanew+Sizeof(TImageNtHeaders) then exit;SrcPeH := pointer(Integer(SrcMz)+SrcMz._lfanew);if (SrcPeH.Signature <> IMAGE_NT_SIGNATURE) then exit;if (SrcPeH.FileHeader.Characteristics and IMAGE_FILE_DLL <> 0) or(SrcPeH.FileHeader.Characteristics and IMAGE_FILE_EXECUTABLE_IMAGE = 0)or (SrcPeH.FileHeader.SizeOfOptionalHeader <> SizeOf(TImageOptionalHeader)) then exit;SrcPeSecH := Pointer(Integer(SrcPeH)+SizeOf(TImageNtHeaders));ImageSize := CalcTotalImageSize(SrcMz, Len, SrcPeH, SrcPeSecH);if ImageSize = 0 thenexit;Mem := VirtualAlloc(nil, ImageSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // 分配内存if Mem <> nil thenbegin// 计算需要复制的PE头字节数l := SrcPeH.OptionalHeader.SizeOfHeaders;for i := 0 to SrcPeH.FileHeader.NumberOfSections - 1 doif (SrcPeSecH.PointerToRawData <> 0) and (SrcPeSecH.PointerToRawData < l) thenl := SrcPeSecH.PointerToRawData;Move(SrcMz^, Mem^, l);PeH := Pointer(Integer(Mem) + PImageDosHeader(Mem)._lfanew);PeSecH := Pointer(Integer(PeH) + sizeof(TImageNtHeaders));Pt := Pointer(Cardinal(Mem) + GetAlignedSize(PeH.OptionalHeader.SizeOfHeaders, PeH.OptionalHeader.SectionAlignment));for i := 0 to PeH.FileHeader.NumberOfSections - 1 dobegin// 定位该节在内存中的位置if PeSecH.VirtualAddress <> 0 thenPt := Pointer(Cardinal(Mem) + PeSecH.VirtualAddress);if PeSecH.SizeOfRawData <> 0 thenbegin// 复制数据到内存Move(Pointer(Cardinal(SrcMz) + PeSecH.PointerToRawData)^, pt^, PeSecH.SizeOfRawData);if peSecH.Misc.VirtualSize < peSecH.SizeOfRawData thenpt := pointer(Cardinal(pt) + GetAlignedSize(PeSecH.SizeOfRawData, PeH.OptionalHeader.SectionAlignment))elsept := pointer(Cardinal(pt) + GetAlignedSize(peSecH.Misc.VirtualSize, peH.OptionalHeader.SectionAlignment));// pt 定位到下一节开始位置endelsept := pointer(Cardinal(pt) + GetAlignedSize(PeSecH.Misc.VirtualSize, PeH.OptionalHeader.SectionAlignment));end;result := True;end;end;typeTVirtualAllocEx = function (hProcess: THandle; lpAddress: Pointer;dwSize, flAllocationType: DWORD; flProtect: DWORD): Pointer; stdcall;varMyVirtualAllocEx: TVirtualAllocEx = nil;function IsNT: Boolean;beginresult := Assigned(MyVirtualAllocEx);end;{ 生成外壳程序命令行 }function PrepareShellExe(CmdParam: string; BaseAddr, ImageSize: Cardinal): string;varr, h, sz: Cardinal;p: Pointer;fid, l: Integer;buf: Pointer;peH: PImageNtHeaders;peSecH: PImageSectionHeaders;beginif IsNT then{ NT 系统下直接使用自身程序作为外壳进程 }result := ParamStr(0)+CmdParamelse begin// 由于98系统下无法重新分配外壳进程占用内存,所以必须保证运行的外壳程序能容纳目标进程并且加载地址一致// 此处使用的方法是从资源中释放出一个事先建立好的外壳程序,然后通过修改其PE头使其运行时能加载到指定地址并至少能容纳目标进程r := FindResource(HInstance, 'SHELL_EXE', RT_RCDATA);h := LoadResource(HInstance, r);p := LockResource(h);l := SizeOfResource(HInstance, r);GetMem(Buf, l);Move(p^, Buf^, l); // 读到内存FreeResource(h);peH := Pointer(Integer(Buf) + PImageDosHeader(Buf)._lfanew);peSecH := Pointer(Integer(peH) + sizeof(TImageNtHeaders));peH.OptionalHeader.ImageBase := BaseAddr; // 修改PE头重的加载基址if peH.OptionalHeader.SizeOfImage < ImageSize then // 目标比外壳大,修改外壳程序运行时占用的内存beginsz := Imagesize - peH.OptionalHeader.SizeOfImage;Inc(peH.OptionalHeader.SizeOfImage, sz); // 调整总占用内存数Inc(peSecH[peH.FileHeader.NumberOfSections-1].Misc.VirtualSize, sz); // 调整最后一节占用内存数end;// 生成外壳程序文件名, 为本程序改后缀名得到的// 由于不想 uses SysUtils (一旦 use 了程序将增大80K左右), 而且偷懒,所以只支持最多运行11个进程,后缀名为.dat, .da0~.da9result := ParamStr(0);result := copy(result, 1, length(result) - 4) + '.dat';r := 0;while r < 10 dobeginfid := CreateFile(pchar(result), GENERIC_READ or GENERIC_WRITE, 0, nil, Create_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);if fid < 0 thenbeginresult := copy(result, 1, length(result)-3)+'da'+Char(r+Byte('0'));inc(r);endelse begin//SetFilePointer(fid, Imagesize, nil, 0);//SetEndOfFile(fid);//SetFilePointer(fid, 0, nil, 0);WriteFile(fid, Buf^, l, h, nil); // 写入文件CloseHandle(fid);break;end;end;result := result + CmdParam; // 生成命令行FreeMem(Buf);end;end;{ 是否包含可重定向列表 }function HasRelocationTable(peH: PImageNtHeaders): Boolean;beginresult := (peH.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress <> 0)and (peH.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size <> 0);end;typePImageBaseRelocation= ^TImageBaseRelocation;TImageBaseRelocation = packed recordVirtualAddress: cardinal;SizeOfBlock: cardinal;end;{ 重定向PE用到的地址 }procedure DoRelocation(peH: PImageNtHeaders; OldBase, NewBase: Pointer);varDelta: Cardinal;p: PImageBaseRelocation;pw: PWord;i: Integer;beginDelta := Cardinal(NewBase) - peH.OptionalHeader.ImageBase;p := pointer(cardinal(OldBase) + peH.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress);while (p.VirtualAddress + p.SizeOfBlock <> 0) dobeginpw := pointer(Integer(p) + Sizeof(p^));for i := 1 to (p.SizeOfBlock - Sizeof(p^)) div 2 dobeginif pw^ and $F000 = $3000 thenInc(PCardinal(Cardinal(OldBase) + p.VirtualAddress + (pw^ and $0FFF))^, Delta);inc(pw);end;p := Pointer(pw);end;end;typeTZwUnmapViewOfSection = function (Handle, BaseAdr: Cardinal): Cardinal; stdcall;{ 卸载原外壳占用内存 }function UnloadShell(ProcHnd, BaseAddr: Cardinal): Boolean;varM: HModule;ZwUnmapViewOfSection: TZwUnmapViewOfSection;beginresult := False;m := LoadLibrary('ntdll.dll');if m <> 0 thenbeginZwUnmapViewOfSection := GetProcAddress(m, 'ZwUnmapViewOfSection');if assigned(ZwUnmapViewOfSection) thenresult := (ZwUnmapViewOfSection(ProcHnd, BaseAddr) = 0);FreeLibrary(m);end;end;{ 创建外壳进程并获取其基址、大小和当前运行状态 }function CreateChild(Cmd: string; var Ctx: TContext; var ProcHnd, ThrdHnd, ProcId, BaseAddr, ImageSize: Cardinal): Boolean;varsi: TStartUpInfo;pi: TProcessInformation;Old: Cardinal;MemInfo: TMemoryBasicInformation;p: Pointer;beginFillChar(si, Sizeof(si), 0);FillChar(pi, SizeOf(pi), 0);si.cb := sizeof(si);result := CreateProcess(nil, PChar(Cmd), nil, nil, False, Create_SUSPENDED, nil, nil, si, pi); // 以挂起方式运行进程if result thenbeginProcHnd := pi.hProcess;ThrdHnd := pi.hThread;ProcId := pi.dwProcessId;{ 获取外壳进程运行状态,[ctx.Ebx+8]内存处存的是外壳进程的加载基址,ctx.Eax存放有外壳进程的入口地址 }ctx.ContextFlags := CONTEXT_FULL;GetThreadContext(ThrdHnd, ctx);ReadProcessMemory(ProcHnd, Pointer(ctx.Ebx+8), @BaseAddr, SizeOf(Cardinal), Old); // 读取加载基址p := Pointer(BaseAddr);{ 计算外壳进程占有的内存 }while VirtualQueryEx(ProcHnd, p, MemInfo, Sizeof(MemInfo)) <> 0 dobeginif MemInfo.State = MEM_FREE thenbreak;p := Pointer(Cardinal(p) + MemInfo.RegionSize);end;ImageSize := Cardinal(p) - Cardinal(BaseAddr);end;end;{ 创建外壳进程并用目标进程替换它然后执行 }function AttachPE(CmdParam: string; peH: PImageNtHeaders; peSecH: PImageSectionHeaders;Ptr: Pointer; ImageSize: Cardinal; var ProcId: Cardinal): Cardinal;vars: string;Addr, Size: Cardinal;ctx: TContext;Old: Cardinal;p: Pointer;Thrd: Cardinal;beginresult := INVALID_HANDLE_VALUE;s := PrepareShellExe(CmdParam, peH.OptionalHeader.ImageBase, ImageSize);if CreateChild(s, ctx, result, Thrd, ProcId, Addr, Size) thenbeginp := nil;if (peH.OptionalHeader.ImageBase = Addr) and (Size >= ImageSize) then // 外壳进程可以容纳目标进程并且加载地址一致beginp := Pointer(Addr);VirtualProtectEx(result, p, Size, PAGE_EXECUTE_READWRITE, Old);endelse if IsNT then // 98 下失败beginif UnloadShell(result, Addr) then // 卸载外壳进程占有内存// 重新按目标进程加载基址和大小分配内存p := MyVirtualAllocEx(Result, Pointer(peH.OptionalHeader.ImageBase), ImageSize, MEM_RESERVE or MEM_COMMIT, PAGE_EXECUTE_READWRITE);if (p = nil) and hasRelocationTable(peH) then // 分配内存失败并且目标进程支持重定向begin// 按任意基址分配内存p := MyVirtualAllocEx(result, nil, ImageSize, MEM_RESERVE or MEM_COMMIT, PAGE_EXECUTE_READWRITE);if p <> nil thenDoRelocation(peH, Ptr, p); // 重定向end;end;if p <> nil thenbeginWriteProcessMemory(Result, Pointer(ctx.Ebx+8), @p, Sizeof(DWORD), Old); // 重置目标进程运行环境中的基址peH.OptionalHeader.ImageBase := Cardinal(p);if WriteProcessMemory(Result, p, Ptr, ImageSize, Old) then // 复制PE数据到目标进程beginctx.ContextFlags := CONTEXT_FULL;if Cardinal(p) = Addr thenctx.Eax := peH.OptionalHeader.ImageBase + peH.OptionalHeader.AddressOfEntryPoint // 重置运行环境中的入口地址elsectx.Eax := Cardinal(p) + peH.OptionalHeader.AddressOfEntryPoint;SetThreadContext(Thrd, ctx); // 更新运行环境ResumeThread(Thrd); // 执行CloseHandle(Thrd);endelse begin // 加载失败,杀掉外壳进程TerminateProcess(Result, 0);CloseHandle(Thrd);CloseHandle(Result);Result := INVALID_HANDLE_VALUE;end;endelse begin // 加载失败,杀掉外壳进程TerminateProcess(Result, 0);CloseHandle(Thrd);CloseHandle(Result);Result := INVALID_HANDLE_VALUE;end;end;end;function MemExecute(const ABuffer; Len: Integer; CmdParam: string; var ProcessId: Cardinal): Cardinal;varpeH: PImageNtHeaders;peSecH: PImageSectionHeaders;Ptr: Pointer;peSz: Cardinal;beginresult := INVALID_HANDLE_VALUE;if alignPEToMem(ABuffer, Len, peH, peSecH, Ptr, peSz) then beginresult := AttachPE(CmdParam, peH, peSecH, Ptr, peSz, ProcessId);VirtualFree(Ptr, peSz, MEM_DECOMMIT);//VirtualFree(Ptr, 0, MEM_RELEASE);end;end;initializationMyVirtualAllocEx := GetProcAddress(GetModuleHandle('Kernel32.dll'), 'VirtualAllocEx');end.-----------------------------------------------------------实例:{$R jiami.RES}uses PEUnit;procedure TForm1.Button1Click(Sender: TObject);varABuffer: array of byte;Stream: TResourceStream;ProcessId: Cardinal;beginStream:=TResourceStream.Create(hinstance,'jiami','exefile');trySetLength(ABuffer, Stream.Size);Stream.ReadBuffer(ABuffer[0], Stream.Size);MemExecute(ABuffer[0], Stream.Size, ' 12345', ProcessId);finallyStream.Free;end;end;如果是win32的exe程序,运行正常,但DOS下的exe,会一闪而过,得不到返回信息。
 
Win32Check(CreateProcess(nil, //lpApplicationName: PChar PChar(CmdLine), //lpCommandLine: PChar nil, //lpProcessAttributes: PSecurityAttributes nil, //lpThreadAttributes: PSecurityAttributes True, //bInheritHandles: BOOL NORMAL_PRIORITY_CLASS, //CREATE_NEW_CONSOLE, nil, PDir, StartInfo, ProceInfo));///把这地方改成你要运行的内存程序应该就可以的 Win32Check(VirtualProtectEx()) 你试下这样
 
如果能给我个完整的例子我追加800分,把我全部的分数都给你,可以另开贴送分。这个问题已经困扰我很久了。
 
DOS 有个管道技术 dir >t.txt 结果就存到1.txt中了,这个 1.txt 可以是任何设备
 
1.txt 可以是任何设备 ???不明白,不写硬盘可以得到 1.txt中的内容?
 
用pipe可以实现你的要求就是接管控制台的输出,然后你从pipe中读取到console程序的输出信息查一下本论坛吧,我都贴过好多次代码的了。
 
我的要求有点特殊,用管道可以实现获取CMD的返回值,我的问题关键是 我的CMD批处理文件是内置于软件资源文件中的,直接从资源文件中读取CMD到内存,然后运行,整个过程不写硬盘!希望高手们帮帮我,我可以追加我所有的分数,谢谢了。
 
转一个 执行控制台程序并且获得它的输出结果 procedure CheckResult(b: Boolean); begin if not b then Raise Exception.Create(SysErrorMessage(GetLastError)); end; function RunDOS(const Prog, CommandLine,Dir: String;var ExitCode:DWORD): String; var HRead,HWrite:THandle; StartInfo:TStartupInfo; ProceInfo:TProcessInformation; b:Boolean; sa:TSecurityAttributes; inS:THandleStream; sRet:TStrings; begin Result := ''; FillChar(sa,sizeof(sa),0); //设置允许继承,否则在NT和2000下无法取得输出结果 sa.nLength := sizeof(sa); sa.bInheritHandle := True; sa.lpSecurityDescriptor := nil; b := CreatePipe(HRead,HWrite,@sa,0); CheckResult(b); FillChar(StartInfo,SizeOf(StartInfo),0); StartInfo.cb := SizeOf(StartInfo); StartInfo.wShowWindow := SW_HIDE; //使用指定的句柄作为标准输入输出的文件句柄,使用指定的显示方式 StartInfo.dwFlags := STARTF_USESTDHANDLES+STARTF_USESHOWWINDOW; StartInfo.hStdError := HWrite; StartInfo.hStdInput := GetStdHandle(STD_INPUT_HANDLE);//HRead; StartInfo.hStdOutput := HWrite; b := CreateProcess(PChar(Prog),//lpApplicationName: PChar PChar(CommandLine), //lpCommandLine: PChar nil, //lpProcessAttributes: PSecurityAttributes nil, //lpThreadAttributes: PSecurityAttributes True, //bInheritHandles: BOOL CREATE_NEW_CONSOLE, nil, PChar(Dir), StartInfo, ProceInfo ); CheckResult(b); WaitForSingleObject(ProceInfo.hProcess,INFINITE); GetExitCodeProcess(ProceInfo.hProcess,ExitCode); inS := THandleStream.Create(HRead); if inS.Size>0 then begin sRet := TStringList.Create; sRet.LoadFromStream(inS); Result := sRet.Text; sRet.Free; end; inS.Free; CloseHandle(HRead); CloseHandle(HWrite); end; ******************* function GetDosOutput(const CommandLine:string): string; var SA: TSecurityAttributes; SI: TStartupInfo; PI: TProcessInformation; StdOutPipeRead, StdOutPipeWrite: THandle; WasOK: Boolean; Buffer: array[0..255] of Char; BytesRead: Cardinal; WorkDir, Line: String; begin Application.ProcessMessages; with SA do begin nLength := SizeOf(SA); bInheritHandle := True; lpSecurityDescriptor := nil; end; // create pipe for standard output redirection CreatePipe(StdOutPipeRead, // read handle StdOutPipeWrite, // write handle @SA, // security attributes 0 // number of bytes reserved for pipe - 0 default ); try // Make child process use StdOutPipeWrite as standard out, // and make sure it does not show on screen. with SI do begin FillChar(SI, SizeOf(SI), 0); cb := SizeOf(SI); dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; wShowWindow := SW_HIDE; hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdinput hStdOutput := StdOutPipeWrite; hStdError := StdOutPipeWrite; end; // launch the command line compiler WorkDir := ExtractFilePath(CommandLine); WasOK := CreateProcess(nil, PChar(CommandLine), nil, nil, True, 0, nil, PChar(WorkDir), SI, PI);   // Now that the handle has been inherited, close write to be safe. // We don't want to read or write to it accidentally. CloseHandle(StdOutPipeWrite); // if process could be created then handle its output if not WasOK then raise Exception.Create('Could not execute command line!') else try // get all output until dos app finishes Line := ''; repeat // read block of characters (might contain carriage returns and line feeds) WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil); // has anything been read? if BytesRead > 0 then begin // finish buffer to PChar Buffer[BytesRead] := #0; // combine the buffer with the rest of the last run Line := Line + Buffer; end; until not WasOK or (BytesRead = 0); // wait for console app to finish (should be already at this point) WaitForSingleObject(PI.hProcess, INFINITE); finally // Close all remaining handles CloseHandle(PI.hThread); CloseHandle(PI.hProcess); end; finally result:=Line; CloseHandle(StdOutPipeRead); end; end; ------------------------------------------------------------------------------------- unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Memo1: TMemo; OpenDialog1: TOpenDialog; btnRUn: TButton; btnOpenFIle: TButton; btnEditFile: TButton; editfilename: TEdit; procedure btnOpenfileClick(Sender: TObject); procedure btnRunClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.btnOpenfileClick(Sender: TObject); begin if opendialog1.Execute then editfilename.Text := opendialog1.FileName; end; procedure TForm1.btnRunClick(Sender: TObject); var hReadPipe, hWritePipe: THandle; si: STARTUPINFO; lsa: SECURITY_ATTRIBUTES; pi: PROCESS_INFORMATION; mDosScreen: string; cchReadBuffer: DWORD; ph: PChar; fname: PChar; i, j: integer; begin fname := allocmem(255); ph := AllocMem(5000); lsa.nLength := sizeof(SECURITY_ATTRIBUTES); lsa.lpSecurityDescriptor := nil; lsa.bInheritHandle := True; if CreatePipe(hReadPipe, hWritePipe, @lsa, 0) = false then begin ShowMessage('Can not create pipe!'); exit; end; fillchar(si, sizeof(STARTUPINFO), 0); si.cb := sizeof(STARTUPINFO); si.dwFlags := (STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW); si.wShowWindow := SW_SHOW; si.hStdOutput := hWritePipe; StrPCopy(fname, EditFilename.text); if CreateProcess(nil, fname, nil, nil, true, 0, nil, nil, si, pi) = False then begin ShowMessage('can not create process'); FreeMem(ph); FreeMem(fname); Exit; end; while (true) do begin if not PeekNamedPipe(hReadPipe, ph, 1, @cchReadBuffer, nil, nil) then break; if cchReadBuffer <> 0 then begin if ReadFile(hReadPipe, ph^, 4096, cchReadBuffer, nil) = false then break; ph[cchReadbuffer] := chr(0); Memo1.Lines.Add(ph); end else if (WaitForSingleObject(pi.hProcess, 0) = WAIT_OBJECT_0) then break; Sleep(100); end; ph[cchReadBuffer] := chr(0); Memo1.Lines.Add(ph); CloseHandle(hReadPipe); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); CloseHandle(hWritePipe); FreeMem(ph); FreeMem(fname); end; end. --------------------------------------------------------------- shellexecute('dir * >>a.txt');
 
我要的是内存中加载cmd,不是从具体的文件,是把cmd放进资源文件,然后释放到内存加载。
 
后退
顶部