Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

BinRun() - Run binary executable from Memory (e.g. Resource)


  • Please log in to reply
39 replies to this topic
HotKeyIt
  • Moderators
  • 7439 posts
  • Last active: Jun 22 2016 09:14 PM
  • Joined: 18 Jun 2008

Above requires AHK_H, original BinRun does not.

 

With AHK_H you can use internal Struct() function instead of _Struct class, also you can save the pData internally, no need for Clip2Object.

We also don't need the BinRun Class anymore since all struct data can be declared static.

 

! AutoHotkey_H version !

BinRun(pData,cmdLine="",cmdLineScript="",ExeToUse="",Title=""){
  static IMAGE_NT_SIGNATURE:=17744,IMAGE_DOS_SIGNATURE:=23117,PAGE_EXECUTE_READWRITE:=64,CREATE_SUSPENDED:=4
  static MEM_COMMIT:=4096,MEM_RESERVE:=8192
  static KeepExeInMem:=[]
  static IMAGE_DOS_HEADER :="
  (
    WORD   e_magic;                     // Magic number
    WORD   e_cblp;                      // Bytes on last page of file
    WORD   e_cp;                        // Pages in file
    WORD   e_crlc;                      // Relocations
    WORD   e_cparhdr;                   // Size of header in paragraphs
    WORD   e_minalloc;                  // Minimum extra paragraphs needed
    WORD   e_maxalloc;                  // Maximum extra paragraphs needed
    WORD   e_ss;                        // Initial (relative) SS value
    WORD   e_sp;                        // Initial SP value
    WORD   e_csum;                      // Checksum
    WORD   e_ip;                        // Initial IP value
    WORD   e_cs;                        // Initial (relative) CS value
    WORD   e_lfarlc;                    // File address of relocation table
    WORD   e_ovno;                      // Overlay number
    WORD   e_res[4];                    // Reserved words
    WORD   e_oemid;                     // OEM identifier (for e_oeminfo)
    WORD   e_oeminfo;                   // OEM information; e_oemid specific
    WORD   e_res2[10];                  // Reserved words
    LONG   e_lfanew;                    // File address of new exe header
  )"
  ,IMAGE_FILE_HEADER :="
  (
    WORD    Machine;
    WORD    NumberOfSections;
    DWORD   TimeDateStamp;
    DWORD   PointerToSymbolTable;
    DWORD   NumberOfSymbols;
    WORD    SizeOfOptionalHeader;
    WORD    Characteristics;
  )"
  ,IMAGE_DATA_DIRECTORY :="
  (
    DWORD   VirtualAddress;
    DWORD   Size;
  )"
  ,IMAGE_OPTIONAL_HEADER64:="
  (
    WORD        Magic;
    BYTE        MajorLinkerVersion;
    BYTE        MinorLinkerVersion;
    DWORD       SizeOfCode;
    DWORD       SizeOfInitializedData;
    DWORD       SizeOfUninitializedData;
    DWORD       AddressOfEntryPoint;
    DWORD       BaseOfCode;
    ULONGLONG   ImageBase;
    DWORD       SectionAlignment;
    DWORD       FileAlignment;
    WORD        MajorOperatingSystemVersion;
    WORD        MinorOperatingSystemVersion;
    WORD        MajorImageVersion;
    WORD        MinorImageVersion;
    WORD        MajorSubsystemVersion;
    WORD        MinorSubsystemVersion;
    DWORD       Win32VersionValue;
    DWORD       SizeOfImage;
    DWORD       SizeOfHeaders;
    DWORD       CheckSum;
    WORD        Subsystem;
    WORD        DllCharacteristics;
    ULONGLONG   SizeOfStackReserve;
    ULONGLONG   SizeOfStackCommit;
    ULONGLONG   SizeOfHeapReserve;
    ULONGLONG   SizeOfHeapCommit;
    DWORD       LoaderFlags;
    DWORD       NumberOfRvaAndSizes;
    BinRun(IMAGE_DATA_DIRECTORY) DataDirectory[16]; // IMAGE_NUMBEROF_DIRECTORY_ENTRIES
  )"
  ,IMAGE_OPTIONAL_HEADER32 :="
  (
    WORD    Magic;
    BYTE    MajorLinkerVersion;
    BYTE    MinorLinkerVersion;
    DWORD   SizeOfCode;
    DWORD   SizeOfInitializedData;
    DWORD   SizeOfUninitializedData;
    DWORD   AddressOfEntryPoint;
    DWORD   BaseOfCode;
    DWORD   BaseOfData;
    DWORD   ImageBase;
    DWORD   SectionAlignment;
    DWORD   FileAlignment;
    WORD    MajorOperatingSystemVersion;
    WORD    MinorOperatingSystemVersion;
    WORD    MajorImageVersion;
    WORD    MinorImageVersion;
    WORD    MajorSubsystemVersion;
    WORD    MinorSubsystemVersion;
    DWORD   Win32VersionValue;
    DWORD   SizeOfImage;
    DWORD   SizeOfHeaders;
    DWORD   CheckSum;
    WORD    Subsystem;
    WORD    DllCharacteristics;
    DWORD   SizeOfStackReserve;
    DWORD   SizeOfStackCommit;
    DWORD   SizeOfHeapReserve;
    DWORD   SizeOfHeapCommit;
    DWORD   LoaderFlags;
    DWORD   NumberOfRvaAndSizes;
    BinRun(IMAGE_DATA_DIRECTORY) DataDirectory[16]; //IMAGE_NUMBEROF_DIRECTORY_ENTRIES
  )"
  ,IMAGE_NT_HEADERS:="
  (
    DWORD Signature;
    BinRun(IMAGE_FILE_HEADER) FileHeader;
    BinRun(IMAGE_OPTIONAL_HEADER" (A_PtrSize=8?64:32) ") OptionalHeader;
  )"
  ,IMAGE_NT_HEADERS32:="
  (
    DWORD Signature;
    BinRun(IMAGE_FILE_HEADER) FileHeader;
    BinRun(IMAGE_OPTIONAL_HEADER32) OptionalHeader;
  )"
  ,IMAGE_NT_HEADERS64:="
  (
    DWORD Signature;
    BinRun(IMAGE_FILE_HEADER) FileHeader;
    BinRun(IMAGE_OPTIONAL_HEADER64) OptionalHeader;
  )"
  ,IMAGE_SECTION_HEADER:="
  (
    BYTE    Name[8];
    union {
        DWORD   PhysicalAddress;
        DWORD   VirtualSize;
    };
    DWORD   VirtualAddress;
    DWORD   SizeOfRawData;
    DWORD   PointerToRawData;
    DWORD   PointerToRelocations;
    DWORD   PointerToLinenumbers;
    WORD    NumberOfRelocations;
    WORD    NumberOfLinenumbers;
    DWORD   Characteristics;
  )"
  ,FLOATING_SAVE_AREA :="
  (
    DWORD   ControlWord;
    DWORD   StatusWord;
    DWORD   TagWord;
    DWORD   ErrorOffset;
    DWORD   ErrorSelector;
    DWORD   DataOffset;
    DWORD   DataSelector;
    BYTE    RegisterArea[80]; //SIZE_OF_80387_REGISTERS
    DWORD   Cr0NpxState;
  )"
  ,PROCESS_INFORMATION :="
  (
    HANDLE hProcess;
    HANDLE hThread;
    DWORD  dwProcessId;
    DWORD  dwThreadId;
  )"
  ,STARTUPINFO :="
  (
    DWORD  cb;
    LPTSTR lpReserved;
    LPTSTR lpDesktop;
    LPTSTR lpTitle;
    DWORD  dwX;
    DWORD  dwY;
    DWORD  dwXSize;
    DWORD  dwYSize;
    DWORD  dwXCountChars;
    DWORD  dwYCountChars;
    DWORD  dwFillAttribute;
    DWORD  dwFlags;
    WORD   wShowWindow;
    WORD   cbReserved2;
    LPBYTE lpReserved2;
    HANDLE hStdInput;
    HANDLE hStdOutput;
    HANDLE hStdError;
  )"
  ,M128A:="ULONGLONG Low;LONGLONG High"
  ,_XMM_SAVE_AREA32 :="
  (
      WORD ControlWord;
      WORD StatusWord;
      BYTE TagWord;
      BYTE Reserved1;
      WORD ErrorOpcode;
      DWORD ErrorOffset;
      WORD ErrorSelector;
      WORD Reserved2;
      DWORD DataOffset;
      WORD DataSelector;
      WORD Reserved3;
      DWORD MxCsr;
      DWORD MxCsr_Mask;
      BinRun(M128A) FloatRegisters[8];
      BinRun(M128A) XmmRegisters[16];
      BYTE Reserved4[96];
  )"
  ,CONTEXT64:="
  (
      DWORD64 P1Home;
      DWORD64 P2Home;
      DWORD64 P3Home;
      DWORD64 P4Home;
      DWORD64 P5Home;
      DWORD64 P6Home;
      DWORD ContextFlags;
      DWORD MxCsr;
      WORD SegCs;      
      WORD SegDs;      
      WORD SegEs;      
      WORD SegFs;      
      WORD SegGs;      
      WORD SegSs;      
      DWORD EFlags;    
      DWORD64 Dr0;     
      DWORD64 Dr1;     
      DWORD64 Dr2;     
      DWORD64 Dr3;     
      DWORD64 Dr6;     
      DWORD64 Dr7;     
      DWORD64 Rax;     
      DWORD64 Rcx;     
      DWORD64 Rdx;     
      DWORD64 Rbx;     
      DWORD64 Rsp;     
      DWORD64 Rbp;     
      DWORD64 Rsi;     
      DWORD64 Rdi;     
      DWORD64 R8;      
      DWORD64 R9;      
      DWORD64 R10;     
      DWORD64 R11;     
      DWORD64 R12;     
      DWORD64 R13;     
      DWORD64 R14;     
      DWORD64 R15;     
      DWORD64 Rip;     
      union {
          BinRun(_XMM_SAVE_AREA32) FltSave; 
          struct {
              BinRun(M128A) Header[2];     
              BinRun(M128A) Legacy[8];     
              BinRun(M128A) Xmm0;          
              BinRun(M128A) Xmm1;          
              BinRun(M128A) Xmm2;          
              BinRun(M128A) Xmm3;          
              BinRun(M128A) Xmm4;          
              BinRun(M128A) Xmm5;          
              BinRun(M128A) Xmm6;          
              BinRun(M128A) Xmm7;          
              BinRun(M128A) Xmm8;          
              BinRun(M128A) Xmm9;          
              BinRun(M128A) Xmm10;         
              BinRun(M128A) Xmm11;         
              BinRun(M128A) Xmm12;         
              BinRun(M128A) Xmm13;         
              BinRun(M128A) Xmm14;         
              BinRun(M128A) Xmm15;         
          };
      };
      BinRun(M128A) VectorRegister[26];    
      DWORD64 VectorControl;       
      DWORD64 DebugControl;        
      DWORD64 LastBranchToRip;     
      DWORD64 LastBranchFromRip;   
      DWORD64 LastExceptionToRip;  
      DWORD64 LastExceptionFromRip;
  )"
  ,CONTEXT32:="
  (
    DWORD ContextFlags;
    DWORD   Dr0;
    DWORD   Dr1;
    DWORD   Dr2;
    DWORD   Dr3;
    DWORD   Dr6;
    DWORD   Dr7;
    BinRun(FLOATING_SAVE_AREA) FloatSave;
    DWORD   SegGs;
    DWORD   SegFs;
    DWORD   SegEs;
    DWORD   SegDs;
    DWORD   Edi;
    DWORD   Esi;
    DWORD   Ebx;
    DWORD   Edx;
    DWORD   Ecx;
    DWORD   Eax;
    DWORD   Ebp;
    DWORD   Eip;
    DWORD   SegCs;              // MUST BE SANITIZED
    DWORD   EFlags;             // MUST BE SANITIZED
    DWORD   Esp;
    DWORD   SegSs;
    BYTE    ExtendedRegisters[512]; // MAXIMUM_SUPPORTED_EXTENSION
  )"  
  ,IDH:=Struct(IMAGE_DOS_HEADER),INH := Struct(IMAGE_NT_HEADERS),pi:=Struct(PROCESS_INFORMATION),si:=Struct(STARTUPINFO,{cb:sizeof(STARTUPINFO)})
	If pData
	{
		If KeepExeInMem[pData] {
			pData:=KeepExeInMem.GetAddress(pData)
		}	else if (pData+0=""){	
				If res := DllCall("FindResource","PTR",lib:=DllCall("GetModuleHandle","PTR",0,"PTR"),"Str",pData,"PTR",10,"PTR")
            KeepExeInMem.SetCapacity(pData,sz :=DllCall("SizeofResource","PTR",lib,"PTR",res))
						,DllCall("RtlMoveMemory","PTR",pData:=KeepExeInMem.GetAddress(pData),"PTR"
                    ,DllCall("LockResource","PTR",hres:=DllCall("LoadResource","PTR",lib,"PTR",res,"PTR"),"PTR"),"PTR",sz)
						,DllCall("FreeResource","PTR",hres),BinRun_Uncompress(data)
			else {
				FileGetSize,sz,%pData%
				FileRead,Data,*c %pData%
        KeepExeInMem.SetCapacity(pData,sz)
        ,DllCall("RtlMoveMemory","PTR",pData:=KeepExeInMem.GetAddress(pData),"PTR",&data,"PTR",sz)
      }
		}
    if !pData
      return false
	}

  If InStr(cmdLine,"`n"){
    PipeName := "\\.\pipe\" (Title ? Title : "AHK" A_TickCount)
    __PIPE_GA_ := DllCall("CreateNamedPipe","str",PipeName,"UInt",2,"UInt",0,"UInt",255,"UInt",0,"UInt",0,"PTR",0,"PTR",0)
    ,__PIPE_    := DllCall("CreateNamedPipe","str",PipeName,"UInt",2,"UInt",0,"UInt",255,"UInt",0,"UInt",0,"PTR",0,"PTR",0)
    if (__PIPE_=-1 or __PIPE_GA_=-1)
      Return 0
    Script:=(A_IsUnicode ? chr(0xfeff) : (chr(239) . chr(187) . chr(191))) SubStr(cmdLine,InStr(cmdLine,"`n")+1)
    ,cmdLine:=Trim(SubStr(cmdLine,1,InStr(cmdLine,"`n")),"`n`r") A_Space PipeName
  }

  IDH[]:=pData
  if (IDH.e_magic != IMAGE_DOS_SIGNATURE){
    MsgBox ERROR: e_magic not found
    return
  }
  INH[] := pData + IDH.e_lfanew
  
  if (INH.Signature != IMAGE_NT_SIGNATURE){
    MsgBox ERROR: Signature not found
    return
  }

  
  If (A_PtrSize=8&&INH.OptionalHeader.magic=267) ; x86 on x64
    pNtHeader:=Struct(IMAGE_NT_HEADERS32,pData + IDH.e_lfanew),ctx:=Struct(Context32),Force32Bit:=1
    ,ctx.ContextFlags := (A_PtrSize=8?0x100000:0x10000) | 0x2 ;CONTEXT_INTEGER
    ,UsedExe:=ExeToUse?ExeToUse:A_WinDir "\Microsoft.NET\Framework\v2.0.50727\vbc.exe"
  else if (A_PtrSize=4&&INH.OptionalHeader.magic=523) ; x64 on x86 not possible
    Return false
  else 
    pNtHeader:=INH,UsedExe:=ExeToUse?ExeToUse:A_IsCompiled?A_ScriptFullPath:A_AhkPath
    ,ctx:=Struct(A_PtrSize=8?Context64:Context32),ctx.ContextFlags := (A_PtrSize=8?0x100000:0x10000) | 0x2 ;CONTEXT_INTEGER
  if DllCall("CreateProcess","PTR",0,"STR","""" UsedExe """" A_Space cmdLine (cmdLineScript?A_Space cmdLineScript:"")
            ,"PTR",0,"PTR",0,"int",0,"Int",CREATE_SUSPENDED,"PTR",0,"PTR",0,"PTR",si[],"PTR",pi[]){
      if DllCall((Force32Bit?"Wow64":"") "GetThreadContext","PTR",pi.hThread,"PTR", ctx[]){
          pPebImageBase:=ctx[A_PtrSize=8&&!Force32Bit?"Rdx":"Ebx"] + (Force32Bit?4:A_PtrSize)*2
          if DllCall("ReadProcessMemory","PTR",pi.hProcess, "PTR", pPebImageBase,"PTR*", dwImagebase,"PTR", (Force32Bit?4:A_PtrSize),"Uint*",NumberOfBytes){
              DllCall("ntdll\NtUnmapViewOfSection","PTR",pi.hProcess, "PTR",dwImagebase)
              pImagebase := DllCall("VirtualAllocEx","PTR",pi.hProcess, "PTR",pNtHeader.OptionalHeader.ImageBase, "PTR",pNtHeader.OptionalHeader.SizeOfImage,"UInt", MEM_COMMIT|MEM_RESERVE,"UInt", PAGE_EXECUTE_READWRITE,"PTR")
              if (pImagebase)
              {
                  if DllCall("WriteProcessMemory","PTR",pi.hProcess,"PTR",pImagebase,"PTR",pData,"PTR",pNtHeader.OptionalHeader.SizeOfHeaders,"UInt*",NumberOfBytes){
                      pSecHeader :=Struct(IMAGE_SECTION_HEADER)
                      pSecHeader[] :=pNtHeader.OptionalHeader[""]+pNtHeader.FileHeader.SizeOfOptionalHeader
                      counter := 0
                      while (++counter < pNtHeader.FileHeader.NumberOfSections+1){
                          DllCall("WriteProcessMemory","PTR",pi.hProcess,"PTR",pImagebase + pSecHeader.VirtualAddress,"PTR",pData + pSecHeader.PointerToRawData,"PTR",pSecHeader.SizeOfRawData,"UInt*", NumberOfBytes)
                          pSecHeader[]:=pSecHeader[]+sizeof(pSecHeader)
                      }
                      if DllCall("WriteProcessMemory","PTR",pi.hProcess,"PTR",pPebImageBase,"PTR",pNtHeader.OptionalHeader.ImageBase[""],"PTR",(Force32Bit?4:A_PtrSize),"UInt*",NumberOfBytes){
                          ctx[A_PtrSize=8&&!Force32Bit?"Rcx":"Eax"] := pImagebase + pNtHeader.OptionalHeader.AddressOfEntryPoint
                          if DllCall((Force32Bit?"Wow64":"") "SetThreadContext","PTR",pi.hThread, "PTR",ctx[]){
                              if DllCall("ResumeThread","PTR",pi.hThread){
                                if (Script){ ; use pipe to pass script to new executable
                                  DllCall("ConnectNamedPipe","PTR",__PIPE_GA_,"PTR",0)
                                  DllCall("CloseHandle","PTR",__PIPE_GA_)
                                  DllCall("ConnectNamedPipe","PTR",__PIPE_,"PTR",0)
                                  if !DllCall("WriteFile","PTR",__PIPE_,"str",script,"UInt",(StrLen(script)+1)*(A_IsUnicode ? 2 : 1),"UInt*",0,"PTR",0)
                                  Return DllCall("CloseHandle","PTR",__PIPE_),0
                                  DllCall("CloseHandle","PTR",__PIPE_)
                                }
                                return pi.hProcess
                              }
                          }
                      }
                  }
              }
          }
      }
      DllCall("TerminateProcess","PTR",pi.hProcess,"UInt", 0)
  }
  return false
}


BinRun_Uncompress( ByRef D ) {  ; Shortcode version of VarZ_Decompress() of VarZ 2.0 wrapper
; VarZ 2.0 by SKAN, 27-Sep-2012. http://www.autohotkey.com/community/viewtopic.php?t=45559
 IfNotEqual, A_Tab, % ID:=NumGet(D,"UInt"), IfNotEqual, ID, 0x5F5A4C,  Return 0, ErrorLevel := -1
 savedHash := NumGet(D,4,"UInt"), TZ := NumGet(D,10,"UInt"), DZ := NumGet(D,14,"UInt")
 DllCall( "shlwapi\HashData", UInt,&D+8, UInt,DZ+10, UIntP,Hash, UInt,4 )
 IfNotEqual, Hash, %savedHash%, Return 0, ErrorLevel := -2
 VarSetCapacity( TD,TZ,0 ), NTSTATUS := DllCall( "ntdll\RtlDecompressBuffer", UShort
 , NumGet(D,8,"UShort"), PTR, &TD, UInt,TZ, PTR,&D+18, UInt,DZ, UIntP,Final, UInt )
 IfNotEqual, NTSTATUS, 0, Return 0, ErrorLevel := NTSTATUS
 VarSetCapacity( D,Final,0 ), DllCall( "RtlMoveMemory", PTR,&D, PTR,&TD, PTR,Final )
 If NumGet(D,"UInt")=0x315F5A4C && NumPut(0x005F5A4C,D,"UInt")
  Return BinRun_Uncompress( D )
Return Final, VarSetCapacity( D,-1 )
}


HotKeyIt
  • Moderators
  • 7439 posts
  • Last active: Jun 22 2016 09:14 PM
  • Joined: 18 Jun 2008

... any chance you wrote your ResourceLoadLibrary function in ahk before creating the built in function in _H? I'd like to use in in _L if possible

Yes, see _MemoryLibrary wink.png

 

 

Thanks.
But I found using BinRun () more smooth,
The most obvious features are:
Mouse funnel does not appear,
Like calling DLL, as smooth.
DynaRun () seems to take up more system resources,
This is probably the illusion.
 
Perhaps DynaRun () can also be loaded in memory?

I have done some improvements to DynaRun() and on my Laptop it is running 2 times faster than BinRun(), but probably this is due to SSD disk though I think Windows caches the executable anyway.



Larctic
  • Members
  • 303 posts
  • Last active: May 10 2016 04:56 PM
  • Joined: 21 Jul 2012
New BinRun (), to enhance the speed, cool.happy.png
And DynaRun () is almost the same. (DynaRun () seems to exist garbled)
I think I still prefer BinRun (), 
It gets rid of the hard drive.
thanks.
 
 
Incidentally question.
Transfer data between processes, L to use it, can only pass strings.
If the H version, it can pass the full variables?
Such as binary variables.
Using H characteristics, or "msvcr100.dll" and the like
I did not have much understanding.
I hope that in a number of processes, to achieve the same effect like ahk.dll command.
 
 
From OnMessage () examples:
 
Send:

	VarSetCapacity(CopyDataStruct, 3*A_PtrSize, 0) 
	SizeInBytes := (StrLen(StringToSend) + 1) * (A_IsUnicode ? 2 : 1)
	NumPut(SizeInBytes, CopyDataStruct, A_PtrSize) 
	NumPut(&StringToSend, CopyDataStruct, 2*A_PtrSize) 

Receive:

	CopyOfData := StrGet(NumGet(lParam + 2*A_PtrSize)) 


HotKeyIt
  • Moderators
  • 7439 posts
  • Last active: Jun 22 2016 09:14 PM
  • Joined: 18 Jun 2008

Sure, works on AHK_L and AHK_H :)

For AHK_H only you can remove #include <_Struct> and change new _Struct to Struct.

PID:=DynaRun("
    (
    #Persistent
    OnMessage(0x4a,""WM_CopyDataVar"")
    SetTimer,Listvars,2000
    return
    ListVars:
    ListVars
    Return
    Escape::ExitApp
    ^!a::MsgBox,262144,VarInfo,`% NumGet(&variable,0,""UInt"") ""``n"" NumGet(&variable,4,""UInt"") 
    #include <_Struct>
    WM_CopyDataVar(w,CopyDataStruct){
      global
      static cds:=new _Struct(""ULONG_PTR dwData,DWORD cbData,PVOID lpData"")
      local var,offset,name
      cds[]:=CopyDataStruct,offset:=StrLen(name:=StrGet(cds.lpData,""CP0""))+1
      if (cds.dwData<2){
        VarSetCapacity(`%name`%,cds.cbData-offset)
       ,DllCall(""RtlMoveMemory"",PTR,&`%name`%,PTR,cds.lpData+offset,PTR,cds.cbData-offset)
       if cds.dwData
        VarsetCapacity(`%name`%,-1)
      } else
        `%name`%:=NumGet(cds.lpData,cds.cbData=8?""UInt64"":cds.cbData=4?""UInt"":cds.cbData=2?""UShort"":""UChar"")
    }
    )")
Sleep 100 ; process needs starting first

If !SendMessageVar("ahk_pid " PID,"test","Hello")
  MsgBox, 262144,Test,Message was sent successfull

VarSetCapacity(data,8),NumPut(100,data,"UInt"),NumPut(200,data,4,"UInt")
If !SendMessageVar("ahk_pid " PID,"variable",data,8)
  MsgBox, 262144,Test,Press CTRL+ALT+a to display structure in other Process or Escape to exit

#include <_Struct>
; SendMessageVar(window,VariableName,Data,Size)
; - window = e.g. ahk_class AutoHotkey or ahk_id 0x345678
; - VariableName = the name of variable to set in other process
; - Data = ByRef data, can be string, integer or variable
; - - for integer specify size -> 1=UChar, 2=UShort,4=UInt,8=UInt64
; - - for string size must be 0
; - - for variable/memory data size must be the size of data
SendMessageVar(window:="",VarName:="",ByRef data:="",size:=0){
  static cds:=new _Struct("ULONG_PTR dwData,DWORD cbData,PVOID lpData")
  if (!window || !varName || varName+0!="")
    return 1
  dhw:=A_DetectHiddenWindows
  DetectHiddenWindows,On
  cds.dwData:=size=0?1:(data+0!=""?2:0) ; 0 = data, 1 = string, 2 = integer
  VarSetCapacity(cdsdata,(size:=size?size:StrLen(data)*(A_IsUnicode?2:1)) + nsz:=StrLen(VarName)+1,0)
  ,StrPut(VarName,&cdsdata,"CP0")
  If (data+0!="") ; NumPut
    NumPut(data,&cdsdata+nsz,size=8?"UInt64":size=4?"UInt":size=2?"UShort":"UChar")
  else ; StrPut, MemPut
    DllCall("RtlMoveMemory","PTR",&cdsdata+nsz,"PTR",&data,"PTR",size)
  cds.lpData:=&cdsdata
  cds.cbData:=size+nsz
  SendMessage,0x4a,% A_ScriptHwnd,% cds[],,%window%
  DetectHiddenWindows % dhw
  return ErrorLevel
}


Larctic
  • Members
  • 303 posts
  • Last active: May 10 2016 04:56 PM
  • Joined: 21 Jul 2012
Thanks.
I'm trying to pass a binary variable,
But why is it always fail?
 
PID:=DynaRun("
    (
    #Persistent
    OnMessage(0x4a,""WM_CopyDataVar"")
    return
    !s::
    ListVars
    Return
    Escape::ExitApp
    !a::MsgBox,`% StrLen(variable)
    WM_CopyDataVar(w,CopyDataStruct){
      global
      static cds:=Struct(""ULONG_PTR dwData,DWORD cbData,PVOID lpData"")
      local var,offset,name
      cds[]:=CopyDataStruct,offset:=StrLen(name:=StrGet(cds.lpData,""CP0""))+1
      if (cds.dwData<2){
        VarSetCapacity(`%name`%,cds.cbData-offset)
       ,DllCall(""RtlMoveMemory"",PTR,&`%name`%,PTR,cds.lpData+offset,PTR,cds.cbData-offset)
       if cds.dwData
        VarsetCapacity(`%name`%,-1)
      } else
        `%name`%:=NumGet(cds.lpData,cds.cbData=8?""UInt64"":cds.cbData=4?""UInt"":cds.cbData=2?""UShort"":""UChar"")
    }
    )")
Sleep 100 ; process needs starting first


FileRead,data,*c %A_AhkPath%
If !SendMessageVar("ahk_pid " PID,"variable",data,8)
  MsgBox, 262144,Test,Press CTRL+ALT+a to display structure in other Process or Escape to exit



; SendMessageVar(window,VariableName,Data,Size)
; - window = e.g. ahk_class AutoHotkey or ahk_id 0x345678
; - VariableName = the name of variable to set in other process
; - Data = ByRef data, can be string, integer or variable
; - - for integer specify size -> 1=UChar, 2=UShort,4=UInt,8=UInt64
; - - for string size must be 0
; - - for variable/memory data size must be the size of data
SendMessageVar(window:="",VarName:="",ByRef data:="",size:=0){
  static cds:=Struct("ULONG_PTR dwData,DWORD cbData,PVOID lpData")
  if (!window || !varName || varName+0!="")
    return 1
  dhw:=A_DetectHiddenWindows
  DetectHiddenWindows,On
  cds.dwData:=size=0?1:(data+0!=""?2:0) ; 0 = data, 1 = string, 2 = integer
  VarSetCapacity(cdsdata,(size:=size?size:StrLen(data)*(A_IsUnicode?2:1)) + nsz:=StrLen(VarName)+1,0)
  ,StrPut(VarName,&cdsdata,"CP0")
  If (data+0!="") ; NumPut
    NumPut(data,&cdsdata+nsz,size=8?"UInt64":size=4?"UInt":size=2?"UShort":"UChar")
  else ; StrPut, MemPut
    DllCall("RtlMoveMemory","PTR",&cdsdata+nsz,"PTR",&data,"PTR",size)
  cds.lpData:=&cdsdata
  cds.cbData:=size+nsz
  SendMessage,0x4a,% A_ScriptHwnd,% cds[],,%window%
  DetectHiddenWindows % dhw
  return ErrorLevel
}



HotKeyIt
  • Moderators
  • 7439 posts
  • Last active: Jun 22 2016 09:14 PM
  • Joined: 18 Jun 2008

Try again now, requires AutoHotkey_H:

PID:=DynaRun("
    (
    #Persistent
    
    OnMessage(0x4a,""WM_CopyDataVar"")
    return
    !s::
    ListVars
    Return
    Escape::ExitApp
    !a::MsgBox,`% StrLen(variable)
    WM_CopyDataVar(w,CopyDataStruct){
      global
      static cds:=Struct(""ULONG_PTR dwData,DWORD cbData,PVOID lpData"")
            ,_AHKVar := ""{Int64 ContentsInt64,Double ContentsDouble,PTR object},{char *mByteContents,LPTSTR CharContents},{UINT_PTR Length,_AHKVar *AliasFor},{UINT_PTR Capacity,UINT_PTR BIV},BYTE HowAllocated,BYTE Attrib,BYTE IsLocal,BYTE Type,LPTSTR Name""
      local var,offset,name
      cds[]:=CopyDataStruct,offset:=StrLen(name:=StrGet(cds.lpData,""CP0""))+1
      if (cds.dwData<2){
        VarSetCapacity(`%name`%,cds.cbData-offset)
        DllCall(""RtlMoveMemory"",PTR,&`%name`%,PTR,cds.lpData+offset,PTR,cds.cbData-offset)
        if cds.dwData
          VarsetCapacity(`%name`%,-1)
        else
          Struct(_AhkVar,getvar(`%name`%),{Attrib:1,Length:cds.cbData-offset})
      } else
        `%name`%:=NumGet(cds.lpData,cds.cbData=8?""UInt64"":cds.cbData=4?""UInt"":cds.cbData=2?""UShort"":""UChar"")
    }
    )")
Sleep 100 ; process needs starting first

FileRead,data,*c %A_AhkPath%
If !SendMessageVar("ahk_pid " PID,"variable",data,size)
  MsgBox, 262144,Test,Press CTRL+ALT+a to display structure in other Process or Escape to exit



; SendMessageVar(window,VariableName,Data,Size)
; - window = e.g. ahk_class AutoHotkey or ahk_id 0x345678
; - VariableName = the name of variable to set in other process
; - Data = ByRef data, can be string, integer or variable
; - - for integer specify size -> 1=UChar, 2=UShort,4=UInt,8=UInt64
; - - for string size must be 0
; - - for variable/memory data size must be the size of data
SendMessageVar(window:="",VarName:="",ByRef data:="",size:=0){
  static cds:=Struct("ULONG_PTR dwData,DWORD cbData,PVOID lpData")
  if (!window || !varName || varName+0!="")
    return 1
  dhw:=A_DetectHiddenWindows
  DetectHiddenWindows,On
  cds.dwData:=size=0?1:(data+0!=""?2:0) ; 0 = data, 1 = string, 2 = integer
  VarSetCapacity(cdsdata,(size:=size?size:StrLen(data)*(A_IsUnicode?2:1)) + nsz:=StrLen(VarName)+1,0)
  ,StrPut(VarName,&cdsdata,"CP0")
  If (data+0!="") ; NumPut
    NumPut(data,&cdsdata+nsz,size=8?"UInt64":size=4?"UInt":size=2?"UShort":"UChar")
  else ; StrPut, MemPut
    DllCall("RtlMoveMemory","PTR",&cdsdata+nsz,"PTR",&data,"PTR",size)
  cds.lpData:=&cdsdata
  cds.cbData:=size+nsz
  SendMessage,0x4a,% A_ScriptHwnd,% cds[],,%window%
  DetectHiddenWindows % dhw
  return ErrorLevel
}


Larctic
  • Members
  • 303 posts
  • Last active: May 10 2016 04:56 PM
  • Joined: 21 Jul 2012
Thanks.happy.png
 
I now want to try to tie BinRun
Write a new library
To make it have the same effect as AhkDllThread,
Can interactively control and transfer data.
As ahk.dll supplement.
But I greedily want to know, is not it can be done more
For example,
1, a large number of data transfer, is safe? Is not require similar CriticalObject constraints?
2, can pass the object? Seems "CDS" is th object,as a class.  I do not know how to use Struct. If yes, then, This will bring a qualitative leap. Or, pass multiple parameters. Such as
SendMessageVar(window:="",n:=1, ByRef data1:="",ByRef data2:="",ByRef data3:="",ByRef data4:="",ByRef data5:="",ByRef data6:="",ByRef data7:="",ByRef data8:="",ByRef data9:="",ByRef data10:=""){
...
  SendMessage,0x4a,% n,% cds[],,%window%   ;n =1, Call the function
...
}
3, BinRun similar AhkExported can, like, read the EXE function, and can be called. Perhaps, ahk.exe can be built AhkExported.
 
In addition, the use of scripts loaded BinRun,
Can not be restarted,
This problem may be improved from EXE aspects do? Such as adding a new command line parameters, such as "/ b"
Similar ahk.dll.
Frankly, the use of BinRun few opportunities
ahk.dll satisfy everything.
But it's too easy to collapse,
Or interfere with other threads.
Some code uses BinRun more stable.


HotKeyIt
  • Moderators
  • 7439 posts
  • Last active: Jun 22 2016 09:14 PM
  • Joined: 18 Jun 2008

1. Data transfer will be slow in general and not thread safe.

2. Objects no. Simple Structs possible.

3. Not sure what you mean.

 

Neither BinRun, nor DynaRun can be restarted because script does not exist anymore.

Generally it would be possible by backing up the script and starting another DynaRun but DynaRun would need to be build in.

 

AutoHotkey.dll is definitely the way to go. We should better add error checks to ahkdll to not to collapse where possible.

If you like, get some examples together and open a new thread so everyone can contribute too and I will add error checking bit by bit.



Larctic
  • Members
  • 303 posts
  • Last active: May 10 2016 04:56 PM
  • Joined: 21 Jul 2012
Yes, I will strive to complete the script.
3 can ignore, I did not express clearly.
Thanks.


Larctic
  • Members
  • 303 posts
  • Last active: May 10 2016 04:56 PM
  • Joined: 21 Jul 2012
DynaRun can use memory version?
 
 
 
My goal, Similar ahkdll, the use of multiple processes.
Like this:
AhkProcess := AhkProcess()
AhkProcess.ahktext()
AhkProcess.addScript("Sub:`nMsgbox Sub`nReturn",0)
AhkProcess.ahkLabel.Sub

Code is not difficult, just a little complicated.



spacecase
  • Members
  • 12 posts
  • Last active: Jul 17 2014 07:53 PM
  • Joined: 31 Mar 2014

Hi, how do I capture stdout and stderr?

 

thanks



tmplinshi
  • Members
  • 245 posts
  • Last active: Mar 12 2015 02:29 PM
  • Joined: 06 Apr 2012

Is it possible to add a "Hide" parameter, same as "run, xxx,, Hide"?



HotKeyIt
  • Moderators
  • 7439 posts
  • Last active: Jun 22 2016 09:14 PM
  • Joined: 18 Jun 2008

Hi, how do I capture stdout and stderr?

 

thanks

The same way you would do with normal executable. For autohotkey you can use /ErrStdOut parameter or #ErrStdOut directive.

 

Is it possible to add a "Hide" parameter, same as "run, xxx,, Hide"?

Can you try this and let me know if it works as expected.

BinRun(pData,cmdLine:="",cmdLineScript:="",Hide:=0,ExeToUse:=""){
  static IMAGE_DOS_HEADER :="WORD e_magic;WORD e_cblp;WORD e_cp;WORD e_crlc;WORD e_cparhdr;WORD e_minalloc;WORD e_maxalloc;WORD e_ss;WORD e_sp;WORD e_csum;WORD e_ip;WORD e_cs;WORD e_lfarlc;WORD e_ovno;WORD e_res[4];WORD e_oemid;WORD e_oeminfo;WORD e_res2[10];LONG e_lfanew"
  ,IMAGE_FILE_HEADER :="WORD Machine;WORD NumberOfSections;DWORD TimeDateStamp;DWORD PointerToSymbolTable;DWORD NumberOfSymbols;WORD SizeOfOptionalHeader;WORD Characteristics"
  ,IMAGE_DATA_DIRECTORY :="DWORD VirtualAddress;DWORD Size"
  ,IMAGE_OPTIONAL_HEADER64:="WORD Magic;BYTE MajorLinkerVersion;BYTE MinorLinkerVersion;DWORD SizeOfCode;DWORD SizeOfInitializedData;DWORD SizeOfUninitializedData;DWORD AddressOfEntryPoint;DWORD BaseOfCode;ULONGLONG ImageBase;DWORD SectionAlignment;DWORD FileAlignment;WORD MajorOperatingSystemVersion;WORD MinorOperatingSystemVersion;WORD MajorImageVersion;WORD MinorImageVersion;WORD MajorSubsystemVersion;WORD MinorSubsystemVersion;DWORD Win32VersionValue;DWORD SizeOfImage;DWORD SizeOfHeaders;DWORD CheckSum;WORD Subsystem;WORD DllCharacteristics;ULONGLONG SizeOfStackReserve;ULONGLONG SizeOfStackCommit;ULONGLONG SizeOfHeapReserve;ULONGLONG SizeOfHeapCommit;DWORD LoaderFlags;DWORD NumberOfRvaAndSizes;BinRun(IMAGE_DATA_DIRECTORY) DataDirectory[16]"
  ,IMAGE_OPTIONAL_HEADER32 :="WORD Magic;BYTE MajorLinkerVersion;BYTE MinorLinkerVersion;DWORD SizeOfCode;DWORD SizeOfInitializedData;DWORD SizeOfUninitializedData;DWORD AddressOfEntryPoint;DWORD BaseOfCode;DWORD BaseOfData;DWORD ImageBase;DWORD SectionAlignment;DWORD FileAlignment;WORD MajorOperatingSystemVersion;WORD MinorOperatingSystemVersion;WORD MajorImageVersion;WORD MinorImageVersion;WORD MajorSubsystemVersion;WORD MinorSubsystemVersion;DWORD Win32VersionValue;DWORD SizeOfImage;DWORD SizeOfHeaders;DWORD CheckSum;WORD Subsystem;WORD DllCharacteristics;DWORD SizeOfStackReserve;DWORD SizeOfStackCommit;DWORD SizeOfHeapReserve;DWORD SizeOfHeapCommit;DWORD LoaderFlags;DWORD NumberOfRvaAndSizes;BinRun(IMAGE_DATA_DIRECTORY) DataDirectory[16]"
  ,IMAGE_NT_HEADERS:="DWORD Signature;BinRun(IMAGE_FILE_HEADER) FileHeader;BinRun(IMAGE_OPTIONAL_HEADER" (A_PtrSize=8?64:32) ") OptionalHeader"
  ,IMAGE_NT_HEADERS32:="DWORD Signature;BinRun(IMAGE_FILE_HEADER) FileHeader;BinRun(IMAGE_OPTIONAL_HEADER32) OptionalHeader"
  ,IMAGE_NT_HEADERS64:="DWORD Signature;BinRun(IMAGE_FILE_HEADER) FileHeader;BinRun(IMAGE_OPTIONAL_HEADER64) OptionalHeader"
  ,IMAGE_SECTION_HEADER:="BYTE Name[8];{DWORD PhysicalAddress;DWORD VirtualSize};DWORD VirtualAddress;DWORD SizeOfRawData;DWORD PointerToRawData;DWORD PointerToRelocations;DWORD PointerToLinenumbers;WORD NumberOfRelocations;WORD NumberOfLinenumbers;DWORD Characteristics"
  ,FLOATING_SAVE_AREA :="DWORD ControlWord;DWORD StatusWord;DWORD TagWord;DWORD ErrorOffset;DWORD ErrorSelector;DWORD DataOffset;DWORD DataSelector;BYTE RegisterArea[80];DWORD Cr0NpxState"
  ,PROCESS_INFORMATION :="HANDLE hProcess;HANDLE hThread;DWORD dwProcessId;DWORD dwThreadId"
  ,STARTUPINFO :="DWORD cb;LPTSTR lpReserved;LPTSTR lpDesktop;LPTSTR lpTitle;DWORD dwX;DWORD dwY;DWORD dwXSize;DWORD dwYSize;DWORD dwXCountChars;DWORD dwYCountChars;DWORD dwFillAttribute;DWORD dwFlags;WORD wShowWindow;WORD cbReserved2;LPBYTE lpReserved2;HANDLE hStdInput;HANDLE hStdOutput;HANDLE hStdError"
  ,M128A:="ULONGLONG Low;LONGLONG High"
  ,_XMM_SAVE_AREA32 :="WORD ControlWord;WORD StatusWord;BYTE TagWord;BYTE Reserved1;WORD ErrorOpcode;DWORD ErrorOffset;WORD ErrorSelector;WORD Reserved2;DWORD DataOffset;WORD DataSelector;WORD Reserved3;DWORD MxCsr;DWORD MxCsr_Mask;BinRun(M128A) FloatRegisters[8];BinRun(M128A)XmmRegisters[16];BYTE Reserved4[96]"
  ,CONTEXT64:="DWORD64 P1Home;DWORD64 P2Home;DWORD64 P3Home;DWORD64 P4Home;DWORD64 P5Home;DWORD64 P6Home;DWORD ContextFlags;DWORD MxCsr;WORD SegCs;WORD SegDs;WORD SegEs;WORD SegFs;WORD SegGs;WORD SegSs;DWORD EFlags;DWORD64 Dr0;DWORD64 Dr1;DWORD64 Dr2;DWORD64 Dr3;DWORD64 Dr6;DWORD64 Dr7;DWORD64 Rax;DWORD64 Rcx;DWORD64 Rdx;DWORD64 Rbx;DWORD64Rsp;DWORD64 Rbp;DWORD64 Rsi;DWORD64 Rdi;DWORD64 R8;DWORD64 R9;DWORD64 R10;DWORD64 R11;DWORD64R12;DWORD64 R13;DWORD64 R14;DWORD64 R15;DWORD64 Rip;{BinRun(_XMM_SAVE_AREA32) FltSave;struct { BinRun(M128A) Header[2];BinRun(M128A) Legacy[8];BinRun(M128A) Xmm0;BinRun(M128A) Xmm1;BinRun(M128A) Xmm2;BinRun(M128A) Xmm3;BinRun(M128A) Xmm4;BinRun(M128A) Xmm5;BinRun(M128A) Xmm6;BinRun(M128A) Xmm7;BinRun(M128A) Xmm8;BinRun(M128A) Xmm9;BinRun(M128A) Xmm10;BinRun(M128A) Xmm11;BinRun(M128A) Xmm12;BinRun(M128A) Xmm13;BinRun(M128A) Xmm14;BinRun(M128A) Xmm15}};BinRun(M128A) VectorRegister[26];DWORD64 VectorControl;DWORD64 DebugControl;DWORD64 LastBranchToRip;DWORD64 LastBranchFromRip;DWORD64 LastExceptionToRip;DWORD64 LastExceptionFromRip"
  ,CONTEXT32:="DWORD ContextFlags;DWORD Dr0;DWORD Dr1;DWORD Dr2;DWORD Dr3;DWORD Dr6;DWORD Dr7;BinRun(FLOATING_SAVE_AREA) FloatSave;DWORD SegGs;DWORD SegFs;DWORD SegEs;DWORD SegDs;DWORD Edi;DWORD Esi;DWORD Ebx;DWORD Edx;DWORD Ecx;DWORD Eax;DWORD Ebp;DWORD Eip;DWORD SegCs;DWORD EFlags;DWORD Esp;DWORD SegSs;BYTE ExtendedRegisters[512]"
  ,IMAGE_NT_SIGNATURE:=17744,IMAGE_DOS_SIGNATURE:=23117,PAGE_EXECUTE_READWRITE:=64,CREATE_SUSPENDED:=4
  ,MEM_COMMIT:=4096,MEM_RESERVE:=8192,STARTF_USESHOWWINDOW:=1
  ,h2o:="B29C2D1CA2C24A57BC5E208EA09E162F(){`nPLACEHOLDERB29C2D1CA2C24A57BC5E208EA09E162FVarSetCapacity(dmp,sz:=StrLen(hex)//2,0)`nLoop,Parse,hex`nIf (""""!=h.=A_LoopField) && !Mod(A_Index,2)`nNumPut(""0x"" h,&dmp,A_Index/2-1,""UChar""),h:=""""`nreturn ObjLoad(&dmp,sz)`n}`n"
  If (pData+0="")
  {
    ; Try first reading the file from Resource
    If res := DllCall("FindResource","PTR",lib:=DllCall("GetModuleHandle","PTR",0,"PTR"),"Str",pData,"PTR",10,"PTR")
      VarSetCapacity(data,sz :=DllCall("SizeofResource","PTR",lib,"PTR",res))
      ,DllCall("RtlMoveMemory","PTR",&data,"PTR",DllCall("LockResource","PTR",hres:=DllCall("LoadResource","PTR",lib,"PTR",res,"PTR"),"PTR"),"PTR",sz)
      ,DllCall("FreeResource","PTR",hres)
      ,!BinRun_Uncompress(data)?(UnZipRawMemory(&data,data2)?(data:=data2):""):""
    else ; else try reading file from disc etc...
      FileRead,Data,*c %pData%
    pData:=&Data
  }
 
  If InStr(cmdLine,"`n"){ ; a script was given, first line contains the cmdLine
    PipeName := "\\.\pipe\AHK" A_TickCount
    __PIPE_GA_ := DllCall("CreateNamedPipe","str",PipeName,"UInt",2,"UInt",0,"UInt",255,"UInt",0,"UInt",0,"PTR",0,"PTR",0)
    __PIPE_    := DllCall("CreateNamedPipe","str",PipeName,"UInt",2,"UInt",0,"UInt",255,"UInt",0,"UInt",0,"PTR",0,"PTR",0)
    if (__PIPE_=-1 or __PIPE_GA_=-1)
      Return 0
    Script:=SubStr(cmdLine,InStr(cmdLine,"`n")+1)
    ,cmdLine:=Trim(SubStr(cmdLine,1,InStr(cmdLine,"`n")),"`n`r") A_Space PipeName
  }

  IDH:=Struct(IMAGE_DOS_HEADER,pData)
 
  if (IDH.e_magic != IMAGE_DOS_SIGNATURE){
    MsgBox ERROR: e_magic not found
    return
  }
  INH := Struct(IMAGE_NT_HEADERS,pData + IDH.e_lfanew)
 
  if (INH.Signature != IMAGE_NT_SIGNATURE){
    MsgBox ERROR: Signature not found
    return
  }

  If (A_PtrSize=8&&INH.OptionalHeader.magic=267) ; x86 on x64
    pNtHeader:=Struct(IMAGE_NT_HEADERS32,pData + IDH.e_lfanew),ctx:=Struct(Context32),Force32Bit:=1
    ,ctx.ContextFlags := (A_PtrSize=8?0x100000:0x10000) | 0x2 ;CONTEXT_INTEGER
    ,UsedExe:=ExeToUse?ExeToUse:A_WinDir "\Microsoft.NET\Framework\v2.0.50727\vbc.exe"
  else if (A_PtrSize=4&&INH.OptionalHeader.magic=523) ; x64 on x86 not possible
    Return false
  else
    pNtHeader:=INH,UsedExe:=ExeToUse?ExeToUse:A_IsCompiled?A_ScriptFullPath:A_AhkPath
    ,ctx:=Struct(A_PtrSize=8?Context64:Context32),ctx.ContextFlags := (A_PtrSize=8?0x100000:0x10000) | 0x2 ;CONTEXT_INTEGER
  pi:=Struct(PROCESS_INFORMATION)
  ,si:=Struct(STARTUPINFO),si.cb:=sizeof(si),si.dwFlags:=HIDE?STARTF_USESHOWWINDOW:0 ;si.wShowWindow already set to 0
  if DllCall("CreateProcess","PTR",0,"STR","""" UsedExe """" A_Space cmdLine (cmdLineScript?A_Space cmdLineScript:"")
            ,"PTR",0,"PTR",0,"int",0,"Int",CREATE_SUSPENDED,"PTR",0,"PTR",0,"PTR",si[],"PTR",pi[]){
      if DllCall((Force32Bit?"Wow64":"") "GetThreadContext","PTR",pi.hThread,"PTR", ctx[]){
          pPebImageBase:=ctx[A_PtrSize=8&&!Force32Bit?"Rdx":"Ebx"] + (Force32Bit?4:A_PtrSize)*2
          if DllCall("ReadProcessMemory","PTR",pi.hProcess, "PTR", pPebImageBase,"PTR*", dwImagebase,"PTR", (Force32Bit?4:A_PtrSize),"Uint*",NumberOfBytes){
              DllCall("ntdll\NtUnmapViewOfSection","PTR",pi.hProcess, "PTR",dwImagebase)
              ,pImagebase := DllCall("VirtualAllocEx","PTR",pi.hProcess, "PTR",pNtHeader.OptionalHeader.ImageBase, "PTR",pNtHeader.OptionalHeader.SizeOfImage,"UInt", MEM_COMMIT|MEM_RESERVE,"UInt", PAGE_EXECUTE_READWRITE,"PTR")
              if (pImagebase)
              {
                  if DllCall("WriteProcessMemory","PTR",pi.hProcess,"PTR",pImagebase,"PTR",pData,"PTR",pNtHeader.OptionalHeader.SizeOfHeaders,"UInt*",NumberOfBytes){
                      pSecHeader :=Struct(IMAGE_SECTION_HEADER)
                      ,pSecHeader[] :=pNtHeader.OptionalHeader[""]+pNtHeader.FileHeader.SizeOfOptionalHeader
                      ,counter := 0
                      while (++counter < pNtHeader.FileHeader.NumberOfSections+1)
                          DllCall("WriteProcessMemory","PTR",pi.hProcess,"PTR",pImagebase + pSecHeader.VirtualAddress,"PTR",pData + pSecHeader.PointerToRawData,"PTR",pSecHeader.SizeOfRawData,"UInt*", NumberOfBytes)
                          ,pSecHeader[]:=pSecHeader[]+sizeof(pSecHeader)
                      if DllCall("WriteProcessMemory","PTR",pi.hProcess,"PTR",pPebImageBase,"PTR",pNtHeader.OptionalHeader.ImageBase[""],"PTR",(Force32Bit?4:A_PtrSize),"UInt*",NumberOfBytes){
                          ctx[A_PtrSize=8&&!Force32Bit?"Rcx":"Eax"] := pImagebase + pNtHeader.OptionalHeader.AddressOfEntryPoint
                          if DllCall((Force32Bit?"Wow64":"") "SetThreadContext","PTR",pi.hThread, "PTR",ctx[]){
                              if DllCall("ResumeThread","PTR",pi.hThread){
                                if (Script){ ; use pipe to pass script to new executable
                                  If IsObject(cmdLineScript){
                                    VarSetCapacity(buf,6),VarsetCapacity(val,8,0)
                                    Loop % sz:=ObjDump(cmdLineScript,dmp)
                                      If NumPut(NumGet(&dmp,A_Index-1,"UChar"),&val,"UIn64") && DllCall("msvcrt\_vsnwprintf","Str",buf,"ptr",6,"str","`%02X","ptr",&val)
                                        hex.=buf
                                    While % _hex:=SubStr(Hex,1 + (A_Index-1)*16370,16370)
                                      _s.= "hex" (A_Index=1?":":".") "=""" _hex """`n"
                                    script:=h2o "global A_Argv:=B29C2D1CA2C24A57BC5E208EA09E162F()`n" script
                                    StringReplace,script,script,PLACEHOLDERB29C2D1CA2C24A57BC5E208EA09E162F,%_s%
                                  }
                                  DllCall("ConnectNamedPipe","PTR",__PIPE_GA_,"PTR",0)
                                  ,DllCall("CloseHandle","PTR",__PIPE_GA_)
                                  ,DllCall("ConnectNamedPipe","PTR",__PIPE_,"PTR",0)
                                  if !DllCall("WriteFile","PTR",__PIPE_,"str",(A_IsUnicode ? chr(0xfeff) : (chr(239) . chr(187) . chr(191))) script
                                              ,"UInt",(StrLen(script))*(A_IsUnicode ? 2 : 1)+(A_IsUnicode?4:6),"UInt*",0,"PTR",0)
                                    Return DllCall("CloseHandle","PTR",__PIPE_),0
                                  DllCall("CloseHandle","PTR",__PIPE_)
                                }
                                return pi.dwProcessId
                              }
                          }
                      }
                  }
              }
          }
      }
      DllCall("TerminateProcess","PTR",pi.hProcess,"UInt", 0)
  }
  return FALSE
}
BinRun_Uncompress( ByRef D ) {  ; Shortcode version of VarZ_Decompress() of VarZ 2.0 wrapper
; VarZ 2.0 by SKAN, 27-Sep-2012. http://www.autohotkey.com/community/viewtopic.php?t=45559
If 0x5F5A4C != NumGet(D, "UInt" )
  Return ErrorLevel := -1,0
savedHash := NumGet(D,4,"UInt"), TZ := NumGet(D,10,"UInt"), DZ := NumGet(D,14,"UInt")
,DllCall( "shlwapi\HashData", PTR,&D+8, UInt,DZ+10, UIntP,Hash, UInt,4 )
If (Hash!=savedHash)
  Return ErrorLevel := -2,0
VarSetCapacity( TD,TZ,0 ), NTSTATUS := DllCall( "ntdll\RtlDecompressBuffer", UShort
, NumGet(D,8,"UShort"), PTR, &TD, UInt,TZ, PTR,&D+18, UInt,DZ, UIntP,Final, UInt )
If NTSTATUS!=0
  Return ErrorLevel := NTSTATUS,0
VarSetCapacity( D,Final,0 ), DllCall( "RtlMoveMemory", PTR,&D, PTR,&TD, PTR,Final )
If NumGet(D,"UInt")=0x315F5A4C && NumPut(0x005F5A4C,D,"UInt")
  Return BinRun_Uncompress( D )
Return VarSetCapacity( D,-1 ),Final
}


tmplinshi
  • Members
  • 245 posts
  • Last active: Mar 12 2015 02:29 PM
  • Joined: 06 Apr 2012

Sorry for late response, I wasn't at home in the past two days.

 

I got an error:

 

 

     Call to nonexistent function.
 
Specifically: UnZipRawMemory(&data,data2)?(data:=data2):""):""

 

 

 

Edit: Oh, wait, I see. I need the header of original BinRun.ahk. Testing...

Edit2: Seems not ture. I'm using AHK_L, sorry I haven't mentioned this before.



HotKeyIt
  • Moderators
  • 7439 posts
  • Last active: Jun 22 2016 09:14 PM
  • Joined: 18 Jun 2008

I see, try this:

#Include <_Struct>
Class _BinRun {
  static IMAGE_DOS_HEADER :="
  (
    WORD   e_magic;                     // Magic number
    WORD   e_cblp;                      // Bytes on last page of file
    WORD   e_cp;                        // Pages in file
    WORD   e_crlc;                      // Relocations
    WORD   e_cparhdr;                   // Size of header in paragraphs
    WORD   e_minalloc;                  // Minimum extra paragraphs needed
    WORD   e_maxalloc;                  // Maximum extra paragraphs needed
    WORD   e_ss;                        // Initial (relative) SS value
    WORD   e_sp;                        // Initial SP value
    WORD   e_csum;                      // Checksum
    WORD   e_ip;                        // Initial IP value
    WORD   e_cs;                        // Initial (relative) CS value
    WORD   e_lfarlc;                    // File address of relocation table
    WORD   e_ovno;                      // Overlay number
    WORD   e_res[4];                    // Reserved words
    WORD   e_oemid;                     // OEM identifier (for e_oeminfo)
    WORD   e_oeminfo;                   // OEM information; e_oemid specific
    WORD   e_res2[10];                  // Reserved words
    LONG   e_lfanew;                    // File address of new exe header
  )"
  ,IMAGE_FILE_HEADER :="
  (
    WORD    Machine;
    WORD    NumberOfSections;
    DWORD   TimeDateStamp;
    DWORD   PointerToSymbolTable;
    DWORD   NumberOfSymbols;
    WORD    SizeOfOptionalHeader;
    WORD    Characteristics;
  )"
  ,IMAGE_DATA_DIRECTORY :="
  (
    DWORD   VirtualAddress;
    DWORD   Size;
  )"
  ,IMAGE_OPTIONAL_HEADER64:="
  (
    WORD        Magic;
    BYTE        MajorLinkerVersion;
    BYTE        MinorLinkerVersion;
    DWORD       SizeOfCode;
    DWORD       SizeOfInitializedData;
    DWORD       SizeOfUninitializedData;
    DWORD       AddressOfEntryPoint;
    DWORD       BaseOfCode;
    ULONGLONG   ImageBase;
    DWORD       SectionAlignment;
    DWORD       FileAlignment;
    WORD        MajorOperatingSystemVersion;
    WORD        MinorOperatingSystemVersion;
    WORD        MajorImageVersion;
    WORD        MinorImageVersion;
    WORD        MajorSubsystemVersion;
    WORD        MinorSubsystemVersion;
    DWORD       Win32VersionValue;
    DWORD       SizeOfImage;
    DWORD       SizeOfHeaders;
    DWORD       CheckSum;
    WORD        Subsystem;
    WORD        DllCharacteristics;
    ULONGLONG   SizeOfStackReserve;
    ULONGLONG   SizeOfStackCommit;
    ULONGLONG   SizeOfHeapReserve;
    ULONGLONG   SizeOfHeapCommit;
    DWORD       LoaderFlags;
    DWORD       NumberOfRvaAndSizes;
    _BinRun.IMAGE_DATA_DIRECTORY DataDirectory[16]; // IMAGE_NUMBEROF_DIRECTORY_ENTRIES
  )"
  ,IMAGE_OPTIONAL_HEADER32 :="
  (
    WORD    Magic;
    BYTE    MajorLinkerVersion;
    BYTE    MinorLinkerVersion;
    DWORD   SizeOfCode;
    DWORD   SizeOfInitializedData;
    DWORD   SizeOfUninitializedData;
    DWORD   AddressOfEntryPoint;
    DWORD   BaseOfCode;
    DWORD   BaseOfData;
    DWORD   ImageBase;
    DWORD   SectionAlignment;
    DWORD   FileAlignment;
    WORD    MajorOperatingSystemVersion;
    WORD    MinorOperatingSystemVersion;
    WORD    MajorImageVersion;
    WORD    MinorImageVersion;
    WORD    MajorSubsystemVersion;
    WORD    MinorSubsystemVersion;
    DWORD   Win32VersionValue;
    DWORD   SizeOfImage;
    DWORD   SizeOfHeaders;
    DWORD   CheckSum;
    WORD    Subsystem;
    WORD    DllCharacteristics;
    DWORD   SizeOfStackReserve;
    DWORD   SizeOfStackCommit;
    DWORD   SizeOfHeapReserve;
    DWORD   SizeOfHeapCommit;
    DWORD   LoaderFlags;
    DWORD   NumberOfRvaAndSizes;
    _BinRun.IMAGE_DATA_DIRECTORY DataDirectory[16]; //IMAGE_NUMBEROF_DIRECTORY_ENTRIES
  )"
  ,IMAGE_NT_HEADERS:="
  (
    DWORD Signature;
    _BinRun.IMAGE_FILE_HEADER FileHeader;
    _BinRun.IMAGE_OPTIONAL_HEADER" (A_PtrSize=8?64:32) " OptionalHeader;
  )"
  ,IMAGE_NT_HEADERS32:="
  (
    DWORD Signature;
    _BinRun.IMAGE_FILE_HEADER FileHeader;
    _BinRun.IMAGE_OPTIONAL_HEADER32 OptionalHeader;
  )"
  ,IMAGE_NT_HEADERS64:="
  (
    DWORD Signature;
    _BinRun.IMAGE_FILE_HEADER FileHeader;
    _BinRun.IMAGE_OPTIONAL_HEADER64 OptionalHeader;
  )"
  ,IMAGE_SECTION_HEADER:="
  (
    BYTE    Name[8];
    union {
        DWORD   PhysicalAddress;
        DWORD   VirtualSize;
    };
    DWORD   VirtualAddress;
    DWORD   SizeOfRawData;
    DWORD   PointerToRawData;
    DWORD   PointerToRelocations;
    DWORD   PointerToLinenumbers;
    WORD    NumberOfRelocations;
    WORD    NumberOfLinenumbers;
    DWORD   Characteristics;
  )"
  ,FLOATING_SAVE_AREA :="
  (
    DWORD   ControlWord;
    DWORD   StatusWord;
    DWORD   TagWord;
    DWORD   ErrorOffset;
    DWORD   ErrorSelector;
    DWORD   DataOffset;
    DWORD   DataSelector;
    BYTE    RegisterArea[80]; //SIZE_OF_80387_REGISTERS
    DWORD   Cr0NpxState;
  )"
  ,PROCESS_INFORMATION :="
  (
    HANDLE hProcess;
    HANDLE hThread;
    DWORD  dwProcessId;
    DWORD  dwThreadId;
  )"
  ,STARTUPINFO :="
  (
    DWORD  cb;
    LPTSTR lpReserved;
    LPTSTR lpDesktop;
    LPTSTR lpTitle;
    DWORD  dwX;
    DWORD  dwY;
    DWORD  dwXSize;
    DWORD  dwYSize;
    DWORD  dwXCountChars;
    DWORD  dwYCountChars;
    DWORD  dwFillAttribute;
    DWORD  dwFlags;
    WORD   wShowWindow;
    WORD   cbReserved2;
    LPBYTE lpReserved2;
    HANDLE hStdInput;
    HANDLE hStdOutput;
    HANDLE hStdError;
  )"
  ,M128A:="ULONGLONG Low;LONGLONG High"
  ,_XMM_SAVE_AREA32 :="
  (
      WORD ControlWord;
      WORD StatusWord;
      BYTE TagWord;
      BYTE Reserved1;
      WORD ErrorOpcode;
      DWORD ErrorOffset;
      WORD ErrorSelector;
      WORD Reserved2;
      DWORD DataOffset;
      WORD DataSelector;
      WORD Reserved3;
      DWORD MxCsr;
      DWORD MxCsr_Mask;
      _BinRun.M128A FloatRegisters[8];
      _BinRun.M128A XmmRegisters[16];
      BYTE Reserved4[96];
  )"
  ,CONTEXT64:="
  (
      DWORD64 P1Home;
      DWORD64 P2Home;
      DWORD64 P3Home;
      DWORD64 P4Home;
      DWORD64 P5Home;
      DWORD64 P6Home;
      DWORD ContextFlags;
      DWORD MxCsr;
      WORD SegCs;      
      WORD SegDs;      
      WORD SegEs;      
      WORD SegFs;      
      WORD SegGs;      
      WORD SegSs;      
      DWORD EFlags;    
      DWORD64 Dr0;     
      DWORD64 Dr1;     
      DWORD64 Dr2;     
      DWORD64 Dr3;     
      DWORD64 Dr6;     
      DWORD64 Dr7;     
      DWORD64 Rax;     
      DWORD64 Rcx;     
      DWORD64 Rdx;     
      DWORD64 Rbx;     
      DWORD64 Rsp;     
      DWORD64 Rbp;     
      DWORD64 Rsi;     
      DWORD64 Rdi;     
      DWORD64 R8;      
      DWORD64 R9;      
      DWORD64 R10;     
      DWORD64 R11;     
      DWORD64 R12;     
      DWORD64 R13;     
      DWORD64 R14;     
      DWORD64 R15;     
      DWORD64 Rip;     
      union {
          _BinRun._XMM_SAVE_AREA32 FltSave; 
          struct {
              _BinRun.M128A Header[2];     
              _BinRun.M128A Legacy[8];     
              _BinRun.M128A Xmm0;          
              _BinRun.M128A Xmm1;          
              _BinRun.M128A Xmm2;          
              _BinRun.M128A Xmm3;          
              _BinRun.M128A Xmm4;          
              _BinRun.M128A Xmm5;          
              _BinRun.M128A Xmm6;          
              _BinRun.M128A Xmm7;          
              _BinRun.M128A Xmm8;          
              _BinRun.M128A Xmm9;          
              _BinRun.M128A Xmm10;         
              _BinRun.M128A Xmm11;         
              _BinRun.M128A Xmm12;         
              _BinRun.M128A Xmm13;         
              _BinRun.M128A Xmm14;         
              _BinRun.M128A Xmm15;         
          };
      };
      _BinRun.M128A VectorRegister[26];    
      DWORD64 VectorControl;       
      DWORD64 DebugControl;        
      DWORD64 LastBranchToRip;     
      DWORD64 LastBranchFromRip;   
      DWORD64 LastExceptionToRip;  
      DWORD64 LastExceptionFromRip;
  )"
  ,CONTEXT32:="
  (
    DWORD ContextFlags;
    DWORD   Dr0;
    DWORD   Dr1;
    DWORD   Dr2;
    DWORD   Dr3;
    DWORD   Dr6;
    DWORD   Dr7;
    _BinRun.FLOATING_SAVE_AREA FloatSave;
    DWORD   SegGs;
    DWORD   SegFs;
    DWORD   SegEs;
    DWORD   SegDs;
    DWORD   Edi;
    DWORD   Esi;
    DWORD   Ebx;
    DWORD   Edx;
    DWORD   Ecx;
    DWORD   Eax;
    DWORD   Ebp;
    DWORD   Eip;
    DWORD   SegCs;              // MUST BE SANITIZED
    DWORD   EFlags;             // MUST BE SANITIZED
    DWORD   Esp;
    DWORD   SegSs;
    BYTE    ExtendedRegisters[512]; // MAXIMUM_SUPPORTED_EXTENSION
  )"
  __New(pData,cmdLine="",cmdLineScript="",Hide=0,ExeToUse=""){
    static IMAGE_NT_SIGNATURE:=17744,IMAGE_DOS_SIGNATURE:=23117,PAGE_EXECUTE_READWRITE:=64,CREATE_SUSPENDED:=4
    static MEM_COMMIT:=4096,MEM_RESERVE:=8192,STARTF_USESHOWWINDOW:=1
    If pData
      If pData is not digit
      {	
        ; Try first reading the file from Resource
        If res := DllCall("FindResource","PTR",lib:=DllCall("GetModuleHandle","PTR",0,"PTR"),"Str",pData,"PTR",10,"PTR")
          VarSetCapacity(data,sz :=DllCall("SizeofResource","PTR",lib,"PTR",res))
          ,DllCall("RtlMoveMemory","PTR",&data,"PTR",DllCall("LockResource","PTR",hres:=DllCall("LoadResource","PTR",lib,"PTR",res,"PTR"),"PTR"),"PTR",sz)
          ,DllCall("FreeResource","PTR",hres)
          ,BinRun_Uncompress(data)
        else ; else try reading file from disc etc...
          FileRead,Data,*c %pData%
        pData:=&Data
      }
    
    If InStr(cmdLine,"`n"){ ; a script was given, first line contains the cmdLine
      PipeName := "\\.\pipe\AHK" A_TickCount
      __PIPE_GA_ := DllCall("CreateNamedPipe","str",PipeName,"UInt",2,"UInt",0,"UInt",255,"UInt",0,"UInt",0,"PTR",0,"PTR",0)
      __PIPE_    := DllCall("CreateNamedPipe","str",PipeName,"UInt",2,"UInt",0,"UInt",255,"UInt",0,"UInt",0,"PTR",0,"PTR",0)
      if (__PIPE_=-1 or __PIPE_GA_=-1)
        Return 0
      Script:=(A_IsUnicode ? chr(0xfeff) : (chr(239) . chr(187) . chr(191))) SubStr(cmdLine,InStr(cmdLine,"`n")+1)
      cmdLine:=Trim(SubStr(cmdLine,1,InStr(cmdLine,"`n")),"`n`r") A_Space PipeName
    }
  
    IDH:=new _Struct(_BinRun.IMAGE_DOS_HEADER,pData)
    if (IDH.e_magic != IMAGE_DOS_SIGNATURE){
      MsgBox ERROR: e_magic not found
      return
    }
    INH := new _Struct(_BinRun.IMAGE_NT_HEADERS,pData + IDH.e_lfanew)
    
    if (INH.Signature != IMAGE_NT_SIGNATURE){
      MsgBox ERROR: Signature not found
      return
    }

    
    If (A_PtrSize=8&&INH.OptionalHeader.magic=267) ; x86 on x64
      pNtHeader:=new _Struct(_BinRun.IMAGE_NT_HEADERS32,pData + IDH.e_lfanew),ctx:=new _Struct(_BinRun.Context32),Force32Bit:=1
      ,ctx.ContextFlags := (A_PtrSize=8?0x100000:0x10000) | 0x2 ;CONTEXT_INTEGER
      ,UsedExe:=ExeToUse?ExeToUse:A_WinDir "\Microsoft.NET\Framework\v2.0.50727\vbc.exe"
    else if (A_PtrSize=4&&INH.OptionalHeader.magic=523) ; x64 on x86 not possible
      Return false
    else 
      pNtHeader:=INH,UsedExe:=ExeToUse?ExeToUse:A_IsCompiled?A_ScriptFullPath:A_AhkPath
      ,ctx:=new _Struct(A_PtrSize=8?_BinRun.Context64:_BinRun.Context32),ctx.ContextFlags := (A_PtrSize=8?0x100000:0x10000) | 0x2 ;CONTEXT_INTEGER
    pi:=new _Struct(_BinRun.PROCESS_INFORMATION)
    si:=new _Struct(_BinRun.STARTUPINFO),si.cb:=sizeof(si),si.dwFlags:=HIDE?STARTF_USESHOWWINDOW:0 ;si.wShowWindow already set to 0
    if DllCall("CreateProcess","PTR",0,"STR","""" UsedExe """" A_Space cmdLine (cmdLineScript?A_Space cmdLineScript:"")
              ,"PTR",0,"PTR",0,"int",0,"Int",CREATE_SUSPENDED,"PTR",0,"PTR",0,"PTR",si[],"PTR",pi[]){
        if DllCall((Force32Bit?"Wow64":"") "GetThreadContext","PTR",pi.hThread,"PTR", ctx[]){
            pPebImageBase:=ctx[A_PtrSize=8&&!Force32Bit?"Rdx":"Ebx"] + (Force32Bit?4:A_PtrSize)*2
            if DllCall("ReadProcessMemory","PTR",pi.hProcess, "PTR", pPebImageBase,"PTR*", dwImagebase,"PTR", (Force32Bit?4:A_PtrSize),"Uint*",NumberOfBytes){
                DllCall("ntdll\NtUnmapViewOfSection","PTR",pi.hProcess, "PTR",dwImagebase)
                pImagebase := DllCall("VirtualAllocEx","PTR",pi.hProcess, "PTR",pNtHeader.OptionalHeader.ImageBase, "PTR",pNtHeader.OptionalHeader.SizeOfImage,"UInt", MEM_COMMIT|MEM_RESERVE,"UInt", PAGE_EXECUTE_READWRITE,"PTR")
                if (pImagebase)
                {
                    if DllCall("WriteProcessMemory","PTR",pi.hProcess,"PTR",pImagebase,"PTR",pData,"PTR",pNtHeader.OptionalHeader.SizeOfHeaders,"UInt*",NumberOfBytes){
                        pSecHeader :=new _Struct(_BinRun.IMAGE_SECTION_HEADER)
                        pSecHeader[] :=pNtHeader.OptionalHeader[""]+pNtHeader.FileHeader.SizeOfOptionalHeader
                        counter := 0
                        while (++counter < pNtHeader.FileHeader.NumberOfSections+1){
                            DllCall("WriteProcessMemory","PTR",pi.hProcess,"PTR",pImagebase + pSecHeader.VirtualAddress,"PTR",pData + pSecHeader.PointerToRawData,"PTR",pSecHeader.SizeOfRawData,"UInt*", NumberOfBytes)
                            pSecHeader[]:=pSecHeader[]+sizeof(pSecHeader)
                        }
                        if DllCall("WriteProcessMemory","PTR",pi.hProcess,"PTR",pPebImageBase,"PTR",pNtHeader.OptionalHeader.ImageBase[""],"PTR",(Force32Bit?4:A_PtrSize),"UInt*",NumberOfBytes){
                            ctx[A_PtrSize=8&&!Force32Bit?"Rcx":"Eax"] := pImagebase + pNtHeader.OptionalHeader.AddressOfEntryPoint
                            if DllCall((Force32Bit?"Wow64":"") "SetThreadContext","PTR",pi.hThread, "PTR",ctx[]){
                                if DllCall("ResumeThread","PTR",pi.hThread){
                                  if (Script){ ; use pipe to pass script to new executable
                                    DllCall("ConnectNamedPipe","PTR",__PIPE_GA_,"PTR",0)
                                    DllCall("CloseHandle","PTR",__PIPE_GA_)
                                    DllCall("ConnectNamedPipe","PTR",__PIPE_,"PTR",0)
                                    if !DllCall("WriteFile","PTR",__PIPE_,"str",script,"UInt",(StrLen(script)+1)*(A_IsUnicode ? 2 : 1),"UInt*",0,"PTR",0)
                                    Return DllCall("CloseHandle","PTR",__PIPE_),0
                                    DllCall("CloseHandle","PTR",__PIPE_)
                                  }
                                  return pi.dwProcessId
                                }
                            }
                        }
                    }
                }
            }
        }
        DllCall("TerminateProcess","PTR",pi.hProcess,"UInt", 0)
    }
    return FALSE
  }
}
BinRun(pData,cmdLine="",cmdLineScript="",Hide=0,ExeToUse=""){
  return new _BinRun(pData,cmdLine,cmdLineScript,Hide,ExeToUse)
}
BinRun_Uncompress( ByRef D ) {  ; Shortcode version of VarZ_Decompress() of VarZ 2.0 wrapper
; VarZ 2.0 by SKAN, 27-Sep-2012. http://www.autohotkey.com/community/viewtopic.php?t=45559
 IfNotEqual, A_Tab, % ID:=NumGet(D,"UInt"), IfNotEqual, ID, 0x5F5A4C,  Return 0, ErrorLevel := -1
 savedHash := NumGet(D,4,"UInt"), TZ := NumGet(D,10,"UInt"), DZ := NumGet(D,14,"UInt")
 DllCall( "shlwapi\HashData", UInt,&D+8, UInt,DZ+10, UIntP,Hash, UInt,4 )
 IfNotEqual, Hash, %savedHash%, Return 0, ErrorLevel := -2
 VarSetCapacity( TD,TZ,0 ), NTSTATUS := DllCall( "ntdll\RtlDecompressBuffer", UShort
 , NumGet(D,8,"UShort"), PTR, &TD, UInt,TZ, PTR,&D+18, UInt,DZ, UIntP,Final, UInt )
 IfNotEqual, NTSTATUS, 0, Return 0, ErrorLevel := NTSTATUS
 VarSetCapacity( D,Final,0 ), DllCall( "RtlMoveMemory", PTR,&D, PTR,&TD, PTR,Final )
 If NumGet(D,"UInt")=0x315F5A4C && NumPut(0x005F5A4C,D,"UInt")
  Return BinRun_Uncompress( D )
Return Final, VarSetCapacity( D,-1 )
}