/
dll2.d
151 lines (137 loc) · 2.72 KB
/
dll2.d
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
// Public Domain
import std.c.windows.windows;
import std.c.stdlib;
version(D_Version2)
{
import core.runtime;
import core.memory;
version(use_patch)
import core.sys.windows.dll;
import core.stdc.string;
extern (C) void _moduleTlsCtor();
extern (C) void _moduleTlsDtor();
}
else
{
import std.gc;
import std.thread;
version(use_patch)
import std.thread_helper;
extern (C)
{
void gc_init();
void gc_term();
void _minit();
void _moduleCtor();
void _moduleDtor();
void _moduleUnitTests();
}
}
extern (Windows)
BOOL DllMain(HINSTANCE hInstance, ULONG ulReason, LPVOID pvReserved)
{
switch (ulReason)
{
case DLL_PROCESS_ATTACH:
version(D_Version2)
{
version(use_patch)
{
if( !dll_fixTLS( hInstance, &_tlsstart, &_tlsend, &_tls_callbacks_a, &_tls_index ) )
return false;
Runtime.initialize();
// attach to all other threads
enumProcessThreads( function (uint id, void* context) {
if( !thread_findByAddr( id ) )
{
thread_attachByAddr( id );
thread_moduleTlsCtor( id );
}
return true;
}, null );
}
else
Runtime.initialize();
}
else
{
gc_init(); // initialize GC
_minit(); // initialize module list
_moduleCtor(); // run module constructors
_moduleUnitTests(); // run module unit tests
version(use_patch)
{
// attach to all other threads
enumProcessThreads( function (uint id, void* context) {
if( !Thread._getThreadById( id ) )
Thread.thread_attach( id, OpenThreadHandle( id ), getThreadStackBottom( id ) );
return true;
}, null );
}
// enumThreads();
}
break;
case DLL_PROCESS_DETACH:
version(D_Version2)
{
version(use_patch)
{
// detach from all other threads
enumProcessThreads(
function (uint id, void* context) {
if( id != GetCurrentThreadId() && thread_findByAddr( id ) )
thread_detachByAddr( id );
return true;
}, null );
}
Runtime.terminate();
}
else
{
version(use_patch)
{
// detach from all other threads
enumProcessThreads(
function (uint id, void* context) {
if( id != GetCurrentThreadId() )
{
thread_moduleTlsDtor( id );
Thread.thread_detach( id );
}
return true;
}, null );
}
_moduleDtor();
gc_term(); // shut down GC
}
break;
case DLL_THREAD_ATTACH:
version(use_patch)
{
version(D_Version2)
{
thread_attachThis();
_moduleTlsCtor();
}
else
Thread.thread_attach();
}
break;
case DLL_THREAD_DETACH:
version(use_patch)
{
version(D_Version2)
{
if( thread_findByAddr( GetCurrentThreadId() ) )
_moduleTlsDtor();
thread_detachThis();
}
else
Thread.thread_detach();
}
break;
default:
assert(0);
}
return true;
}