Ascend4nt

Process + Thread + DLL Functions UDFs

44 posts in this topic

#1 ·  Posted (edited)

Process + Thread + DLL Functions UDFs

Posted Image Posted Image

Fully tested on O/S's from Windows 2000 -> Windows 7, in both 32-bit and 64-bit modes.

*Note: the dropdown box in the GUI has issues in Windows 2000 - workaround - type 1st letter of process.

Also, RemoteThreads may not start if Terminal Services is not installed on Win2000.

This is a compilation of all my Process, Thread, and DLL functions (and now Driver functions) into a number of UDF modules. Most every and anything useful can be done with these functions. The best part is the GUI interfaces (ProcessFunctionsTest, ThreadFunctionsTest) which let you experiment with what functions do without even touching a line of code. And whats that? Oh yes - it creates Threads. Even 'Wow64' threads, which requires a new way of thinking =)

Bundled with the core Process, Thread, and DLL UDF's are numerous support functions, examples, and even a DLL Injection module. A comparison program 'ProcessListPropertiesTest' is also included for comparison against PsaltyDS's _ProcessListProperties UDF).

The GUI's pictured above are the best way to explore the possible uses of the Process + Thread functions included, but the functionality extends beyond those default function calls. For example, there are more filters for the 'List' functions, plus other functionality that is not exposed in the GUI examples. There's also the DLL Functions which aren't even touched on (but are made use of nonetheless).

*For another example use of the Process Functions UDF see the ProcessGetWinPEImportExports UDF.

Below is a list of all the functions available (check the function headers for more info):

ProcessFunctions UDF's

_ProcessFunctions.au3

; General Functions:
;   _ProcessOpen()          ; Open a handle to a Process(). Also returns ProcessID# in @extended
;   _ProcessCloseHandle()   ; Close the handle of a Process opened with _ProcessOpen()
;   _ProcessGetPID()        ; Given a Process handle, returns the Process ID#. Not necessary for properly written code.
;   _ProcessGetExitCode()   ; Get exit code for a Process that has terminated
;   _ProcessIsWow64()       ; Returns True if Process being accessed is running in 32-bit mode on an x64 O/S
;   _ProcessGetPriorityX()  ; Gets the Process Priority Class. 'X' tacked on due to name conflict with _ProcessGetPriority()
;   _ProcessSetPriorityX()  ; Sets the Process's Priority Class. 'X' tacked on to keep consistent with above function.
;   _ProcessGetAffinityMask() ; Gets the Affinity Mask for the given Process. Also returns the current System Affinity mask
;   _ProcessSetAffinityMask() ; Sets the Affinity Mask for the given Process.
;   _ProcessGetTimes()      ; Returns Process Creation, Exit, Kernel/User-mode Times [<_WinTimeFunctions.au3> is helpful here)
;   _ProcessGetSessionID()  ; Returns Session ID # for a given ProcessID #. May be restrictions based on Privilege level.
;   _ProcessGetOwner()      ; Returns the Owner/'User Name' for a given Process.
;   _ProcessGetHandleCount(); Returns the # of open handles for a given Process
;   _ProcessGetIOCounters() ; Returns information on I/O Counters (read/write operation counts and bytes) for given Process
;   _ProcessGetGUIResources(); Returns the # of GDI or 'USER' Objects for a given Process
;   _ProcessGetFilename() ; Returns the process name based on Process handle (Win2000 and XP/2003+ dual support)
;   _ProcessGetFilenameByPID() ; Returns the process name based on Process ID#
;   _ProcessGetPathname() ; Returns the full Pathname for a given Process handle (chooses 1 of 3 different API calls).
;                    ; NOTE: Due to issues with 'device name' returns on XP & 2003 versions, this may call 2 internal funcs
;   _ProcessWaitForInputIdle()  ; Waits for a Process with a GUI to become ready to receive input on startup.
;
; Memory Functions:
;   _ProcessGetMemInfo()            ; Returns information on Memory usage of the Process
;   _ProcessEmptyWorkingSet()       ; Flushes non-essential memory of a Process to the Pagefile
;   _ProcessMemoryRead()            ; Read from a Process's memory
;   _ProcessMemoryReadSimple()  ; Read simple datatype from a Process's memory
;   _ProcessMemoryWrite()           ; Write to a Process's memory
;   _ProcessMemoryWriteSimple() ; Write simple datatype to a Process's memory
;   _ProcessMemoryAlloc()           ; Allocates memory for a given Process (mostly same as _MemVirtualAllocEx)
;   _ProcessMemoryFree()            ; Frees memory allocated with _ProcessMemoryAlloc() (mostly same as _MemVirtualFreeEx)
;   _ProcessMemoryVirtualQuery()    ; Retrieves various info on the Process's memory where a given address is located
;   _ProcessMemoryVirtualProtect()  ; Alters the protection type of a Process's memory
;
; Termination Function:
;   _ProcessTerminate()     ; Terminates the given Process (with optional exit code)
;
; Extra Wrapper Functions:
;   _ProcessIs32Bit()       ; Returns True if Process is 32-bit (makes _ProcessIsWow64() use more simpler)
;   _ProcessIs64Bit()       ; Returns True if Process is 64-bit (makes _ProcessIsWow64() use more simpler)

_ProcessListFunctions.au3

; List/Enumeration Functions (all but 2 functions here utilize CreateToolHelp32Snapshot):
;   _ProcessListEx()        ; Get a List of Processes with extended info (like ProcessList but with Parent PID, etc)
;   _ProcessListWTS()       ; Get a List of Processes like ProcessList, with extra info: Session ID and Owner/'User Name' info
;   _ProcessListHeaps()     ; Get a List of Heap information for a Process (with optional Heap-walking)
;   _ProcessListThreads()   ; Get a List of Threads for *all* processes, or filtered for a select Process
;   _ProcessListModules()   ; Get a List of Module for a Process (with Filtering options)
;                           ; NOTE: Getting 32-bit Modules in addition to 64-bit modules may cause the main EXE to be listed twice
;                           ; (at the start of the 32-bit Modules list). This generally only happens when probing 32-bit Processes.
;   _ProcessWinList()       ; Get a List of Window handles belonging to a Process, with filter options
;   _ProcessesWinList()   ; List of Window handles belonging to Processes [i]plural[/i]
;
; Extra Wrapper Functions:
;   _ProcessGetChildren()   ; Returns child process(es) info for given process (utilizes _ProcessListEx())
;   _ProcessGetParent()     ; Returns parent process information for given process (utilizes _ProcessListEx())
;   _ProcessGetModuleBaseAddress()  ; Returns the Base address for the Module in the given process (utilizes _ProcessListModules())
;                                   ; NOTE that the process name itself is also a module, so its address can also be looked up
;   _ProcessGetModuleByAddress()    ; Returns module info for the module that contains the given address.

_ProcessUndocumented.au3

; Main Functions:
;   _ProcessUDGetStrings()      ; Retrieves Command Line, Current Directory, Invokation method, Environment, etc strings.
;   _ProcessUDGetPID()          ; Retrieves the Process ID for a given Process handle. Unnecessary for properly written code.
;   _ProcessUDGetParentPID()    ; Retrieves the Parent Process ID for a given Process - fastest method!
;   _ProcessUDGetSessionID()    ; Retrieves the Session ID for a given Process (uses Process *Handles* vs the standard API call)
;   _ProcessUDGetHandleCount()  ; Retrieves count of open handles for a Process
;
; Memory Functions:
;   _ProcessUDGetMemInfo()  ; Returns information on Memory usage of the Process
;                           ; (Virtual Size elements are what distinguish this call from _ProcessGetMemInfo())
;   _ProcessUDGetHeaps()    ; Returns an array of Process heaps (base pointers)
;
; Misc. Functions:
;   _ProcessUDGetSubSystemInfo()    ; Returns the Image SubSystem type for the Process.
;                                   ; Typical returns: 1 (Native System Process), 2 (GUI), 3 (CUI)
;
; Suspend/Resume Functions:
;   _ProcessUDSuspend()     ; Suspends the given Process (or increments Suspend count)
;   _ProcessUDResume()      ; Resumes the given Process (or decrements the Suspend count)

_ProcessUndocumentedList.au3

; Main Function(s):
;   _ProcessUDListEverything()  ; Gets basically anything and everything for every running Process and it's threads
;                               ; Big advantage of this is no special privileges or administrative mode required,
;                               ; and works from 32->64 bit Processes.
;                               ; (inspired by Manko's _WinAPI_ThreadsnProcesses module)
;   _ProcessUDListModules()     ; Get a List of Module for a Process (with Filtering options), using 'undocumented' functions.
;                               ; NOTE: 32-bit code can not get modules for 64-bit Processes, and 64-bit code can not
;                               ;   get 32-bit modules for 32-bit Processes (it will only return 64-bit Wow64 module info)
;
; Wrapper Functions:
;   _ProcessUDIsSuspended()         ; Uses _ProcessUDListEverything() in determining if a specific Process is Suspended
;   _ProcessUDGetModuleBaseAddress(); Returns the Base address for the Module in the given Process (utilizes _ProcessUDListModules())
;                                   ; NOTE that the process name itself is also a module, so its address can also be looked up
;   _ProcessUDGetModuleByAddress()  ; Returns module info for the module that contains the given address.

_ProcessCreateRemoteThread.au3

; Functions:
;   _ProcessCreateRemoteThread()    ; create a Thread in another Process

_ProcessCreateRemoteThreadStub.au3

; Functions:
;   _ProcessGenerateThreadStub()    ; Creates the binary code for a Thread Stub, but doesn't inject it
;   _ProcessCreateRemoteThreadStub(); Creates a remote Thread Stub, injects it, and returns a pointer to it
;                                   ; NOTE that this *MUST* be destroyed AFTER the Thread has terminated, and
;                                   ; *BEFORE* program Exit. It will not free itself on its own.
;   _ProcessDestroyRemoteThreadStub()   ; Destroys the Remote Stub created by _ProcessCreateRemoteThreadStub()
;                                       ; As above, note that this MUST be done AFTER Thread termination

_ProcessDLLProcFunctions.au3

; Functions:
;   _ProcessGetProcAddresses()  ; Returns pointers to base DLL & functions in an external Process
;   _ProcessGetProcAddress()    ; Returns a single pointer to a function in an external Process (@extended=Base DLL)

_ProcessUDGetPEB.au3

; Functions:
;   _ProcessUDGetPEB()  ; Returns the full PEB structure for a Process (fully defined in the UDF)

Thread Functions UDF's

_ThreadFunctions.au3

; Functions:
;   _ThreadOpen()           ; Opens a handle to a Thread.
;   _ThreadGetCurrentID()   ; Gets the current Thread ID #
;   _ThreadCreate()         ; Creates a Thread for the current process and returns a handle to it (@extended = Thread ID#)
;   _ThreadGetThreadID()    ; Returns Thread ID given a Thread handle. Vista/2008+ req'd. Not necessary for properly written code.
;   _ThreadGetProcessID()   ; Returns Process ID given a Thread handle. Vista/2008+ req'd.
;   _ThreadGetPriority()    ; Gets the Thread priority
;   _ThreadSetPriority()    ; Sets the Thread priority.
;   _ThreadGetAffinityMask() ; Wrapper for _ThreadSetAffinityMask() that quickly sets a thread's affinity to a value (default = 1)
;                           ; and back to its original affinity state again.
;                           ; NOTE that the better/safer method would be to pass _ProcessGetAffinityMask() as 2nd param
;                           ; and even BETTER - use the 'Undocumented' function _ThreadUDGetAffinityMask()
;   _ThreadSetAffinityMask() ; Sets the Affinity Mask for the given Thread. Returns previous Affinity Mask in @extended
;   _ThreadGetTimes()       ; Returns Thread Creation, Exit, Kernel/User-mode Times [<_WinTimeFunctions.au3> is helpful here)
;   _ThreadWaitForExit()    ; Waits for a Thread to exit, with optional Timeout
;   _ThreadStillActive()    ; Checks to see if a Thread is still active (running)
;   _ThreadGetExitCode()    ; Gets the exit code of a Thread that has terminated.
;                           ; NOTE: 0x103 may mean 'still active' if not a possible exit code.
;                           ; Use _ThreadWaitForExit or _ThreadStillActive to make sure
;   _ThreadSuspend()        ; Suspends a given Thread, or increases the 'suspend count'
;   _ThreadWow64Suspend()   ; "" "", but for 32-bit threads running on a 64-bit O/S (Vista/2008+ only)
;                           ; NOTE: in testing, works same as _ThreadSuspend() for both 32-bit and 64-bit processes!
;   _ThreadResume()         ; Resumes a given Thread, or decreases the 'suspend count' if >1
;   _ThreadTerminate()      ; Terminates a Thread. *** NOT RECOMMENDED ***
;                           ; Use only as a last resort, or if certain that terminating the Thread won't have repercussions.
;   _ThreadCloseHandle()    ; Closes a Thread handle (and invalidates it)
;   _ThreadGetWinThreadID() ; Returns the Thread ID # that Created the given Window (also returns Process ID# in @extended)

_ThreadListFunctions.au3

; Wrapper Functions:
;   _ThreadList()       ; just a simple wrapper for _ProcessListThreads()
;   _ThreadExists()     ; uses _ProcessListThreads() to determine if a Thread # exists

_ThreadUndocumented.au3

; Main Functions:
;   _ThreadUDGetThreadID()      ; Retrieves the Thread ID for a given Thread handle. Unneccessary for properly written code.
;   _ThreadUDGetProcessID()     ; Retrieves the Process ID for a given Thread.
;   _ThreadUDGetAffinityMask()  ; Retrieves the Affinity Mask for a given Thread.
;   _ThreadUDGetStartAddress()  ; Retrieves the Start Address of the given Thread
;
; Wrapper Functions:
;   _ThreadUDIsWow64()          ; Determines if the Thread is running in Wow64 (needs Process functions to Query this)
;
; Extra Wrapper Functions:
;   _ThreadUDIs32Bit()      ; Returns True if Thread is 32-bit (makes _ThreadUDIsWow64() use more simpler)
;   _ThreadUDIs64Bit()      ; Returns True if Thread is 64-bit (makes _ThreadUDIsWow64() use more simpler)

_ThreadUndocumentedList.au3

; Main (Wrapper) Functions:
;   _ThreadUDIsSuspended()      ; Returns True/False if a given Thread ID is Suspended.
;                               ; NOTE: It is recommended to call this function with a Process ID as well
;                               ;   Additionally: This function will increase the size of stripped Obfuscated code
;                               ; due to additional functions it includes as options to getting the Process ID #

_ThreadUDGetTEB.au3

; Functions:
;   _ThreadUDGetTEB()   ; Returns the full TEB/TIB structure for a Thread (fully defined in UDF)

_ThreadContext.au3

; Functions:
;   _ThreadGetContext()         ; Returns a Context structure for the given Thread
;   _ThreadGetWow64Context()    ; '' same - but for 32-bit Processes on a 64-bit O/S
;   _ThreadSetContext()         ; Changes the Context for a Thread based on the given structure
;   _ThreadSetWow64Context()    ; '' same - but for 32-bit Processes on a 64-bit O/S

DLL Functions UDF's

_DLLFunctions.au3

; Already-Loaded DLL/Main .EXE Functions:
;   _DLL_GetLoadedLibraryHandle()   ; Gets the handle for an already-loaded DLL (or base .EXE)
;   _DLL_GetModuleFilename()        ; Gets the full pathname for the given DLL handle
;   _DLL_ForcePermanentLoad()       ; Forces the given DLL to be permanently loaded (handle, address, or string allowed)
;                                   ; XP/2003+ O/S required
;   _DLL_GetHandleFromAddress()     ; Gets the base DLL or main .EXE module handle from a given address
;                                   ; XP/2003+ O/S required (there is an alternative in _ProcessListFunctions.au3 though)
;
; Main DLL Load/Get-Address Functions:
;   _DLL_LoadLibrary()      ; Loads a DLL (or increments DLL-load count), returns a handle to it
;   _DLL_FreeLibrary()      ; Frees/Releases the DLL (and memory) as loaded by _DLL_LoadLibrary()
;                           ; (or decrements DLL-load count)
;   _DLL_GetProcAddress()   ; Returns a pointer to the procedure address of a function within the given DLL
;
; Wrapper Functions:
;   _DLL_GetBaseAndProcAddresses()  ; Gets the Base DLL address and the address of any # of passed functions
;                                   ; (Loading/Freeing [if needed] of DLL is handled within.)
;   _DLL_GetBaseAndProcAddress()    ; Gets the Base DLL address and a single function address
;                                   ; (uses _DLL_GetBaseAndProcAddresses)

_DLLInjection.au3

; Functions:
;   _DLLInject()    ; Injects a DLL into the given Process
;   _DLLUnInject()  ; UnInjects (or decrements ref. count) of a DLL in given Process

DriverList.au3 UDF:

; _DriverList() ; Returns a list of Drivers that were loaded by the O/S

This is now a very comprehensive suite. Most everything a programmer or user would find useful is included. If by chance you can think of *any* other (useful) functions to add to this project, however, let me know.

For those that need to measure a Process's CPU Usage, please see my PDH Performance Counters UDF, another comprehensive UDF suite.

Special note: For most all _Process* functions that require a 'QUERY' info handle, use the constant $PROCESS_QUERY_LIMITED_INFO, which is set based on O/S. There's only one exception to this that I can think of: _ProcessMemoryVirtualQuery() which requires full Query access no matter what O/S (0x400). Thread* functions can make use of 2 constants which are set based on O/S - $THREAD_QUERY_LIMITED_INFO and $THREAD_SET_LIMITED_INFO. Experiment with the GUI's on Vista+ O/S's to see what's the minimum req's.

Download the Source and/or GUI Exe's from my site

Optional addition: Special NomadMemory UDF designed to work with ProcessFunctions:

NomadMemoryPF.au3

Ascend4nt's AutoIT Code License agreement:

While I provide this source code freely, if you do use the code in your projects, all I ask is that:

  • If you provide source, keep the header as I have put it, OR, if you expand it, then at least acknowledge me as the original author, and any other authors I credit
  • If the program is released, acknowledge me in your credits (it doesn't have to state which functions came from me, though again if the source is provided - see #1)
  • The source on it's own (as opposed to part of a project) can not be posted unless a link to the page(s) where the code were retrieved from is provided and a message stating that the latest updates will be available on the page(s) linked to.
  • Pieces of the code can however be discussed on the threads where Ascend4nt has posted the code without worrying about further linking.
UPDATES:

6/8/2011:

New:

  • _ProcessUDGetPEB.au3, _ThreadUDGetTEB.au3 -> both return fully filled out Structures for PEB or TEB
  • _ThreadContext.au3 - yes, I decided to add it in. There's some usefulness from a debug/inspection standpoint
  • _DriverList.au3 - Returns information about drivers loaded by the O/S (which don't show up in process lists!)
Added:
  • _ProcessesWinList() - multiple processes with the same name? This will get all the windows (_ProcessListFunctions UDF)
  • Functions for new modules: _ProcessUDGetPEB, _ThreadUDGetTEB, _ThreadGetContext, _ThreadGetWow64Context,

    _ThreadSetContext, _ThreadSetWow64Context, _DriverList

  • New examples: ProcessMemoryReducer.au3, DriverList.au3, DLLInjectionExample (stripped out of the _DLLInjection UDF)
  • Support modules for the GUI's
Changed:
  • Most 'List' functions now allow an 'everything that does NOT match criteria' flag [+8] (excludes matches)
  • Misc. tweaks in certain UDF's: slimmed code, pointers to Process memory can be numerical/string,
  • 'Test' GUI's - 'System' process is now allowed (though good luck getting much information on it). Also, new functions added, some minor fixes & tweaks.
Fixed:
  • _ProcessWinList() - 'Alt-Tab'-only windows was returning some 'non-Alt-tab' windows
  • _RemoteMsgBox() - Proper cleanup if error
9-3-2010:

Brand New:

  • _DLLFunctions.au3 - DLL/.EXE functions - Load/Free DLL, Get Base Address/Handle, Get Proc Addresses, etc
  • Complete Threads UDF's suite!!; Misc. other UDF's + a GUI and examples!
Added:
  • _ProcessWaitForInputIdle() - waits for a Process with a GUI to initialize and become ready for input.
  • _ProcessGetModuleBaseAddress() - added new parameter allowing the function to return a Wow64 module address if >1 match
  • _ProcessGetModuleByAddress() - allows one to see what module a given address belongs to
  • _ProcessUDIsSuspended() - utilizes _ProcessUDListEverything()
  • _ProcessUDListModules() - alternative to _ProcessListModules(), using undocumented functions
  • _ProcessUDGetModuleBaseAddress() - uses the above, same functionality as _ProcessGetModuleBaseAddress()
  • _ProcessUDGetModuleByAddress() - uses the above, same functionality as _ProcessGetModuleByAddress()
  • _ProcessUDGetSubSystemInfo() - determine if Process is a Native System Process, a CUI, or GUI
  • Internal function: __PFEnforcePID() - shortens/simplifies code a bit
  • _ProcessCreateRemoteThread.au3 with important new function:

    _ProcessCreateRemoteThread() - example included

  • _ProcessDLLProcFunctions.au3 - gets external Process's API Proc Addresses (and DLL Base address)
  • Precompiled&Optimized 32&64-bit Executables included.
Changed:
  • ProcessFunctionsTest updated:

    - all functions now included with full examples, PID# appended to 'Self',

    'Safety' MsgBoxes, Compiled version limited bit-mode switching (*x64.exe), and misc. small changes

    Added optimum compile mode - use this to decrease size & squeeze more performance out of the program

    - Integration with ThreadFunctionsTest GUI, reliance on some Thread functions.

  • _ProcessMemoryFree() - now takes a pointer as a reference, and if MEM_RELEASE (and successful), invalidates the pointer
Fixed:
  • TestProcessFunctions: Get SEDEBUG Privilege function) was returning True even when it failed to work
  • _ProcessUDGetStrings -> Unicode string lengths are in bytes (mistakenly assumed it was in chars) - fixed
7-3-2010:

Added:

  • _ProcessTerminate (_ProcessFunctions UDF)
  • _ProcessUDSuspend (_ProcessUndocumented UDF)*
  • _ProcessUDResume (_ProcessUndocumented UDF)*
*Win2000 w/o Service Packs does not support Process Suspend/Resume

Changed:

  • TestProcessFunctions UDF updated to use new functions
  • _ProcessListThreads array size/redimming adjusted for better performance
6-12-2010:

Added:

  • _ProcessUDGetHeaps() ; a faster way to get basic heap handle/counts
  • Example: TestProcessListProperties (for comparison with PsaltyDS's _ProcessListProperties)
  • <_ProcessUndocumentedList.au3> module, currently with only one (very important) function: _ProcessUDListEverything(). It's all in it's name, haha. This is where you can get all kinds of info about Processes on your PC without having Admin privileges or worrying about bit-modes. Inspired by Manko's _WinAPI_ThreadsnProcesses()
Changed:
  • _ProcessListThreads: Now allows the filter to be a Thread ID if 2nd param is True:

    _ProcessListThreads($vFilterID=-1,$bThreadFilter=False)

  • GUI: Added function definitions, rewording of a few things,

    _ProcessListThreads() now cycles twice - once for ALL processes, then again for selected Process

Fixed:
  • Not all returns were consistent in @error situations in <_ProcessFunctions.au3>.
6-9-2010:

Added:

  • _ProcessMemoryAlloc (same functionality as _MemVirtualAllocEx(), but using the _Process* standard call/return structure)
  • _ProcessMemoryFree (same functionality as _MemVirtualFreeEx(), '' '')
  • _ProcessMemoryVirtualQuery() - find out information regarding Process memory
  • _ProcessMemoryVirtualProtect() - alter protection type of Process memory
  • GUI: Extra functions added, extra examples.
Changed:
  • _ProcessReadMemory renamed to _ProcessMemoryRead, for consistency's sake
  • _ProcessWriteMemory renamed to _ProcessMemoryWrite, '' ''
Fixed:
  • GUI: Error in logic for certain access requirements
6-5-2010: GUI changes:
  • Made dropdown list read-only, forced auto-sort of processes (by name).
  • Changed List type of outputs to popup in listviews (using _ArrayDisplay).
  • Fixed issue if module is compiled.
  • Minor output changes.
  • Fixed access requirements missing for selected function on Windows 2000 O/S

Edited by Ascend4nt
3 people like this

Share this post


Link to post
Share on other sites



Looks massive. Gonna test it now.


[Not using this account any more. Using "iShafayet" instead]

Share this post


Link to post
Share on other sites

Share this post


Link to post
Share on other sites

Funkalicious bunch of goodies! :mellow:

/Manko


Yes i rush things! (I sorta do small bursts inbetween doing nothing.) Things I have rushed and reRushed:* ProDLLer - Process manager - Unload viri modules (dll) and moore...* _WinAPI_ProcessListOWNER_WTS() - Get Processes owner list...* _WinAPI_GetCommandLineFromPID() - Get commandline of target process...* _WinAPI_ThreadsnProcesses() Much info if expanded - optional Indented "Parent/Child"-style Processlist. Moore to come... eventually...

Share this post


Link to post
Share on other sites

Thanks everyone, hope it helps some :mellow: Any suggestions for improvements/additions are welcome.

Actually I have one thing I was thinking about the GUI interface - I should just put all those 'List' functions into _ArrayDisplay()'s, like I had originally. The only issue I thought was that it might bug people to have to constantly close those.. but now I'm just sitting there looking at the output (which sure takes it's sweet old time), and have to say it's just plain ugly and hard to read. Yeah, I think I'll have to change that behavior..

I could also allow users to input parameters for the functions, but that's just such a pain.. though I guess if enough people want it, I could come up with something..

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

Okay, since the GUI issues were bugging me, I decided to make small modifications to it:

Updates:

6-5-2010: GUI changes:

  • Made dropdown list read-only, forced auto-sort of processes (by name).
  • Changed List type of outputs to popup in listviews (using _ArrayDisplay).
  • Fixed issue if module is compiled.
  • Minor output changes.
  • Fixed access requirements missing for selected function on Windows 2000 O/S
*edit: added fix in GUI for Windows 2000 O/S's (last item). Sorry about that. Edited by Ascend4nt

Share this post


Link to post
Share on other sites

Newly Updated:

6-9-2010:

Added:

  • _ProcessMemoryAlloc (same functionality as _MemVirtualAllocEx(), but using the _Process* standard call/return structure)
  • _ProcessMemoryFree (same functionality as _MemVirtualFreeEx(), '' '')
  • _ProcessMemoryVirtualQuery() - find out information regarding Process memory
  • _ProcessMemoryVirtualProtect() - alter protection type of Process memory
  • GUI: Extra functions added, extra examples.
Changed:

  • _ProcessReadMemory renamed to _ProcessMemoryRead, for consistency's sake
  • _ProcessWriteMemory renamed to _ProcessMemoryWrite, '' ''
Fixed:

  • GUI: Error in logic for certain access requirements

Share this post


Link to post
Share on other sites

#8 ·  Posted (edited)

Updated. Awesome new _ProcessUDListEverything() function included (inspired by Manko's UDF) - see below for full changelog:

6-12-2010:

Added:

  • _ProcessUDGetHeaps() ; a faster way to get basic heap handle/counts
  • Example: TestProcessListProperties (for comparison with PsaltyDS's _ProcessListProperties)
  • <_ProcessUndocumentedList.au3> module, currently with only one (very important) function: _ProcessUDListEverything(). It's all in it's name, haha. This is where you can get all kinds of info about Processes on your PC without having Admin privileges or worrying about bit-modes. Inspired by Manko's _WinAPI_ThreadsnProcesses()
Changed:

  • _ProcessListThreads: Now allows the filter to be a Thread ID if 2nd param is True:

    _ProcessListThreads($vFilterID=-1,$bThreadFilter=False)

  • GUI: Added function definitions, rewording of a few things,

    _ProcessListThreads() now cycles twice - once for ALL processes, then again for selected Process

Fixed:

  • Not all returns were consistent in @error situations in <_ProcessFunctions.au3>.
Edited by Ascend4nt

Share this post


Link to post
Share on other sites

Wow, this is really awesome and fast as hell :mellow:

Is or will it be possible to get the CPU or Mem Usage of a process, like PsaltyDS UDF or Windows TaskManager returns it?

Share this post


Link to post
Share on other sites

#10 ·  Posted (edited)

thanks for the compliment. There's two places memory usage for a Process is available, one gives more info than the other - both can retrieve the basic 'Working Set Size' you need. Just look at a comparison of TestProcessListProperties and PsaltyDS's _ProcessListProperties (note that both need elevated privileges to return info for everything). There are a few differences in what is available, which is why I wrote the function (to show the differences). One of the shortcomings of the functions I've written is that you cannot get the command line from a 64-bit process when run in 32-bit mode (you can get this via WMI though).

Also, i covered CPU usage in the first post. Here:

Right now the only thing I can say that is truly lacking is a measure of CPU Usage - but that kind of functionality requires repeated calculations on System + Process times. My suggestion is, if you need this - either use WMI functions (unreliable in my experience), or my PDH Performance Counters UDF.

Edited by Ascend4nt

Share this post


Link to post
Share on other sites

Thanks for the fast reply :mellow:

The mem usage i figured out myself... with your great examples :P

My english isn't the best and i thought, that this function needs a lot of cpu usage. But now i will take a look at your PDH Performance Counters UDF :party:

Share this post


Link to post
Share on other sites

After tossing this around for a while, I decided I might as well fill out the Process functions UDF with Suspend, Resume, and Termination functions.

UPDATES:

7-3-2010:

Added:

  • _ProcessTerminate (_ProcessFunctions UDF)
  • _ProcessUDSuspend (_ProcessUndocumented UDF)*
  • _ProcessUDResume (_ProcessUndocumented UDF)*
*Win2000 w/o Service Packs does not support Process Suspend/Resume

Changed:

  • TestProcessFunctions UDF updated to use new functions
  • _ProcessListThreads array size/redimming adjusted for better performance

Share this post


Link to post
Share on other sites

Share this post


Link to post
Share on other sites

haha, thx KaFu. Don't know how you knew I updated the UDF before I posted about it.. ESP? :blink:

Share this post


Link to post
Share on other sites

Very nice UDF - small question.

I am using this to query for existence of a process opened by the user - it will be running on a terminal server. In my testing, it is returning "Domain Users" as the user instead of the actual user name. I assume I am missing something stupid. Here is just the snippet that matters that will return that. Additional info, yes my computer is added to the domain.

Run("cmd.exe")
$procOp = _ProcessOpen("cmd.exe", 0x20000, False)
$infoOwn = _ProcessGetOwner($procOp)
MsgBox (0, "", $infoOown)

In addition, if I get it to return the correct value, I assume I will need to query for multiple instances of a process name, load them into an array, and check each of them, right?

Thanks in advance for any help.

Share this post


Link to post
Share on other sites

#16 ·  Posted (edited)

z0iid, thats pretty interesting. The SID stuff is still a bit confusing to me, so I'm not entirely sure what's going on, or what I should be looking for. Try using a 'debug' version of _ProcessGetOwner(), like below*, and let me know what displays in the Console Output box in ScITe (You can PM me or 'censor' it if you need to keep certain things private):

*edit: code removed, if z0iid still wants help, PM me

Edited by Ascend4nt

Share this post


Link to post
Share on other sites

Well, this has been long in coming. But the wait was well worth it, I assure you ;).

I've now tackled just about everything I want to with Processes, Threads (new), and DLL (new) functions. I've bundled special Binary code threads that work under 32-bit and 64-bit mode, as well as one for 'Wow64 mode' (injecting into a 32-bit Process from a 64-bit Process). So this is a fairly big and bold program (as far as I'm concerned :) )

The GUI's now have more features, and although the *GUI* code is messy to look at - it is very well tested. I've even put compiler directives to shrink the code down if you would like to recompile these programs (executables ARE included however - both 32 and 64-bit).

- It's not just a function playground, this here is a process manipulation suite! boo. yah -

Okay, having said all that nonsense, here's the update list:

9-3-2010:

Brand New:

  • _DLLFunctions.au3 - DLL/.EXE functions - Load/Free DLL, Get Base Address/Handle, Get Proc Addresses, etc
  • Complete Threads UDF's suite!!; Misc. other UDF's + a GUI and examples!
Added:

  • _ProcessWaitForInputIdle() - waits for a Process with a GUI to initialize and become ready for input.
  • _ProcessGetModuleBaseAddress() - added new parameter allowing the function to return a Wow64 module address if >1 match
  • _ProcessGetModuleByAddress() - allows one to see what module a given address belongs to
  • _ProcessUDIsSuspended() - utilizes _ProcessUDListEverything()
  • _ProcessUDListModules() - alternative to _ProcessListModules(), using undocumented functions
  • _ProcessUDGetModuleBaseAddress() - uses the above, same functionality as _ProcessGetModuleBaseAddress()
  • _ProcessUDGetModuleByAddress() - uses the above, same functionality as _ProcessGetModuleByAddress()
  • _ProcessUDGetSubSystemInfo() - determine if Process is a Native System Process, a CUI, or GUI
  • Internal function: __PFEnforcePID() - shortens/simplifies code a bit
  • _ProcessCreateRemoteThread.au3 with important new function:

    _ProcessCreateRemoteThread() - example included

  • _ProcessDLLProcFunctions.au3 - gets external Process's API Proc Addresses (and DLL Base address)
  • Precompiled&Optimized 32&64-bit Executables included.
Changed:

  • ProcessFunctionsTest updated:

    - all functions now included with full examples, PID# appended to 'Self',

    'Safety' MsgBoxes, Compiled version limited bit-mode switching (*x64.exe), and misc. small changes

    Added optimum compile mode - use this to decrease size & squeeze more performance out of the program

    - Integration with ThreadFunctionsTest GUI, reliance on some Thread functions.

  • _ProcessMemoryFree() - now takes a pointer as a reference, and if MEM_RELEASE (and successful), invalidates the pointer
Fixed:

  • TestProcessFunctions: Get SEDEBUG Privilege function) was returning True even when it failed to work
  • _ProcessUDGetStrings -> Unicode string lengths are in bytes (mistakenly assumed it was in chars) - fixed

Share this post


Link to post
Share on other sites

Any chance you could add reading and writing to pointers? It looks pretty simple based on the NomadMemory version. Just a loop of reading addresses it appears.

Share this post


Link to post
Share on other sites

The functionality is there, you just need to know how to use it. The GUI's give you pretty much everything you need to use this code right. The function headers are more detailed of course..

Reading/writing to a pointer is no different than reading or writing any other piece of data. However, you must make sure you have the ability to read or write to the given address (_ProcessMemoryVirtualQuery) before using the next pointer for subsequent passes of reading/writing.

You won't see me posting an example of it, because I won't be posting anything related to game cheating/hacking.

However, you reminded me - its not a bad idea to give an optional 'datatype' parameter for Read/Write functions, to make reading simple elements (like pointers) alot easier. The problem with that is certain datatypes are architecture-specific and people can easily pass the wrong # of bytes to the function (4 vs. 8 bytes for 32 and 64-bit pointers, for example). Simple enough to resolve though in the main code (one global variable can be set ala '$PTR_SIZE')... but I digress.

I've done some pointer dereferencing myself using my code, but that was in the interest of seeing where code pointers get parked after a 'Suspend'. (Suspend usually parks a thread on a 'C3' (return code), which then leads one to check the Stack for the return address, and if there's another return pointed to by that address, and so forth). Maybe a bit above people's heads, but fun stuff to do. (unfortunately I haven't included the required Context functions to do that stuff in this release.. maybe in the future if I can think of a legiit. use people might have for it)

Share this post


Link to post
Share on other sites

#20 ·  Posted (edited)

Alright, no problem. Another question: What about Reading/Writing to registers? That would be quite useful for many people. I would do it myself but I'm afraid I don't know much about how to do it in ANY language.

Edit:: I found how, but I'm not sure how to go about converting it to AutoIt. I would love to help create this if at all possible.

http://msdn.microsoft.com/en-us/library/ms679362%28VS.85%29.aspx

#include <windows.h> 
#include <process.h> 
#include <stdio.h> 
#include <assert.h> 
 
void mythreadfunc(void *data) 
{ 
... 
 
_exitthread(); 
} 
 
void changeThreadState() 
{ 
HANDLE thread = (HANDLE)_beginthread( mythreadfunc, 0, NULL ); 
CONTEXT context; 
BOOL success; 
 
SuspendThread(thread); 
 
// get context 
context.ContextFlags = (CONTEXT_FULL); 
success = GetThreadContext(thread, &context); 
assert(success); 
printf( "eax=%08X, ebx=%08X, ecx=%08X\n", 
context.Eax, context.Ebx, context.Ecx ); 
 
// change context (dangerous, can crash program) 
context.Eax = 0x1234BBBB; 
context.Ecx = 0x2468ABCD; 
success = SetThreadContext(thread, &context); 
assert(success); 
 
ResumeThread(thread); 
 
// the resumed thread should see different values of eax, and ecx 
}
Edited by darkjohn20

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Similar Content

    • ur
      By ur
      With  ProcessList ( ["name"] )  we are able to get the running process list from the local machine.
       
      Is there anyway to get the list from Remote machine, more precisely to get to know the status whether a particular application is running or not on remote machine using AutoIT?
       
      We can implement through PSList.exe, but again we need to parse the text of it to read the output.
      Is there any direct UDF in AutoIT?
    • Luigi
      By Luigi
      Greetings, someone can give a exemple, how send a error from a C#'s dll to AutoIt?
      I use this line, to send an error... but, I want get a error code In AutoIt with macro @error, it's possible?
       
      throw new ArgumentException("arquivo map não existe", "value" ); In this way, work, I know ther are error, but, @errror always is zero.
      I don't want this, I want a number as error code.
      Can you help me?
       
      Best regards
    • nss
      By nss
      Hi all,
       
      I am making a program in which I use Bass audio library (with the wrapper for autoit that I found here on forums I think) because of its support for dx effects.
      My problem, though, is that when effects as reverb or echo/delay are added, the channel length is not extended as to fit the tail of the effect, so if the file was really short, you wouldn't even hear the reverb at all.
      I've tried setting the  buffer parameter even to 60k ms, updating the channel length to 60k ms, but nothing makes it so that the effects aren't being cut off.
      I've heard that I could add silence manually to wave files by adding the chr(0) characters, but haven't had any luck doing that, either.
      What I'm doing:
      initialize bass use streamCreateFile to load the wave file with the fx flag and length parameter set to 60000 set the config buffer to 60000 use channel set fx to add dx8 reverb use channel play to play the sound use bass update to update the length to 60000  
      I even tried having only silence in one wave file and tried joining two wave files together, but that didn't work either.
       
      Any help would be very much appreciated.
    • Nareshm
      By Nareshm
      If Process exits then end process and ;Some code here {1}
       
      If Process does not exits then ; My {1} Code
    • junkew
      By junkew
      Since W8.1 (actually IE 11 with W7 will work also) microsoft has a Javascript runtime that can be called from scripting languages
      As shown in this example from C++: https://iobservable.net/blog/2013/11/12/introduction-to-jsrt/
      By loading either JSCRIPT9.DLL or CHAKRA.DLL you can embed ECMA JavaScript in your application
      And implemented here in AutoHotKey https://autohotkey.com/boards/viewtopic.php?f=6&t=5739
      Triggered by other threads: 
      https://www.autoitscript.com/forum/topic/185883-accessing-autoit-variables/ https://iobservable.net/blog/2013/11/12/introduction-to-jsrt/ https://www.autoitscript.com/forum/topic/184824-chakracore-udf-executing-javascript-in-autoit/ http://eclipsesource.com/blogs/2016/04/06/getting-started-with-microsoft-chakracore/
        This code is almost working but unfortunately not with the expected output. Someone seeing what is wrong? 
      It runs completely after fixes of DanyFirex 
       
      ;~ https://iobservable.net/blog/2013/11/ ;~ Should work on all windows versions with IE11 #AutoIt3Wrapper_UseX64=N #Region enum JsErrorCode : unsigned int Enum $JsNoError = 0, _ $JsErrorCategoryUsage = 0x10000, _ $JsErrorInvalidArgument, _ $JsErrorNullArgument, _ $JsErrorNoCurrentContext, _ $JsErrorInExceptionState, _ $JsErrorNotImplemented, _ $JsErrorWrongThread, _ $JsErrorRuntimeInUse, _ $JsErrorBadSerializedScript, _ $JsErrorInDisabledState, _ $JsErrorCannotDisableExecution, _ $JsErrorHeapEnumInProgress, _ $JsErrorArgumentNotObject, _ $JsErrorInProfileCallback, _ $JsErrorInThreadServiceCallback, _ $JsErrorCannotSerializeDebugScript, _ $JsErrorAlreadyDebuggingContext, _ $JsErrorAlreadyProfilingContext, _ $JsErrorIdleNotEnabled, _ $JsErrorCategoryEngine = 0x20000, _ $JsErrorOutOfMemory, _ $JsErrorCategoryScript = 0x30000, _ $JsErrorScriptException, _ $JsErrorScriptCompile, _ $JsErrorScriptTerminated, _ $JsErrorScriptEvalDisabled, _ $JsErrorCategoryFatal = 0x40000, _ $JsErrorFatal ;~ }JsErrorCode; #EndRegion enum JsErrorCode : unsigned int #Region typedef enum JsRuntimeVersion Enum $JsRuntimeVersion10 = 0, $JsRuntimeVersion11 = 1 #EndRegion typedef enum JsRuntimeVersion ; Create callback function. Local $hPrintf = DllCallbackRegister("_printf", "long", "ptr;bool;ptr;ushort;ptr") Local $hJSRuntime = DllOpen("c:\windows\system32\jscript9.dll") $JsRuntimeAttributeNone = 0x00000000 ;~ #RequireAdmin Example() Func Example() Local $script = "native.printf('hello world')" ;~ Local $script = "native.printf('number=%#x string=%s\n', 255, 'test')" ;~ Local $script = "(()=>{return 'Hello world!';})()" ;~ Local $script = "var x='helloworld'; return x;" ;~ Local $script = "var x=10;" & @CRLF & "var y=11;" ;~ Local $script = "(42);" ;~ Local $script = "(" & @CRLF ;~ $script=$script & "host.echo(JSON.stringify({foo:'bar'}));)" & @CRLF ;~ $script=$script & "42 // The script's result :) "& @CRLF ;~ $script=$script & ")"& @CRLF ;~ $script=$script & "class Host {"& @CRLF ;~ $script=$script & " echo(s) {"& @CRLF ;~ $script=$script & " MsgBox %s%"& @CRLF ;~ $script=$script & " }"& @CRLF ;~ $script=$script & "}"& @CRLF Local $aResult Local $runtime Local $context ;~ // Create a runtime ;~ JsCreateRuntime(JsRuntimeAttributeNone, nullptr, &runtime); $runtime = _JsCreateRuntime($JsRuntimeAttributeNone, 0, $runtime) ; ;~ // Create an execution context. ;~ JsCreateContext(runtime, &context); $context = _JsCreateContext($runtime, $context) ;~ // Now set the current execution context. ;~ JsSetCurrentContext(context); _JsSetCurrentContext($context) ; ; Get the Global object for adding stuff ;~ JsGetGlobalObject(&global); Local $global $global = _JsGetGlobalObject($global) ;~ JsPropertyIdRef nativeProp; ;~ JsGetPropertyIdFromName(L"native", &nativeProp); Local $nativeProp $nativeProp = _JsGetPropertyIdFromName("native", $nativeProp) ;~ JsValueRef nativeObj; ;~ JsCreateObject(&nativeObj); Local $nativeObj $nativeObj = _JsCreateObject($nativeObj) ;~ JsPropertyIdRef printfProp; ;~ JsGetPropertyIdFromName(L"printf", &printfProp); Local $printfProp $printfProp = _JsGetPropertyIdFromName("printf", $printfProp) ;~ JsValueRef printfFunc; ;~ JsCreateFunction(PrintFormat, nullptr, &printfFunc); Local $printfFunc $printfFunc = _JsCreateFunction(DllCallbackGetPtr($hPrintf), 0, $printfFunc) ;~ JsSetProperty(nativeObj, printfProp, printfFunc, true); _JsSetProperty($nativeObj, $printfProp, $printfFunc, True) ;~ JsSetProperty(global, nativeProp, nativeObj, true); _JsSetProperty($global, $nativeProp, $nativeObj, True) ;~ STDAPI_(JsErrorCode) JsCreateFunction( ;~ _In_ JsNativeFunction nativeFunction, ;~ _In_opt_ void *callbackState, ;~ _Out_ JsValueRef *function ;~ ); ; Get a JsValueRef for our Host object ;~ hostRef := ToJsValue(Host) ;~ $aResult=DllCall($hJSRuntime, "int","JsVariantToValue", "ptr", &variant, "ptr*", valref) ; Pass our Host object to the script engine ;~ DllCall("jscript9\JsSetProperty", "ptr", globalObject, "ptr", hostPropertyId, "ptr", hostRef, "int", true) ;~ // Run the script. ;~ STDAPI_(JsErrorCode) JsRunScript( ;~ _In_z_ const wchar_t *script, ;~ _In_ JsSourceContext sourceContext, ;~ _In_z_ const wchar_t *sourceUrl, ;~ _Out_ JsValueRef *result ;~ ); Local $currentSourceContext = 1 ;~ JsRunScript(script.c_str(), currentSourceContext++, L"", &result); Local $result = "" Local $sourceURL = "" $aResult = DllCall($hJSRuntime, "int", "JsRunScript", "WSTR", $script, "UINT*", $currentSourceContext, "wstr", "dummysource.js", "WSTR*", $result) ConsoleWrite("Error 11: " & @error & @CRLF) If @error = 0 Then ConsoleWrite($aResult[0] & ";" & $aResult[1] & ";" & $aResult[2] & ";" & $aResult[3] & ";" & $aResult[4] & @CRLF) EndIf ;~ // Convert your script result to String in JavaScript redundant if your script returns a String ;~ JsValueRef resultJSString; ;~ STDAPI_(JsErrorCode) JsConvertValueToString( ;~ _In_ JsValueRef value, ;~ _Out_ JsValueRef *stringValue ;~ ); ;~ JsConvertValueToString(result, &resultJSString); ;~ $aResult=DllCall($hJSRuntime, "int", "JsConvertValueToString", "WSTR", $script, "long", 1, "WSTR*",0, "WSTR*", $result) ;~ consolewrite("Error 4: " & @error & @CRLF) ;~ if @error=0 Then ;~ consolewrite($aResult[0] & ";" & $aResult[1] & ";" & $aResult[2] & ";" & $aResult[3] & ";" & $aResult[4] & @CRLF) ;~ EndIf ;~ ;~ // Project script result back to C++. ;~ const wchar_t *resultWC; ;~ size_t stringLength; ;~ JsStringToPointer(resultJSString, &resultWC, &stringLength); ;~ wstring resultW(resultWC); ;~ cout << string(resultW.begin(), resultW.end()) << endl; ;~ system("pause"); ;~ // Dispose runtime ;~ JsSetCurrentContext(JS_INVALID_REFERENCE); ;~ JsDisposeRuntime(runtime); Return 0 ; EndFunc ;==>Example ; Create callback function. ;~ JsValueRef CALLBACK PrintFormat(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) ;~ { ;~ const wchar_t *format; ;~ size_t length; ;~ JsStringToPointer(arguments[1], &format, &length); ;~ VARIANT variant; ;~ JsValueToVariant(arguments[2], &variant); ;~ const wchar_t *str; ;~ JsStringToPointer(arguments[3], &str, &length); ;~ wprintf(format, variant.intVal, str); ;~ return JS_INVALID_REFERENCE; ;~ } ;~ typedef _Ret_maybenull_ JsValueRef (CALLBACK * JsNativeFunction)( ;~ _In_ JsValueRef callee, ;~ _In_ bool isConstructCall, ;~ _In_ JsValueRef *arguments, ;~ _In_ unsigned short argumentCount ;~ ); Func _printf($callee, $isConstructCall, $arguments, $argumentCount, $callbackState) ConsoleWrite("there we are with " & $argumentCount & " arguments" & @CRLF) Local $tArgs = DllStructCreate("ptr JsValues[" & $argumentCount & "]", $arguments) ;~ STDAPI_(JsErrorCode) JsConvertValueToString( ;~ _In_ JsValueRef value, ;~ _Out_ JsValueRef *stringValue ;~ ); ;~ JsConvertValueToString(result, &resultJSString); local $tresult $aResult=DllCall($hJSRuntime, "int", "JsConvertValueToString", "ptr", DllStructGetData($tArgs,1,2), "ptr*", $tresult) consolewrite("Error 4: " & @error & @CRLF) if @error=0 Then consolewrite( $aResult[0] & ";" & $aResult[1] & ";" & $aResult[2] & @CRLF) $tresult=$aresult[2] EndIf ;~ STDAPI_(JsErrorCode) JsValueToVariant( ;~ _In_ JsValueRef object, ;~ _Out_ VARIANT *variant ;~ ); ;~ Local $aResult = DllCall($hJSRuntime, "dword", "JsValueToVariant", "ptr", $arguments[0], "ptr*", 0) ;~ If @error Then Return SetError(3, 0, @error) ;~ If $aResult[0] <> 0 Then Return SetError(4, 0, $aResult[0]) ;~ consolewrite($aResult[2]) Local $aResult = DllCall($hJSRuntime, "dword", "JsStringToPointer", "ptr", $tResult, "ptr*", 0, "int*", 0) If @error Then Return SetError(3, 0, @error) If $aResult[0] <> 0 Then Return SetError(4, 0, $aResult[0]) Local $tString = DllStructCreate("wchar string["&$aResult[3]&"]", $aResult[2]) consolewrite("+Parameter: " & $tString.string & @CRLF) Return 0 EndFunc ;==>_printf ;~ typedef void *JsRuntimeHandle; ;~ // Create a runtime. ;~ Edge mode signature STDAPI_(JsErrorCode) JsCreateRuntime( ;~ _In_ JsRuntimeAttributes attributes, ;~ _In_opt_ JsThreadServiceCallback threadService, ;~ _Out_ JsRuntimeHandle *runtime); ;~ Legacy mode signature ;~ STDAPI_(JsErrorCode) JsCreateRuntime( ;~ _In_ JsRuntimeAttributes attributes, ;~ _In_ JsRuntimeVersion version, ;~ _In_opt_ JsThreadServiceCallback threadService, ;~ _Out_ JsRuntimeHandle *runtime ;~ ); ;~ $runtime=_JsCreateRuntime(JsRuntimeAttributeNone, 0, $runtime); Func _JsCreateRuntime($JsRuntimeAttributeNone, $JSRuntimeVersion, $runtime) $aResult = DllCall($hJSRuntime, "int", "JsCreateRuntime", "int", $JsRuntimeAttributeNone, "int", $JSRuntimeVersion, "ptr", 0, "ptr*", $runtime) If @error Then Return SetError(1, @error, 0) Return $aResult[4] EndFunc ;==>_JsCreateRuntime ;~ // Edge mode signature ;~ STDAPI_(JsErrorCode) JsCreateContext( ;~ _In_ JsRuntimeHandle runtime, ;~ _Out_ JsContextRef *newContext); ;~ // Legacy mode signature ;~ STDAPI_(JsErrorCode) JsCreateContext( ;~ _In_ JsRuntimeHandle runtime, ;~ _In_ IDebugApplication *debugApplication, ;~ _Out_ JsContextRef *newContext ;~ ); ;~ JsCreateContext(runtime, &context); Func _JsCreateContext($runtime, $context) $aResult = DllCall($hJSRuntime, "int", "JsCreateContext", "ptr", $runtime, "ptr", 0, "ptr*", $context) If @error Then Return SetError(1, @error, 0) Return $aResult[3] EndFunc ;==>_JsCreateContext ;~ STDAPI_(JsErrorCode) JsSetCurrentContext( ;~ _In_ JsContextRef context ;~ ); ;~ JsSetCurrentContext(context); Func _JsSetCurrentContext($context) $aResult = DllCall($hJSRuntime, "int", "JsSetCurrentContext", "ptr", $context) If @error Then Return SetError(1, @error, 0) Return $JsNoError EndFunc ;==>_JsSetCurrentContext ; Get the Global object for adding stuff ;~ STDAPI_(JsErrorCode) JsGetGlobalObject( ;~ _Out_ JsValueRef *globalObject ;~ ); ;~ JsValueRef global; ;~ JsGetGlobalObject(&global); Func _JsGetGlobalObject($global) $aResult = DllCall($hJSRuntime, "int", "JsGetGlobalObject", "ptr*", $global) If @error Then Return SetError(1, @error, 0) Return $aResult[1] EndFunc ;==>_JsGetGlobalObject ; Get a property ID for the name "host" ;~ STDAPI_(JsErrorCode) JsGetPropertyIdFromName( ;~ _In_z_ const wchar_t *name, ;~ _Out_ JsPropertyIdRef *propertyId ;~ ); ;~ DllCall("jscript9\JsGetPropertyIdFromName", "wstr", "host", "ptr*", hostPropertyId) ;~ local $hostPropertyID ;~ $aResult=DllCall($hJSRuntime, "int","JsGetPropertyIdFromName", "wstr", "host", "ptr*", $hostPropertyId) ;~ consolewrite("Error 5: " & @error & @CRLF) ;~ if @error=0 Then ;~ consolewrite($aResult[0] & ";" & $aResult[1] & ";" & $aResult[2] & @CRLF) ;~ EndIf ;~ JsPropertyIdRef nativeProp; ;~ JsGetPropertyIdFromName(L"native", &nativeProp); Func _JsGetPropertyIdFromName($propname, $nativeProp) $aResult = DllCall($hJSRuntime, "int", "JsGetPropertyIdFromName", "wstr", $propname, "ptr*", $nativeProp) If @error Then Return SetError(1, @error, 0) Return $aResult[2] EndFunc ;==>_JsGetPropertyIdFromName ;~ STDAPI_(JsErrorCode) JsCreateObject( ;~ _Out_ JsValueRef *object ;~ ); ;~ JsValueRef nativeObj; ;~ JsCreateObject(&nativeObj); Local $nativeObj Func _JsCreateObject($JSRTobject) $aResult = DllCall($hJSRuntime, "int", "JsCreateObject", "ptr*", $JSRTobject) If @error Then Return SetError(1, @error, 0) Return $aResult[1] EndFunc ;==>_JsCreateObject ;~ STDAPI_(JsErrorCode) JsCreateFunction( ;~ _In_ JsNativeFunction nativeFunction, ;~ _In_opt_ void *callbackState, ;~ _Out_ JsValueRef *function ;~ ); Func _JsCreateFunction($fncCallBackPtr, $callbackState, $fncVar) $aResult = DllCall($hJSRuntime, "int", "JsCreateFunction", "ptr", $fncCallBackPtr, "ptr*", $callbackState, "ptr*", $fncVar) If @error Then Return SetError(1, @error, 0) Return $aResult[3] EndFunc ;==>_JsCreateFunction ;~ JsSetProperty(nativeObj, printfProp, printfFunc, true); ;~ STDAPI_(JsErrorCode) JsSetProperty( ;~ _In_ JsValueRef object, ;~ _In_ JsPropertyIdRef propertyId, ;~ _In_ JsValueRef value, ;~ _In_ bool useStrictRules ;~ ); Func _JsSetProperty($Obj, $Prop, $Func, $val) ; $aResult = DllCall($hJSRuntime, "int", "JsSetProperty", "ptr", $Obj, "ptr", $Prop, "ptr", $Func, "int", $val) If @error Then Return SetError(1, @error, 0) EndFunc ;==>_JsSetProperty