[英]How can I execute code directly from memory in delphi?
Is it possible to mimic the loadlibrary
function? 是否可以模仿loadlibrary
函数? I want to load a library from a BLOB field without first writing it to a temporary file, and I need a solution which is not dependent on specific version of delphi compiler or windows, and does not trigger antivirus software. 我想从BLOB字段加载一个库而不先将其写入临时文件,我需要一个不依赖于特定版本的delphi编译器或Windows的解决方案,并且不会触发防病毒软件。
Yes you can, and you need not loadlibrary
to execute a code from memory - you need to allocate a memory using VirtualAlloc function with PAGE_EXECUTE flag set 是的,你可以,你不需要loadlibrary
来从内存执行代码 - 你需要使用VirtualAlloc函数分配一个内存,并设置PAGE_EXECUTE标志
Update: here is a quick and dirty demo of the code executed from memory for 32-bit Delphi - I only tested that it works: 更新:这是一个快速而肮脏的演示代码,从32位Delphi的内存执行 - 我只测试它的工作原理:
type
TIncMe = procedure(var I: Integer);
var
IncMeProc: TIncMe;
procedure IncMe(var I: Integer);
begin
Inc(I);
end;
procedure CopyIncMe;
var
Size: LongWord;
Tmp: Pointer;
begin
Size:= LongWord(@CopyIncMe) - LongWord(@IncMe);
Tmp:= VirtualAlloc(nil, Size, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE);
Move(Pointer(@IncMe)^, Tmp^, Size);
IncMeProc:= Tmp;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
J: Integer;
begin
J:= 0;
CopyIncMe;
while J < 10 do begin
IncMeProc(J);
ShowMessage(IntToStr(J));
end;
VirtualFree(@IncMeProc, 0, MEM_RELEASE);
end;
dzlib contains a ready made object for reading a dll from a resource into memory and using it without ever saving it to disc: dzlib包含一个现成的对象,用于将资源从资源读入内存并使用它而无需将其保存到光盘:
This is the main file ... 这是主要档案......
http://sourceforge.net/p/dzlib/code/147/tree/dzlib/trunk/src/u_dzResourceDllLoader.pas http://sourceforge.net/p/dzlib/code/147/tree/dzlib/trunk/src/u_dzResourceDllLoader.pas
.. but it needs other files from the same repository. ..但它需要来自同一存储库的其他文件。
There's an article on delphi.about.com , that shows how to load a dll from a resource. 有一篇关于delphi.about.com的文章,展示了如何从资源加载dll。
It first loads the resource into memory, and then loads the dll from the resource using Memory Module 它首先将资源加载到内存中,然后使用内存模块从资源加载dll
Instead of a resource, you can use a database or whatever source you want to load the dll from. 您可以使用数据库或任何要从中加载dll的源代替资源。 Once it is in a memory stream, you can use the following code to load and execute the dll functions, which looks very much like 'normal' code to invoke a dll: 一旦它在内存流中,您可以使用以下代码加载和执行dll函数,这看起来非常像调用dll的“普通”代码:
var
btMM: PBTMemoryModule;
begin
btMM := BTMemoryLoadLibary(mp_DllData, m_DllDataSize);
try
if btMM = nil then Abort;
@m_TestCallstd := BTMemoryGetProcAddress(btMM, 'TestCallstd');
if @m_TestCallstd = nil then Abort;
m_TestCallstd('This is a Dll Memory call!');
except
Showmessage('An error occoured while loading the dll: ' + BTMemoryGetLastError);
end;
if Assigned(btMM) then BTMemoryFreeLibrary(btMM);
end;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.