-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmodMultiThreading2.bas
More file actions
1924 lines (1432 loc) · 60.3 KB
/
modMultiThreading2.bas
File metadata and controls
1924 lines (1432 loc) · 60.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Attribute VB_Name = "modMultiThreading"
' //
' // modMultiThreading2.bas - The module provides support for multi-threading.
' // Version 2.1
' // © Krivous Anatoly Anatolevich (The trick), 2015-2019
' // No TLB, No additional DLLs, No Asm-thunks (in compiled form)
' // Private object creation based on NameBasedObjectFactory by firehacker
' //
Option Explicit
Private Const HEAP_CREATE_ENABLE_EXECUTE As Long = &H40000
Private Const PAGE_EXECUTE_READWRITE As Long = &H40&
Private Const CC_STDCALL As Long = 4
Private Const HEAP_ZERO_MEMORY As Long = &H8
Private Const HKEY_CURRENT_USER As Long = &H80000001
Private Const REG_OPTION_NON_VOLATILE As Long = 0
Private Const KEY_WRITE As Long = &H20006
Private Const KEY_QUERY_VALUE As Long = &H1
Private Const REG_SZ As Long = 1
Private Const CLSCTX_INPROC_SERVER As Long = 1
Private Const CLSCTX_LOCAL_SERVER As Long = 4
Private Const MSHLFLAGS_TABLESTRONG As Long = 1
Private Const MSHCTX_INPROC As Long = 3
Private Const WM_ASYNCH_CALL As Long = &H8001&
Private Const TLS_OUT_OF_INDEXES As Long = &HFFFF&
Private Const PROCESS_HEAP_ENTRY_BUSY As Long = &H4
Private Const TH32CS_SNAPTHREAD As Long = 4
Private Const MESSAGE_WINDOW_CLASS As String = "MT2_VB6"
Private Const WM_ONCALLBACK As Long = &H400
Private Const HWND_MESSAGE As Long = -3
Private Const THREAD_SUSPEND_RESUME As Long = 2
Private Const SYNCHRONIZE As Long = &H100000
Private Const PM_REMOVE As Long = &H1
' // Lazy GUID structure
Private Type tCurGUID
c1 As Currency
c2 As Currency
End Type
' // That structure is used for asynch call. Caller pass that structure to callee
' // Callee uses that structure to make asynch call and callback to caller
Private Type tAsynchCallData
pStream As Long ' // Stream for marshaling of callback object
sCallBackName As String ' // Callback method name
eCallType As VbCallType ' // Call type (Method, Property, etc.)
sMethodName As String ' // Method name to call
vArgs() As Variant ' // Arguments
End Type
' // TLS data for new thread
Private Type tThreadData
lpParameter As Long
lpAddress As Long
End Type
' // Object types flags
Private Enum eObjThreadDataFlags
OTDF_ACTIVEX ' // Create new ActiveX object (Public)
OTDF_PRIVATE ' // Create local object (Private)
End Enum
' // New object info. That structure uses to create new object in new thread
Private Type tNewObjectThreadData
eFlags As eObjThreadDataFlags ' // Object type
pStream As Long ' // Marshaling stream
hEvent As Long ' // Synchronization event
pClsid As Long ' // Class identifier (for ActiveX calsses - CLSID, for private calsses - name)
pIID As Long ' // Interface identifier
hr As Long ' // Result
End Type
Private Type CRITICAL_SECTION
pDebugInfo As Long
LockCount As Long
RecursionCount As Long
OwningThread As Long
LockSemaphore As Long
SpinCount As Long
End Type
Private Type tCriticalSection
tWinApiSection As CRITICAL_SECTION
bIsInitialized As Boolean
End Type
Private Type PROCESS_HEAP_ENTRY
lpData As Long
cbData As Long
cbOverhead As Byte
iRegionIndex As Byte
wFlags As Integer
dwCommittedSize As Long
dwUnCommittedSize As Long
lpFirstBlock As Long
lpLastBlock As Long
End Type
Private Type THREADENTRY32
dwSize As Long
cntUsage As Long
th32ThreadID As Long
th32OwnerProcessID As Long
tpBasePri As Long
tpDeltaPri As Long
dwFlags As Long
End Type
Private Type POINTAPI
x As Long
y As Long
End Type
Private Type msg
hwnd As Long
message As Long
wParam As Long
lParam As Long
time As Long
pt As POINTAPI
End Type
Private Type WNDCLASSEX
cbSize As Long
style As Long
lpfnwndproc As Long
cbClsextra As Long
cbWndExtra2 As Long
hInstance As Long
hIcon As Long
hCursor As Long
hbrBackground As Long
lpszMenuName As Long
lpszClassName As Long
hIconSm As Long
End Type
Private Declare Function MsgWaitForMultipleObjects Lib "user32" ( _
ByVal nCount As Long, _
ByRef pHandles As Long, _
ByVal fWaitAll As Long, _
ByVal dwMilliseconds As Long, _
ByVal dwWakeMask As Long) As Long
Private Declare Function Sleep Lib "kernel32" ( _
ByVal dwMilliseconds As Long) As Long
Private Declare Function vbaNew Lib "msvbvm60" _
Alias "__vbaNew" ( _
ByRef lpObjectInformation As Any) As IUnknown
Private Declare Function lstrcmp Lib "kernel32" _
Alias "lstrcmpA" ( _
ByVal lpString1 As Long, _
ByVal lpString2 As Long) As Long
Private Declare Function EbExecuteLine Lib "vba6.dll" ( _
ByVal pStringToExec As Long, _
ByVal Foo1 As Long, _
ByVal Foo2 As Long, _
ByVal fCheckOnly As Long) As Long
Private Declare Function InitializeCriticalSection Lib "kernel32" ( _
ByRef lpCriticalSection As CRITICAL_SECTION) As Long
Private Declare Sub EnterCriticalSection Lib "kernel32" ( _
ByRef lpCriticalSection As CRITICAL_SECTION)
Private Declare Sub LeaveCriticalSection Lib "kernel32" ( _
ByRef lpCriticalSection As CRITICAL_SECTION)
Private Declare Sub DeleteCriticalSection Lib "kernel32" ( _
ByRef lpCriticalSection As CRITICAL_SECTION)
Private Declare Function TryEnterCriticalSection Lib "kernel32" ( _
ByRef lpCriticalSection As CRITICAL_SECTION) As Long
Private Declare Function IStream_Reset Lib "Shlwapi" Alias "#213" ( _
ByVal pStm As Any) As Long
Private Declare Function rtcCallByName Lib "msvbvm60" ( _
ByRef vRet As Variant, _
ByVal cObj As Object, _
ByVal sMethod As Long, _
ByVal eCallType As VbCallType, _
ByRef pArgs() As Variant, _
ByVal lcid As Long) As Long
Private Declare Function vbaObjSet Lib "msvbvm60" _
Alias "__vbaObjSet" ( _
ByRef dstObject As Any, _
ByRef srcObjPtr As Any) As Long
Private Declare Function vbaObjSetAddref Lib "msvbvm60" _
Alias "__vbaObjSetAddref" ( _
ByRef dstObject As Any, _
ByRef srcObjPtr As Any) As Long
Private Declare Sub CoFreeUnusedLibraries Lib "ole32" ()
Private Declare Function RegCreateKeyEx Lib "advapi32.dll" _
Alias "RegCreateKeyExW" ( _
ByVal hKey As Long, _
ByVal lpSubKey As Long, _
ByVal Reserved As Long, _
ByVal lpClass As Long, _
ByVal dwOptions As Long, _
ByVal samDesired As Long, _
ByRef lpSecurityAttributes As Any, _
ByRef phkResult As Long, _
ByRef lpdwDisposition As Long) As Long
Private Declare Function RegCloseKey Lib "advapi32.dll" ( _
ByVal hKey As Long) As Long
Private Declare Function RegSetValueEx Lib "advapi32.dll" _
Alias "RegSetValueExW" ( _
ByVal hKey As Long, _
ByVal lpValueName As Long, _
ByVal Reserved As Long, _
ByVal dwType As Long, _
ByRef lpData As Any, _
ByVal cbData As Long) As Long
Private Declare Function CreateIExprSrvObj Lib "MSVBVM60.DLL" ( _
ByVal pUnk1 As Long, _
ByVal lUnk2 As Long, _
ByVal pUnk3 As Long) As IUnknown
Private Declare Function VBDllGetClassObject Lib "MSVBVM60.DLL" ( _
ByRef phModule As Long, _
ByVal lReserved As Long, _
ByVal pVBHeader As Long, _
ByRef pClsid As Any, _
ByRef pIID As Any, _
ByRef pObject As Any) As Long
Private Declare Function GetMem2 Lib "msvbvm60" ( _
ByRef pSrc As Any, _
ByRef pDst As Any) As Long
Private Declare Function GetMem4 Lib "msvbvm60" ( _
ByRef pSrc As Any, _
ByRef pDst As Any) As Long
Private Declare Function GetMem8 Lib "msvbvm60" ( _
ByRef pSrc As Any, _
ByRef pDst As Any) As Long
Private Declare Function DispCallFunc Lib "oleaut32.dll" ( _
ByRef pvInstance As Any, _
ByVal oVft As Long, _
ByVal cc As Long, _
ByVal vtReturn As VbVarType, _
ByVal cActuals As Long, _
ByRef prgvt As Any, _
ByRef prgpvarg As Any, _
ByRef pvargResult As Variant) As Long
Private Declare Function VirtualProtect Lib "kernel32" ( _
ByVal lpAddress As Long, _
ByVal dwSize As Long, _
ByVal flNewProtect As Long, _
ByRef lpflOldProtect As Long) As Long
Private Declare Function TlsAlloc Lib "kernel32" () As Long
Private Declare Function TlsFree Lib "kernel32" ( _
ByVal dwTlsIndex As Long) As Long
Private Declare Function TlsSetValue Lib "kernel32" ( _
ByVal dwTlsIndex As Long, _
ByRef lpTlsValue As Any) As Long
Private Declare Function TlsGetValue Lib "kernel32" ( _
ByVal dwTlsIndex As Long) As Long
Private Declare Function HeapAlloc Lib "kernel32" ( _
ByVal hHeap As Long, _
ByVal dwFlags As Long, _
ByVal dwBytes As Long) As Long
Private Declare Function HeapCreate Lib "kernel32" ( _
ByVal flOptions As Long, _
ByVal dwInitialSize As Long, _
ByVal dwMaximumSize As Long) As Long
Private Declare Function HeapDestroy Lib "kernel32" ( _
ByVal hHeap As Long) As Long
Private Declare Function HeapLock Lib "kernel32" ( _
ByVal hHeap As Long) As Long
Private Declare Function HeapUnlock Lib "kernel32" ( _
ByVal hHeap As Long) As Long
Private Declare Function HeapWalk Lib "kernel32" ( _
ByVal hHeap As Long, _
ByRef lpEntry As PROCESS_HEAP_ENTRY) As Long
Private Declare Function HeapFree Lib "kernel32" ( _
ByVal hHeap As Long, _
ByVal dwFlags As Long, _
ByVal lpMem As Long) As Long
Private Declare Function GetProcessHeap Lib "kernel32" () As Long
Private Declare Function CreateThread Lib "kernel32" ( _
ByRef lpThreadAttributes As Any, _
ByVal dwStackSize As Long, _
ByVal lpStartAddress As Long, _
ByRef lpParameter As Any, _
ByVal dwCreationFlags As Long, _
ByRef lpThreadId As Long) As Long
Private Declare Function CoInitialize Lib "ole32" ( _
ByRef pvReserved As Any) As Long
Private Declare Function CopyMemory Lib "kernel32" _
Alias "RtlMoveMemory" ( _
ByRef Destination As Any, _
ByRef Source As Any, _
ByVal Length As Long) As Long
Private Declare Function CoMarshalInterThreadInterfaceInStream Lib "ole32.dll" ( _
ByRef riid As Any, _
ByVal pUnk As Any, _
ByRef ppstm As Any) As Long
Private Declare Function CoMarshalInterface Lib "ole32.dll" ( _
ByVal pStm As Long, _
ByRef riid As Any, _
ByVal pUnk As Any, _
ByVal dwDestContext As Long, _
ByRef pvDestContext As Any, _
ByVal mshlflags As Long) As Long
Private Declare Function CoGetInterfaceAndReleaseStream Lib "ole32.dll" ( _
ByVal pStm As Long, _
ByRef riid As Any, _
ByRef pUnk As Any) As Long
Private Declare Function CoUnmarshalInterface Lib "ole32.dll" ( _
ByVal pStm As Long, _
ByRef riid As Any, _
ByRef pUnk As Any) As Long
Private Declare Function CoReleaseMarshalData Lib "ole32" ( _
ByVal pStm As Long) As Long
Private Declare Function GetMessage Lib "user32" _
Alias "GetMessageW" ( _
ByRef lpMsg As Any, _
ByVal hwnd As Long, _
ByVal wMsgFilterMin As Long, _
ByVal wMsgFilterMax As Long) As Long
Private Declare Function TranslateMessage Lib "user32" ( _
ByRef lpMsg As Any) As Long
Private Declare Function DispatchMessage Lib "user32" _
Alias "DispatchMessageW" ( _
ByRef lpMsg As Any) As Long
Private Declare Function WaitForSingleObject Lib "kernel32" ( _
ByVal hHandle As Long, _
ByVal dwMilliseconds As Long) As Long
Private Declare Function CreateEvent Lib "kernel32" _
Alias "CreateEventW" ( _
ByRef lpEventAttributes As Any, _
ByVal bManualReset As Long, _
ByVal bInitialState As Long, _
ByVal lpName As Long) As Long
Private Declare Function SetEvent Lib "kernel32" ( _
ByVal hEvent As Long) As Long
Private Declare Function CLSIDFromProgID Lib "ole32" ( _
ByVal TSzProgID As Long, _
ByRef pGuid As Any) As Long
Private Declare Function CoCreateInstance Lib "ole32" ( _
ByVal rclsid As Long, _
ByVal pUnkOuter As Long, _
ByVal dwClsContext As Long, _
ByVal riid As Long, _
ByRef ppv As Any) As Long
Private Declare Function CreateStreamOnHGlobal Lib "ole32" ( _
ByVal hGlobal As Long, _
ByVal fDeleteOnRelease As Long, _
ByRef ppstm As Any) As Long
Private Declare Function PostThreadMessage Lib "user32" _
Alias "PostThreadMessageW" ( _
ByVal idThread As Long, _
ByVal msg As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) As Long
Private Declare Function lstrlen Lib "kernel32" _
Alias "lstrlenA" ( _
ByVal lpString As Long) As Long
Private Declare Function SysAllocStringByteLen Lib "oleaut32" ( _
ByRef m_pBase As Any, _
ByVal sz As Long) As String
Private Declare Function CreateToolhelp32Snapshot Lib "kernel32" ( _
ByVal dwFlags As Long, _
ByVal th32ProcessID As Long) As Long
Private Declare Function Thread32First Lib "kernel32" ( _
ByVal hSnapshot As Long, _
ByRef lpte As THREADENTRY32) As Long
Private Declare Function Thread32Next Lib "kernel32" ( _
ByVal hSnapshot As Long, _
ByRef lpte As THREADENTRY32) As Long
Private Declare Function GetCurrentProcessId Lib "kernel32" () As Long
Private Declare Function GetClassLong Lib "user32" _
Alias "GetClassLongW" ( _
ByVal hwnd As Long, _
ByVal nIndex As Long) As Long
Private Declare Function SetClassLong Lib "user32" _
Alias "SetClassLongW" ( _
ByVal hwnd As Long, _
ByVal nIndex As Long, _
ByVal dwNewLong As Long) As Long
Private Declare Function GetClassInfoEx Lib "user32" _
Alias "GetClassInfoExW" ( _
ByVal hInstance As Long, _
ByVal lpClassName As Long, _
ByRef lpWndClassEx As WNDCLASSEX) As Long
Private Declare Function UnregisterClass Lib "user32" _
Alias "UnregisterClassW" ( _
ByVal lpClassName As Long, _
ByVal hInstance As Long) As Long
Private Declare Function RegisterClassEx Lib "user32" _
Alias "RegisterClassExW" ( _
ByRef pcWndClassEx As WNDCLASSEX) As Integer
Private Declare Function GetProcAddress Lib "kernel32" ( _
ByVal hModule As Long, _
ByVal lpProcName As String) As Long
Private Declare Function CreateWindowEx Lib "user32" _
Alias "CreateWindowExW" ( _
ByVal dwExStyle As Long, _
ByVal lpClassName As Long, _
ByVal lpWindowName As Long, _
ByVal dwStyle As Long, _
ByVal x As Long, _
ByVal y As Long, _
ByVal nWidth As Long, _
ByVal nHeight As Long, _
ByVal hWndParent As Long, _
ByVal hMenu As Long, _
ByVal hInstance As Long, _
ByRef lpParam As Any) As Long
Private Declare Function GetModuleHandle Lib "kernel32" _
Alias "GetModuleHandleW" ( _
ByVal lpModuleName As Long) As Long
Private Declare Function DestroyWindow Lib "user32" ( _
ByVal hwnd As Long) As Long
Private Declare Function SuspendThread Lib "kernel32" ( _
ByVal hThread As Long) As Long
Private Declare Function ResumeThread Lib "kernel32" ( _
ByVal hThread As Long) As Long
Private Declare Function OpenThread Lib "kernel32" ( _
ByVal dwDesiredAccess As Long, _
ByVal bInheritHandle As Long, _
ByVal dwThreadId As Long) As Long
Private Declare Function PeekMessage Lib "user32" _
Alias "PeekMessageW" ( _
ByRef lpMsg As msg, _
ByVal hwnd As Long, _
ByVal wMsgFilterMin As Long, _
ByVal wMsgFilterMax As Long, _
ByVal wRemoveMsg As Long) As Long
Private Declare Sub ZeroMemory Lib "kernel32" _
Alias "RtlZeroMemory" ( _
ByRef Destination As Any, _
ByVal Length As Long)
Private Declare Sub CoUninitialize Lib "ole32" ()
' // Export to close handles from clients
Public Declare Function CloseHandle Lib "kernel32" ( _
ByVal hObject As Long) As Long
Private lTlsSlot As Long ' // Index of the item in the TLS. There will be data specific to the thread.
Private pVBHeader As Long ' // Pointer to VBHeader structure.
Private hModule As Long ' // Base address.
Private tLockMarshal As tCriticalSection ' // Critical section for multiple-time marshaling
Private tLockHeap As tCriticalSection ' // Critical section for cleaning heap
Private hHeadersHeap As Long
' // IN IDE ONLY
Private hCodeHeap As Long ' // Heap for dynamic code
Private hMsgWindow As Long ' // Handle of message window
' // Initialize
Public Function Initialize() As Boolean
Dim bIsInIDE As Boolean
Debug.Assert MakeTrue(bIsInIDE)
If Not bIsInIDE Then
InitializeCriticalSection tLockMarshal.tWinApiSection
tLockMarshal.bIsInitialized = True
InitializeCriticalSection tLockHeap.tWinApiSection
tLockHeap.bIsInitialized = True
hModule = App.hInstance
pVBHeader = GetVBHeader()
If pVBHeader = 0 Then GoTo CleanUp
ModifyVBHeader AddressOf FakeMain
hHeadersHeap = HeapCreate(0, 0, 65536)
If hHeadersHeap = 0 Then GoTo CleanUp
End If
lTlsSlot = TlsAlloc()
If lTlsSlot = TLS_OUT_OF_INDEXES Then GoTo CleanUp
' // Main thread already initialized
TlsSetValue lTlsSlot, ByVal 1&
Initialize = True
CleanUp:
If Not Initialize Then
Uninitialize
End If
End Function
' // Uninitialize resources
' // WARNING! Don't call it if a thread uses resources
Public Sub Uninitialize()
Dim bIsInIDE As Boolean
Debug.Assert MakeTrue(bIsInIDE)
If bIsInIDE Then
If hMsgWindow Then
DestroyWindow hMsgWindow
UnregisterClass StrPtr(MESSAGE_WINDOW_CLASS), App.hInstance
End If
If hCodeHeap Then HeapDestroy hCodeHeap
hMsgWindow = 0
hCodeHeap = 0
End If
If tLockMarshal.bIsInitialized Then DeleteCriticalSection tLockMarshal.tWinApiSection
If tLockHeap.bIsInitialized Then DeleteCriticalSection tLockHeap.tWinApiSection
If hHeadersHeap Then HeapDestroy hHeadersHeap
If lTlsSlot Then TlsFree lTlsSlot
FreeUnusedHeaders
tLockMarshal.bIsInitialized = False
tLockHeap.bIsInitialized = False
hHeadersHeap = 0
lTlsSlot = 0
End Sub
' // Create a new thread
Public Function vbCreateThread(ByVal lpThreadAttributes As Long, _
ByVal dwStackSize As Long, _
ByVal lpStartAddress As Long, _
ByVal lpParameter As Long, _
ByVal dwCreationFlags As Long, _
ByRef lpThreadId As Long, _
Optional ByVal bIDEInSameThread As Boolean = True) As Long
Dim bIsInIDE As Boolean
Dim hr As Long
Dim pThreadData As Long
Debug.Assert MakeTrue(bIsInIDE)
If bIsInIDE Then
If bIDEInSameThread Then
' // Run function in main thread
hr = DispCallFunc(ByVal 0&, lpStartAddress, CC_STDCALL, vbEmpty, 1, vbLong, VarPtr(CVar(lpParameter)), CVar(0))
If hr Then
Err.Raise hr
End If
Exit Function
End If
Err.Raise 5
End If
pThreadData = PrepareData(lpStartAddress, lpParameter)
If pThreadData = 0 Then Exit Function
' // Create thread
vbCreateThread = CreateThread(ByVal lpThreadAttributes, _
dwStackSize, _
AddressOf ThreadProc, _
ByVal pThreadData, _
dwCreationFlags, _
lpThreadId)
End Function
' // Allow marshaling of private classes
Public Function EnablePrivateMarshaling( _
ByVal bEnable As Boolean) As Boolean
Dim hKey As Long
Dim sValue As String
If bEnable Then
sValue = "1"
Else
sValue = "0"
End If
If RegCreateKeyEx(HKEY_CURRENT_USER, StrPtr("Software\Microsoft\Visual Basic\6.0"), 0, 0, _
REG_OPTION_NON_VOLATILE, KEY_WRITE Or KEY_QUERY_VALUE, ByVal 0&, hKey, 0) Then
Exit Function
End If
If RegSetValueEx(hKey, StrPtr("AllowUnsafeObjectPassing"), 0, REG_SZ, ByVal StrPtr(sValue), LenB(sValue) + 2) Then
GoTo CleanUp
End If
EnablePrivateMarshaling = True
CleanUp:
RegCloseKey hKey
End Function
' // FOR IDE ONLY
' // Get address of callback procedure that calls user function in main thread
' // It uses a window to transmit call from callback thread to main thread
' // When callback procedure is being called asm-thunk call SendMessage to
' // message-only window that is in main thread. Window proc of that window
' // calls pfnCallback function and passes pointer to stack of caller thread
Public Function InitCurrentThreadAndCallFunctionIDEProc( _
ByVal pfnCallback As Long, _
ByVal lParametersSize As Long) As Long
Dim ptr As Long
Dim hUser32 As Long
Dim pfnSendMessage As Long
' // Initialize message window and heap
hMsgWindow = InitializeMessageWindow()
If hMsgWindow = 0 Then Exit Function
' // Check if thunk already exists
ptr = FindThunk(pfnCallback)
If ptr Then
InitCurrentThreadAndCallFunctionIDEProc = ptr
Exit Function
End If
' // Make asm-thunk
' // LEA EAX, [ESP+4]
' // PUSH EAX
' // PUSH pfnCallback
' // PUSH WM_ONCALLBACK
' // PUSH hMsgWindow
' // Call SendMessageW
' // RETN lParametersSize
hUser32 = GetModuleHandle(StrPtr("user32"))
ptr = HeapAlloc(hCodeHeap, 0, &H1C)
If ptr = 0 Then Exit Function
pfnSendMessage = GetProcAddress(hUser32, "SendMessageW") - ptr - &H19
GetMem8 11469288874.1005@, ByVal ptr
GetMem8 749398979713119.0272@, ByVal ptr + &H8
GetMem8 99643241.2672@, ByVal ptr + &H10
GetMem4 &HC200&, ByVal ptr + &H18
GetMem4 pfnCallback, ByVal ptr + &H6
GetMem4 hMsgWindow, ByVal ptr + &H10
GetMem2 lParametersSize, ByVal ptr + &H1A
GetMem4 pfnSendMessage, ByVal ptr + &H15
InitCurrentThreadAndCallFunctionIDEProc = ptr
End Function
' // Initialize message window
Private Function InitializeMessageWindow() As Long
Dim tClass As WNDCLASSEX
Dim pWndProc As Long
Dim bRegistered As Boolean
If hMsgWindow Then
InitializeMessageWindow = hMsgWindow
Exit Function
End If
tClass.cbSize = Len(tClass)
' // Check if class already registered
If GetClassInfoEx(App.hInstance, StrPtr(MESSAGE_WINDOW_CLASS), tClass) = 0 Then
' // Create heap for asm-thunks
If hCodeHeap = 0 Then
hCodeHeap = HeapCreate(HEAP_CREATE_ENABLE_EXECUTE, 0, 0)
If hCodeHeap = 0 Then GoTo CleanUp
End If
' // Create window proc
pWndProc = CreateWndProcCode()
If pWndProc = 0 Then GoTo CleanUp
tClass.hInstance = App.hInstance
tClass.lpfnwndproc = pWndProc
tClass.lpszClassName = StrPtr(MESSAGE_WINDOW_CLASS)
tClass.cbClsextra = 8 ' // 0x00 - hCodeHeap
' // 0x04 - hMsgWindow
' // 0x08 - size
If RegisterClassEx(tClass) = 0 Then GoTo CleanUp
bRegistered = True
End If
' // Create window
hMsgWindow = CreateWindowEx(0, StrPtr(MESSAGE_WINDOW_CLASS), 0, 0, 0, 0, 0, 0, _
HWND_MESSAGE, 0, App.hInstance, ByVal 0&)
If hMsgWindow = 0 Then Exit Function
If Not bRegistered Then
' // Destroy previous session window and get heap
DestroyWindow GetClassLong(hMsgWindow, 4)
hCodeHeap = GetClassLong(hMsgWindow, 0)
' // Free unused thunks
FreeThunks tClass.lpfnwndproc
End If
' // Save global data
SetClassLong hMsgWindow, 0, hCodeHeap
SetClassLong hMsgWindow, 4, hMsgWindow
InitializeMessageWindow = hMsgWindow
Exit Function
CleanUp:
If pWndProc Then HeapFree hCodeHeap, 0, pWndProc
If bRegistered Then UnregisterClass StrPtr(MESSAGE_WINDOW_CLASS), App.hInstance
If hCodeHeap Then HeapDestroy hCodeHeap
hCodeHeap = 0
hMsgWindow = 0
End Function
' // Free thunks
Private Sub FreeThunks( _
ByVal pfnWndProc As Long)
Dim tEntry As PROCESS_HEAP_ENTRY
Dim pPointers() As Long
Dim lIndex As Long
Dim lCount As Long
ReDim pPointers(255)
If HeapLock(hCodeHeap) = 0 Then Exit Sub
Do While HeapWalk(hCodeHeap, tEntry)
If tEntry.wFlags And PROCESS_HEAP_ENTRY_BUSY Then
If tEntry.lpData <> pfnWndProc Then
If lIndex > UBound(pPointers) Then
ReDim Preserve pPointers(lIndex + 256)
End If
pPointers(lIndex) = tEntry.lpData
lIndex = lIndex + 1
End If
End If
Loop
HeapUnlock hCodeHeap
lCount = lIndex
For lIndex = 0 To lCount - 1
HeapFree hCodeHeap, 0, pPointers(lIndex)
Next
End Sub
Private Function FindThunk( _
ByVal pfn As Long) As Long
Dim tEntry As PROCESS_HEAP_ENTRY
Dim pfnCur As Long
If HeapLock(hCodeHeap) = 0 Then Exit Function
Do While HeapWalk(hCodeHeap, tEntry)
If tEntry.wFlags And PROCESS_HEAP_ENTRY_BUSY Then
GetMem4 ByVal tEntry.lpData + &H6, pfnCur
If pfnCur = pfn Then
FindThunk = tEntry.lpData
Exit Do
End If
End If
Loop
HeapUnlock hCodeHeap
End Function
' // Create window proc
Private Function CreateWndProcCode() As Long
Dim ptr As Long
Dim hUser32 As Long
Dim pfnDefWindowProc As Long
ptr = HeapAlloc(hCodeHeap, 0, &H1A)
If ptr = 0 Then Exit Function
hUser32 = GetModuleHandle(StrPtr("user32"))
pfnDefWindowProc = GetProcAddress(hUser32, "DefWindowProcW") - ptr - &HF
' // CMP DWORD [ESP+8], WM_ONCALLBACK
' // JE SHORT L
' // JMP DefWindowProcW
' // L: PUSH DWORD PTR SS:[ESP+10]
' // CALL DWORD PTR SS:[ESP+10]
' // RETN 10
GetMem8 439819570.2913@, ByVal ptr
GetMem8 -7205759402265.6652@, ByVal ptr + 8
GetMem8 -446281617701647.8604@, ByVal ptr + &H10
GetMem2 16&, ByVal ptr + &H18
GetMem4 pfnDefWindowProc, ByVal ptr + &HB
CreateWndProcCode = ptr
End Function
' // Init thread and call function
' // This function is useful for callback of WINAPI functions which can call function in arbitrary thread
Public Function InitCurrentThreadAndCallFunction( _
ByVal pfnCallback As Long, _
ByVal pParam As Long, _
ByRef lReturnValue As Long) As Boolean
Dim cExpSrv As IUnknown
Dim pThreadData As Long
Dim hr As Long
Dim vRet As Variant
Dim bIsInIDE As Boolean
Debug.Assert MakeTrue(bIsInIDE)
If bIsInIDE Then
' // Error
Exit Function
End If
Set cExpSrv = CreateIExprSrvObj(0, 4, 0)
If lTlsSlot Then
' // Check if thread already initialized
pThreadData = TlsGetValue(lTlsSlot)
If pThreadData <> 0 Then
CoInitialize ByVal 0&
' // Just call by pointer
hr = DispCallFunc(ByVal 0&, pfnCallback, CC_STDCALL, vbLong, 1, vbLong, VarPtr(CVar(pParam)), vRet)
CoUninitialize
If hr Then
Err.Raise hr
End If
lReturnValue = vRet
InitCurrentThreadAndCallFunction = True
Exit Function
End If
End If
pThreadData = PrepareData(pfnCallback, pParam)
If pThreadData = 0 Then Exit Function
Set cExpSrv = Nothing
lReturnValue = ThreadProc(pThreadData)
End Function
' // Create new private object in the new thread by name
Public Function CreatePrivateObjectByNameInNewThread( _
ByRef sClassName As String, _
Optional ByVal pIID As Long, _
Optional ByRef lAsynchId As Long) As IUnknown
Dim tThreadData As tNewObjectThreadData
Dim hThread As Long
Dim tIID_IDispatch As tCurGUID
Dim sAnsiName As String
Dim bIsInIDE As Boolean
Debug.Assert MakeTrue(bIsInIDE)
sAnsiName = StrConv(sClassName, vbFromUnicode)
tThreadData.eFlags = OTDF_PRIVATE
tThreadData.pClsid = StrPtr(sAnsiName)
If pIID = 0 Then
tIID_IDispatch.c1 = 13.2096@
tIID_IDispatch.c2 = 504403158265495.5712@
tThreadData.pIID = VarPtr(tIID_IDispatch)
Else: tThreadData.pIID = pIID
End If
If bIsInIDE Then
ActiveXThreadProc tThreadData
vbaObjSet CreatePrivateObjectByNameInNewThread, ByVal tThreadData.pStream
lAsynchId = tThreadData.pStream
Else
tThreadData.hEvent = CreateEvent(ByVal 0&, 1, 0, 0)
If tThreadData.hEvent = 0 Then Err.Raise 7
hThread = vbCreateThread(0, 0, AddressOf ActiveXThreadProc, VarPtr(tThreadData), 0, lAsynchId)
' // Wait for object creation
WaitForSingleObject tThreadData.hEvent, -1
CloseHandle tThreadData.hEvent
If tThreadData.hr Then
Err.Raise tThreadData.hr
End If
If tThreadData.pStream = 0 Then Exit Function
Set CreatePrivateObjectByNameInNewThread = UnMarshal(tThreadData.pStream, pIID)
End If
End Function
' // Create new ActiveX object in the new thread by ProgID
Public Function CreateActiveXObjectInNewThread2( _
ByRef sProgID As String, _
Optional ByVal pIID As Long, _
Optional ByRef lAsynchId As Long) As IUnknown
Dim tClsId As tCurGUID
If CLSIDFromProgID(StrPtr(sProgID), tClsId) < 0 Then
Err.Raise 5
End If
Set CreateActiveXObjectInNewThread2 = CreateActiveXObjectInNewThread(VarPtr(tClsId), pIID, lAsynchId)
End Function
' // Create new ActiveX object in the new thread
Public Function CreateActiveXObjectInNewThread( _
ByVal pClsid As Long, _
Optional ByVal pIID As Long, _
Optional ByRef lAsynchId As Long) As IUnknown
Dim tThreadData As tNewObjectThreadData
Dim hThread As Long
Dim tIID_IDispatch As tCurGUID
Dim bIsInIDE As Boolean
Debug.Assert MakeTrue(bIsInIDE)
tThreadData.eFlags = OTDF_ACTIVEX
tThreadData.pClsid = pClsid
If pIID = 0 Then
tIID_IDispatch.c1 = 13.2096@
tIID_IDispatch.c2 = 504403158265495.5712@
tThreadData.pIID = VarPtr(tIID_IDispatch)
Else: tThreadData.pIID = pIID
End If
If bIsInIDE Then
ActiveXThreadProc tThreadData
vbaObjSet CreateActiveXObjectInNewThread, ByVal tThreadData.pStream
lAsynchId = tThreadData.pStream
Else
tThreadData.hEvent = CreateEvent(ByVal 0&, 1, 0, 0)
If tThreadData.hEvent = 0 Then Err.Raise 7
hThread = vbCreateThread(0, 0, AddressOf ActiveXThreadProc, VarPtr(tThreadData), 0, lAsynchId)