I present the module for working with multithreading in VB6 for Standard EXE projects. This module is based on this solution with some bug fixing and the new functionality is added. The module doesn't require any additional dependencies and type libraries, works as in the IDE (all the functions work in the main thread) as in the compiled form.
To start working with the module, you need to call the Initialize function, which initializes the necessary data (it initializes the critical sections for exclusive access to the heaps of marshalinig and threads, modifies VBHeader (here is description), allocates a TLS slot for passing the parameters to the thread).
The main function of thread creation is vbCreateThread, which is an analog of the CreateThread function.
' // Create a new threadPublicFunctionvbCreateThread(ByVallpThreadAttributesAsLong,_ByValdwStackSizeAsLong,_ByVallpStartAddressAsLong,_ByVallpParameterAsLong,_ByValdwCreationFlagsAsLong,_ByReflpThreadIdAsLong,_OptionalByValbIDEInSameThreadAsBoolean=True)AsLong
The function creates a thread and calls the function passed in the lpStartAddress parameter with the lpParameter parameter. In the IDE, the call is reduced to a simple call by the pointer implemented through DispCallFunc. In the compiled form, this function works differently. Because a thread requires initialization of project-specific data and initialization of the runtime, the parameters passed to lpStartAddress and lpParameter are temporarily stored into the heap by the PrepareData function, and the thread is created in the ThreadProc function, which immediately deals with the initialization and calling of the user-defined function with the user parameter. This function creates a copy of the VBHeader structure via CreateVBHeaderCopy and changes the public variable placement data in the:
VbPublicObjectDescriptor.lpPublicBytes, VbPublicObjectDescriptor.lpStaticBytes structures (BTW it wasn't implemented in the previous version) so that global variables are not affected during initialization. Further, VBDllGetClassObject calls the FakeMain function (whose address is written to the modified VBHeader structure). To transfer user parameters, it uses a TLS slot (since Main function doesn't accept parameters, details here). In FakeMain, parameters are directly extracted from TLS and a user procedure is called. The return value of the function is also passed back through TLS. There is one interesting point related to the copy of the header that wasn't included in the previous version. Because the runtime uses the header after the thread ends (with DLL_THREAD_DETACH), we can't release the header in the ThreadProc procedure, therefore there will be a memory leak. To prevent the memory leaks, the heap of fixed size is used, the headers aren't cleared until there is a free memory in this heap. As soon as the memory ends (and it's allocated in the CreateVBHeaderCopy function), resources are cleared. The first DWORD of header actually stores the ID of the thread which it was created in and the FreeUnusedHeaders function checks all the headers in the heap. If a thread is completed, the memory is freed (although the ID can be repeated, but this doesn't play a special role, since in any case there will be a free memory in the heap and if the header isn't freed in one case, it will be released later). Due to the fact that the cleanup process can be run immediately from several threads, access to the cleanup is shared by the critical section tLockHeap.tWinApiSection and if some thread is already cleaning up the memory the function will return True which means that the calling thread should little bit waits and the memory will be available.
The another feature of the module is the ability to initialize the runtime and the project and call the callback function. This can be useful for callback functions that can be called in the context of an arbitrary thread (for example, InternetStatusCallback). To do this, use the InitCurrentThreadAndCallFunction and InitCurrentThreadAndCallFunctionIDEProc functions. The first one is used in the compiled application and takes the address of the callback function that will be called after the runtime initialization, as well as the parameter to be passed to this function. The address of the first parameter is passed to the callback procedure to refer to it in the user procedure:
' // This function is used in compiled formPublicFunctionCallbackProc(_ByVallThreadIdAsLong,_ByValsKeyAsString,_ByValfTimeFromLastTickAsSingle)AsLong' // Init runtime and call CallBackProc_user with VarPtr(lThreadId) parameterInitCurrentThreadAndCallFunctionAddressOfCallBackProc_user,VarPtr(lThreadId),CallbackProcEndFunction' // Callback function is called by runtime/window proc (in IDE)PublicFunctionCallBackProc_user(_ByReftParamAstCallbackParams)AsLongEndFunction
CallBackProc_user will be called with the initialized runtime.
This function doesn't work in the IDE because in the IDE everything works in the main thread. For debugging in the IDE the function InitCurrentThreadAndCallFunctionIDEProc is used which returns the address of the assembler thunk that translates the call to the main thread and calls the user function in the context of the main thread. This function takes the address of the user's callback function and the size of the parameters in bytes. It always passes the address of the first parameter as a parameter of a user-defined function. I'll tell you a little more about the work of this approach in the IDE. To translate a call from the calling thread to the main thread it uses a message-only window. This window is created by calling the InitializeMessageWindow function. The first call creates a WindowProc procedure with the following code:
As you can see from the code, this procedure "listens" to the WM_ONCALLBACK message which contains the parameter wParam - the function address, and in the lParam parameters. Upon receiving this message it calls this procedure with this parameter, the remaining messages are ignored. This message is sent just by the assembler thunk from the caller thread. Futher, a window is created and the handle of this window and the code heap are stored into the data of the window class. This is used to avoid a memory leak in the IDE because if the window class is registered once, then these parameters can be obtained in any debugging session. The callback function is generated in InitCurrentThreadAndCallFunctionIDEProc, but first it's checked whether the same callback procedure has already been created (in order to don't create the same thunk). The thunk has the following code:
As you can see from the code, during calling a callback function, the call is transmitted via SendMessage to the main thread. The lParametersSize parameter is used to correctly restore the stack.
The next feature of the module is the creation of objects in a separate thread, and you can create them as private objects (the method is based on the code of the NameBasedObjectFactory by firehacker module) as public ones.
To create the project classes use the CreatePrivateObjectByNameInNewThread function and for ActiveX-public classes:
CreateActiveXObjectInNewThread and CreateActiveXObjectInNewThread2 ones.
Before creating instances of the project classes you must first enable marshaling of these objects by calling the EnablePrivateMarshaling function. These functions accept the class identifier (ProgID / CLSID for ActiveX and the name for the project classes) and the interface identifier (IDispatch / Object is used by default). If the function is successfully called a marshaled object and an asynchronous call ID are returned. For the compiled version this is the ID of thread for IDE it's a pointer to the object. Objects are created and "live" in the ActiveXThreadProc function. The life of objects is controlled through the reference count (when it is equal to 1 it means only ActiveXThreadProc refers to the object and you can delete it and terminate the thread). You can call the methods either synchronously - just call the method as usual or asynchronously - using the AsynchDispMethodCall procedure. This procedure takes an asynchronous call ID, a method name, a call type, an object that receives the call notification, a notification method name and the list of parameters. The procedure copies the parameters to the temporary memory, marshals the notification object, and sends the data to the object's thread via WM_ASYNCH_CALL. It should be noted that marshaling of parameters isn't supported right now therefore it's necessary to transfer links to objects with care. If you want to marshal an object reference you should use a synchronous method to marshal the objects and then call the asynchronous method. The procedure is returned immediately. In the ActiveXThreadProc thread the data is retrieved and a synchronous call is made via MakeAsynchCall. Everything is simple, CallByName is called for the thread object and CallByName for notification. The notification method has the following prototype:
PublicSubCallBack(ByValvRetAsVariant)
, where vRet accepts the return value of the method.
The following functions are intended for marshaling:
Marshal, Marshal2, UnMarshal, FreeMarshalData. The first one creates information about the marshaling (Proxy) of the interface and puts it into the stream (IStream) that is returned. It accepts the interface identifier in the pInterface parameter (IDispatch / Object by default). The UnMarshal function, on the contrary, receives a stream and creates a Proxy object based on the information in the stream. Optionally, you can release the thread object. Marshal2 does the same thing as Marshal except that it allows you to create a Proxy object many times in different threads. FreeMarshalData releases the data and the stream accordingly. If, for example, you want to transfer a reference to an object between two threads, it is enough to call the Marshal / UnMarshal pair in the thread which created the object and in the thread that receives the link respectively. In another case, if for example there is the one global object and you need to pass a reference to it to the multiple threads (for example, the logging object), then Marshal2 is called in the object thread, and UnMarshal with the bReleaseStream parameter is set to False is called in client threads. When the data is no longer needed, FreeMarshalData is called.
The WaitForObjectThreadCompletion function is designed to wait for the completion of the object thread and receives the ID of the asynchronous call. It is desirable to call this function always at the end of the main process because an object thread can somehow interact with the main thread and its objects (for example, if the object thread has a marshal link to the interface of the main thread).
The SuspendResume function is designed to suspend/resume the object's thread; bSuspend determines whether to sleep or resume the thread.
In addition, there are also several examples in the attacment of working with module:
Callback - the project demonstrates the work with the callback-function periodically called in the different threads. Also, there is an additional project of native dll (on VB6) which calls the function periodically in the different threads;
JuliaSet - the Julia fractal generation in the several threads (user-defined);
CopyProgress - Copy the folder in a separate thread with the progress of the copy;
PublicMarshaling - Creating public objects (Dictionary) in the different threads and calling their methods (synchronously / asynchronously);
PrivateMarshaling - Creating private objects in different threads and calling their methods (synchronously / asynchronously);
MarshalUserInterface - Creating private objects in different threads and calling their methods (synchronously / asynchronously) based on user interfaces (contains tlb and Reg-Free manifest).
InitProjectContextDll - Initialization of the runtime in an ActiveX DLL and call the exported function from the different threads. Setup callbacks to the executable.
InternetStatusCallback - IternetStatusCallback usage in VB6. Async file downloading.
The module is poorly tested so bugs are possible. I would be very glad to any bug-reports, wherever possible I will correct them. Thank you all for attention!
Best Regards,
The trick.
IMPORTANT NOTE: The following screenshot appears if you chose to download this project from GitHub, using Google chrome or Edge. These browsers will say "Virus detected". There is no virus in there, is just a compiled version of this very project uploaded by his creator, namely TheTrick. Today, security "specialists" go through new heights of incompetence at the world level. All "antivirus" companies get their signatures from one place, namely VirusTotal.com. As flock of sheeps they trust what "users" say about a file (remember that in general).Antivirus companies don't have competent specialists anymore:
Hello everyone (sorry my English). There was a time, and decided to write something unusual on VB6, namely to try to write a driver. I must say before that I never wrote a driver and have no programming experience in kernel mode. The driver, according to my idea, will have to read the memory is not available in user mode, namely in the range 0x80000000 - 0xffffffff (in default mode, without IMAGE_FILE_LARGE_ADDRESS_AWARE). Immediately give the driver source code which is obtained:
So, the driver must have an entry point DriverEntry, which causes the controller I/O driver is loaded. In the parameters of a pointer to an object-driver and a pointer to a string containing the name of the registry key corresponding to the loadable driver. In the Init procedure, we create two lines, one with the name of the device, the other with reference to the device name. Because we can not use the runtime kernel mode, it is necessary to create a string in the form of a static array, wrapped in a user-defined type, thereby VB6 allocates memory for the array on the stack. If you use a string that will inevitably be caused by one of the functions for runtime and copy assignment line, and we can not allow that. Then we can call IoCreateDevice, which creates a device object. Device object is the recipient of I/O requests and to him we will access when calling CreateFile function from user mode.
The first parameter is a pointer to an object-driver; the second parameter is 0, then since we do not have the structure of the expansion device, and we do not need to allocate memory; the third parameter we pass the name of the device, it is we need to implement access to the device; fourth parameter passed to the device type (see below). in the fifth, we pass 0 as we have "non-standard device"; in the sixth pass False, because We do not need single-user mode; the last parameter - the output. As the name of the device we have to use a string like \Device\DeviceName (where DeviceName - TrickMemReader), is the name we need to ensure that we can create a link to it, which in turn need to access the device from user mode. Device type - FILE_DEVICE_MEMREADER. All non-standard devices must be of type or FILE_DEVICE_UNKNOWN, or the number of 0x8000 - 0xffff. I created FILE_DEVICE_MEMREADER constant with a value of 0x8000, which corresponds to the first free number. On success, the device is created and filled structure DEVICE_OBJECT. After the need to create a connection between the device name of the kernel mode and user mode. As the name we use \DosDevices\TrickMemReader, from user mode, we will refer to it via the link '\\.\TrickMemReader". The link is created through IoCreateSymbolicLink. Next we define callback-procedure that will be called when certain events occur:
DriverUnload - deinitialize driver;
DriverCreateClose - when opening and closing device;
DriverDeviceControl - when calling DeviceIoControl.
And So. Now we return STATUS_SUCCESS, which corresponds to the successful implementation.* Now consider the procedure DriverUnload. It's simple - we remove the connection and set up the device. In the processing functions of opening and closing device DriverCreateClose, the status of the request, we return a success, and return the IRP packet I/O manager. Exchange of data between an application and device via the IRP-packets. IRP-package consists of 2 parts: a header and a stack of variable length. Part of the structure represented by the type of IRP. So now we add functionality to our driver function DriverDeviceControl. In this function I/O Manager will send IRP-data packet transmitted from the client application, which we will generate a call to DeviceIoControl. The parameters we pass 2 Long numbers: 1st address, where produce reading, 2nd number of bytes to read. Also one of the parameters passed to IRP-bag, when calling DeviceIoControl, a control code input / output (IOCTL), which represents the structure of the device type, function number, the type of data and the type of access. You can define several such codes for different operations and use them. I defined the code so IOCTL_READ_MEMORY = 0x80002000, 8000 - corresponds to the type of our device (FILE_DEVICE_MEMREADER); function number = 0x800, values below are reserved for user-defined functions allowed values 0x800 - 0xFFF; the type of data transmission - 0x0 (METHOD_BUFFERED), it means that we will receive / transmit data through the buffer that is specified SystemBuffer IRP-package); access type - FILE_ANY_ACCESS. visually:
So, as a function of DriverDeviceControl we get a pointer to the I/O stack IRP-query using the IoGetCurrentIrpStackLocation, which returns the parameter of lpCurStackLocation. When Successes (if non-zero pointer) is copied to the local structure IO_STACK_LOCATION parameters are referenced by the pointer. Now we check the IOCTL-code field AssociatedIrp, which is a union (in VB6 no associations) which stores a pointer to SystemBuffer. Because we have the type of data corresponds METHOD_BUFFERED, in parameter SystemBuffer contains a pointer to the buffer with the parameters (address and size) DeviceIoControl, in this buffer, we can also recover data that is written to the output buffer DeviceIoControl. Now, if we have data contains the correct values (IOCTL and SystemBuffer), then we copy into local variables (lpPointer, DataSize). Next, check the size of the buffer. Size of the system I/O buffer is contained in the parameter DeviceIoControl.OutputBufferLength. If the requested number of bytes is not larger than the size of the system buffer, then everything is fine. Now we need to calculate the number of memory pages occupied by the data that we want to copy. To do this, we define the virtual address of the beginning of the page corresponding to pass a pointer, and because page size is a multiple of 4 KB (0x1000) we simply vanish 12-bit pointer. Next, we check in the cycle will not be whether an exception is thrown Page fault using the MmIsAddressValid. If the page is not in memory, the function returns False. Thus we check the number of pages that you want us to take a piece of memory and the number of pages that we can read. Then we calculate the actual size of the data that we will be able to read and, if necessary, adjust the size. Next to the title of IRP-package we copy the data size that we can read and a successful status. IoStatus.Information field matches the value returned by DeviceIoControl parameter lpBytesReturned. Next copy in SystemBuffer right amount of bytes using RtlMoveMemory and return IRP-package I/O manager. Return the status of a successful operation. In all other cases, return error STATUS_INVALID_PARAMETER and zero data size. All the driver code is ready.
Proceed to the compilation. Because we can not use the runtime, all the API-functions, we declare a TLB, so that they fall into the import:
PS. InterlockedExchange - I left because first driver had a bit of a different structure, subsequently left the ad in the TLB. In the driver, it does not fall into imports.
To the driver worked to do three things:
In the field Subsystem, structure IMAGE_OPTIONAL_HEADER PE-driver file should be the value that corresponds to IMAGE_SUBSYSTEM_NATIVE kernel-mode driver.
Specify as the entry point of our procedure DriverEntry
Add a relocation section, in order that the driver can be loaded at any address.
Exclude MSVBVM60 of imports.
For the first 3 points are added to the compilation keys vbp-file with the following contents:
Compile the project with all the default optimization. To exclude the runtime of the import, I use a utility Patch, I used here. I'm a little modify it, as initially could not start the driver and long puzzled because of what it does, and the reason was the checksum. After exclusion of the import library checksum has changed, and I do not update it. And EXE, DLL, etc. this field is not checked, and the driver checks. To check the watch imports in any viewer PE:
As you can see there is no runtime. What we required. To test driver I wrote a simple program that loads the driver and works with him.
The driver must be in the same folder as the program. Code is commented, so I will not describe his work. To debug a driver you want to use the kernel-mode debugger. Debug going on a virtual system (VMware) - Windows XP. As a debugger take Syser, choose our driver and click Load. The system stops and we go to the debugger:
We are in the beginning of the function DriverEntry. The first "CALL" corresponds to a function call Init. If we follow step by step (F8) what's inside, we see how to complete the structure and called RtlInitUnicodeString for the device name and a symbolic link. The second "CALL" corresponds to the function "NT_SUCCESS", look it returns TRUE (in the register EAX) and code jumps after checking (TEST EAX, EAX) zero (False) on:
As can be seen code pushes the stack parameters for the IoCreateDevice from last to first using the instructions "PUSH". We start checking parameters. Check the name of the device (the third parameter - PUSH 0f8a2c010), for example, type "d 0f8a2c010" (which means to view a memory dump at f8a2c010, addresses are valid only for the current debugging) and see the contents:
the first 8 bytes - this is our variable DeviceName. The first two words - respectively the length of the line and the maximum length of the string in bytes. Next double word - a pointer to a string, look (d f8a2c0d8 consider the byte order little-endian):
there Unicode string with the name of the device. If you look at parameter Device (last output parameter - PUSH 0f8a2c020), we can see that it is different from the name on the 0x10 byte. Now look at the declaration of variables, the variable "Device" is declared after the DeviceName and DeviceLink, a total length of 8 + 8 = 0x10 bytes. Ie the order of the variables in the memory corresponds to the order in the ad code. Check the first non-const parameter ESI, in the beginning it is copied to the value at ESP + 0xC. Register ESP - points to the top of the stack. If you walk to the top function DriverEntry, you can see the preservation of the stack of two registers ESI and EDI (by agreement StdCall these registers are saved in the list, ie, the procedure should not change them after the call). DriverObject transmitted in the first variable, i.e. closest to the top of the stack, and after all the settings saved return address - ie DriverObject parameter before executing the first instruction in the DriverEntry function is located at ESP + 4 (the stack grows downward addresses), after two instructions "PUSH" he accordingly shifted by 8 bytes, as a result DriverObject located at ESP + 0C, all right . Correct settings, you can call the function. Hit F10 to not go inside and look IoCreateDevice value of the EAX register after the call, there must be a non-negative integer that indicates that the function worked without error. I have it returned 0 (STATUS_SUCCESS), everything is fine. Next comes the familiar procedure at 0xF8A2B750 - NT_SUCCESS:
If successful, go jump on 0xf8a2b7bf, where there is the pushing of the stack parameters for the function IoCreateSymbolicLink. Parameter DeviceName we have checked, check DeviceLink:
What you need. Hit F10, test EAX, if successful go further if it fails, remove the device and exit with an error. Procedure at 0xf8a2bbb0 - it GetAddr, which simply returns its this value:
Next there is copying of addresses at offsets DriverObject, if you look at the declaration you can see that at offset 0x34 is written address DriverUnload, at offset 0x38 - MajorFunction (0), etc. Recorded values correspond to the address of the function in our driver. Then there is zero EAX (the returned value) and exit from the procedure DriverEntry. Everything works without error, go ahead. So, to track the performance of the driver we will put a breakpoint on the function DriverDeviceControl. Address it is possible to take on the newly written offsets in the structure of DRIVER_OBJECT or find easy viewing and by analyzing the code. In my test, the address is 0xf8a2b870, go to him (. 0xf8a2b870) and press F9, set breakpoints. On the contrary instructions to set a marker:
Now, when this function is called the debugger will stop code execution and enables us to step through the code. Function "DriverCreateClose" and "DriverUnload" I will not describe, because everything is simple. Hit F5, thereby continuing to perform normally. We were immediately transferred back to Windows. Now we run our test application, enter any address (eg 81234567) and click on the button Read. Our challenge intercepts debugger and we can continue to test the function code DriverDeviceControl. Details inside I will not describe the code will focus on the copy:
Immediately look at the stack (register ESP), we see that the correct parameters are passed. In any case, do a dump, then compare:
Press F5 - and return to Windows. We look at the dump is already in our program:
As you can see everything is fine copy. Let's try to copy the data to a page boundary, so that one page was missing. Experimental method was found such a page that's what we get:
As we can see that the data is copied correctly, which did not work there, we displayed a question mark. The output parameter DeviceIoControl we actually returns the number of bytes read, we use it to display a question mark. _________________________________________________________________ As you can see on VB6, you can write a simple driver, and if you use inline assembly can be more serious and write something. Thank you for your attention. Good Luck!