import_meth=1;
Start(false);
bCreateProcess=GetProcAddress("kernel32.dll","CreateProcessInternalW");
AddBreak(bCreateProcess,1,0);
EnableBreak(bCreateProcess);
while true do
	Continue(true);
	if break_where==bCreateProcess then
		break;
	elseif break_where==0xf00 then
		WriteEx("Damn, process died :(",true,true,0x0000ff);
		return -1;
	end;
end;
suspended=ReadMem(ESP+0x1c,4);
if (suspended & 4)==0 then
	WriteMem(ESP+0x1c,suspended | 4,4);
end;
bReturn=ReadMem(ESP,4);
ProcInfo=ReadMem(ESP+44,4);
AddBreak(bReturn,1,0);
EnableBreak(bReturn);
while true do
	Continue(true);
	if break_where==bReturn then
		break;
	elseif break_where==0xf00 then
		WriteEx("Damn, process died :(",true,true,0x0000ff);
		return -1;
	end;
end;
pid=ReadMem(ProcInfo+8,4);
tid=ReadMem(ProcInfo+12,4);
WriteLog(string.format("Got new pid=0x%.04X and tid=0x%.04X",pid,tid));



--bUnmap=GetProcAddress("ntdll.dll","ZwUnmapViewOfSection");
--AddBreak(bUnmap,1,0); EnableBreak(bUnmap);
--while true do
--	Continue(true);
--	if break_where==bUnmap then
--		break;
--	elseif break_where==0xf00 then
--		WriteEx("Damn, process died :(",true,true,0x0000ff);
--		return -1;
--	end;
--end;
--WriteLog("Section is about to be unmapped");



bVAlloc=GetProcAddress("ntdll.dll","ZwAllocateVirtualMemory");
AddBreak(bVAlloc,1,0);
EnableBreak(bVAlloc);
while true do
	Continue(true);
	if break_where==bVAlloc then
		if ReadMem(ESP+4,4)~=0xffffffff then
			break;
		end;
		TraceAndReplace(bVAlloc);
	elseif break_where==0xf00 then
		WriteEx("Damn, process died :(",true,true,0x0000ff);
		return -1;
	end;
end;
imagesize=ReadMem(ReadMem(ESP+16,4),4);
victimbase=ReadMem(ReadMem(ESP+8,4),4);
WriteLog(string.format("Got new base=0x%08X and size=0x%08X",victimbase,imagesize));
bSetContext=GetProcAddress("ntdll.dll","ZwSetContextThread");
AddBreak(bSetContext,1,0);
EnableBreak(bSetContext);
while true do
	Continue(true);
	if break_where==bSetContext then
		break;
	elseif break_where==0xf00 then
		WriteEx("Damn, process died :(",true,true,0x0000ff);
		return -1;
	end;
end;
temp=ReadMem(ESP+8,4);
jmp_to_oep=ReadMem(temp+0xb0,4)-victimbase;
WriteLog(string.format("Got new OEP=0x%08X",jmp_to_oep));
bResumeThread=GetProcAddress("ntdll.dll","ZwResumeThread");
AddBreak(bResumeThread,1,0);
EnableBreak(bResumeThread);
while true do
	Continue(true);
	if break_where==bResumeThread then
		break;
	elseif break_where==0xf00 then
		WriteEx("Damn, process died :(",true,true,0x0000ff);
		return -1;
	end;
end;
oldpid=victim_id;
oldtid=thread_id;
victim_base=victimbase;
WriteLog("Ready to attach");
if (suspended & 4)~=0 then
	local temp=thread_id;
	thread_id=ReadMem(ProcInfo+12,4);
	Suspend();
	thread_id=temp;
end;
AttachFast(pid,tid);
image_size=imagesize;
Dump();
if cut_sections==true then
	ProcessResources();
	CutSections();
	ProcessExport();
	ProcessTLS();
end;
RestoreImportRelocs();
if cut_sections==true then
	SaveResources();
end;
SaveFile();
Terminate();
AttachFast(oldpid,oldtid);
Terminate();