Debian Codegraph @

libphobos/libdruntime/core/sys/windows/threadaux.d

raw
1 /**
2 * This module provides OS specific helper function for threads support
3 *
4 * Copyright: Copyright Digital Mars 2010 - 2010.
5 * License: Distributed under the
6 * $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0).
7 * (See accompanying file LICENSE)
8 * Source: $(DRUNTIMESRC core/sys/windows/_threadaux.d)
9 * Authors: Rainer Schuetze
10 */
11
12 module core.sys.windows.threadaux;
13 version (Windows):
14
15 import core.sys.windows.basetsd/+ : HANDLE+/;
16 import core.sys.windows.winbase/+ : CloseHandle, GetCurrentThreadId, GetCurrentProcessId,
17 GetModuleHandleA, GetProcAddress+/;
18 import core.sys.windows.windef/+ : BOOL, DWORD, FALSE, HRESULT+/;
19 import core.stdc.stdlib;
20
21 public import core.thread;
22
23 extern(Windows)
24 HANDLE OpenThread(DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwThreadId) nothrow @nogc;
25
26 extern (C) extern __gshared int _tls_index;
27
28 extern (C) // rt.minfo
29 {
30 void rt_moduleTlsCtor();
31 void rt_moduleTlsDtor();
32 }
33
34 private:
35 ///////////////////////////////////////////////////////////////////
36 struct thread_aux
37 {
38 // don't let symbols leak into other modules
39
40 enum SystemProcessInformation = 5;
41 enum STATUS_INFO_LENGTH_MISMATCH = 0xc0000004;
42
43 // structs subject to change according to MSDN, more info at http://undocumented.ntinternals.net
44 // declarations according to http://processhacker.sourceforge.net/doc/ntexapi_8h_source.html
45 // NOTE: the declarations assume default alignment for Win64 and contain some padding data
46 struct UNICODE_STRING
47 {
48 short Length;
49 short MaximumLength;
50 wchar* Buffer;
51 }
52 // process or thread ID, documentation says it is a HANDLE, but it's actually the ID (a DWORD)
53 alias size_t PTID;
54
55 struct _SYSTEM_PROCESS_INFORMATION
56 {
57 int NextEntryOffset; // When this entry is 0, there are no more processes to be read.
58 int NumberOfThreads;
59 long WorkingSetPrivateSize;
60 uint HardFaultCount;
61 uint NumberOfThreadsHighWatermark;
62 ulong CycleTime;
63 long CreateTime;
64 long UserTime;
65 long KernelTime;
66 UNICODE_STRING ImageName;
67 int BasePriority;
68 PTID /*Unique*/ProcessId;
69 PTID InheritedFromUniqueProcessId;
70 uint HandleCount;
71 uint SessionId;
72 size_t UniqueProcessKey;
73 size_t PeakVirtualSize;
74 size_t VirtualSize;
75 uint PageFaultCount;
76 size_t PeakWorkingSetSize;
77 size_t WorkingSetSize;
78 size_t QuotaPeakPagedPoolUsage;
79 size_t QuotaPagedPoolUsage;
80 size_t QuotaPeakNonPagedPoolUsage;
81 size_t QuotaNonPagedPoolUsage;
82 size_t PagefileUsage;
83 size_t PeakPagefileUsage;
84 size_t PrivatePageCount;
85 long ReadOperationCount;
86 long WriteOperationCount;
87 long OtherOperationCount;
88 long ReadTransferCount;
89 long WriteTransferCount;
90 long OtherTransferCount;
91
92 // SYSTEM_THREAD_INFORMATION or SYSTEM_EXTENDED_THREAD_INFORMATION structures follow.
93 }
94
95 struct _SYSTEM_THREAD_INFORMATION
96 {
97 long KernelTime;
98 long UserTime;
99 long CreateTime;
100 uint WaitTime;
101 void* StartAddress;
102 PTID ProcessId;
103 PTID ThreadId;
104 int Priority;
105 int BasePriority;
106 uint ContextSwitches;
107 uint ThreadState;
108 int WaitReason;
109 int reserved;
110 }
111
112 alias fnNtQuerySystemInformation = extern(Windows)
113 HRESULT function( uint SystemInformationClass, void* info, uint infoLength, uint* ReturnLength ) nothrow @nogc;
114
115 enum ThreadBasicInformation = 0;
116
117 struct THREAD_BASIC_INFORMATION
118 {
119 int ExitStatus;
120 void** TebBaseAddress;
121 PTID ProcessId;
122 PTID ThreadId;
123 size_t AffinityMask;
124 int Priority;
125 int BasePriority;
126 }
127
128 alias fnNtQueryInformationThread = extern(Windows)
129 int function( HANDLE ThreadHandle, uint ThreadInformationClass, void* buf, uint size, uint* ReturnLength ) nothrow @nogc;
130
131 enum SYNCHRONIZE = 0x00100000;
132 enum THREAD_GET_CONTEXT = 8;
133 enum THREAD_QUERY_INFORMATION = 0x40;
134 enum THREAD_SUSPEND_RESUME = 2;
135
136 ///////////////////////////////////////////////////////////////////
137 // get the thread environment block (TEB) of the thread with the given handle
138 static void** getTEB( HANDLE hnd ) nothrow @nogc
139 {
140 HANDLE nthnd = GetModuleHandleA( "NTDLL" );
141 assert( nthnd, "cannot get module handle for ntdll" );
142 fnNtQueryInformationThread fn = cast(fnNtQueryInformationThread) GetProcAddress( nthnd, "NtQueryInformationThread" );
143 assert( fn, "cannot find NtQueryInformationThread in ntdll" );
144
145 THREAD_BASIC_INFORMATION tbi;
146 int Status = (*fn)(hnd, ThreadBasicInformation, &tbi, tbi.sizeof, null);
147 assert(Status == 0);
148
149 return tbi.TebBaseAddress;
150 }
151
152 // get the thread environment block (TEB) of the thread with the given identifier
153 static void** getTEB( uint id ) nothrow @nogc
154 {
155 HANDLE hnd = OpenThread( THREAD_QUERY_INFORMATION, FALSE, id );
156 assert( hnd, "OpenThread failed" );
157
158 void** teb = getTEB( hnd );
159 CloseHandle( hnd );
160 return teb;
161 }
162
163 // get linear address of TEB of current thread
164 static void** getTEB() nothrow @nogc
165 {
166 version (D_InlineAsm_X86)
167 {
168 asm pure nothrow @nogc
169 {
170 naked;
171 mov EAX,FS:[0x18];
172 ret;
173 }
174 }
175 else version (D_InlineAsm_X86_64)
176 {
177 asm pure nothrow @nogc
178 {
179 naked;
180 mov RAX,0x30;
181 mov RAX,GS:[RAX]; // immediate value causes fixup
182 ret;
183 }
184 }
185 else version (GNU_InlineAsm)
186 {
187 void** teb;
188 version (X86)
189 asm pure nothrow @nogc { "movl %%fs:0x18, %0;" : "=r" (teb); }
190 else version (X86_64)
191 asm pure nothrow @nogc { "movq %%gs:0x30, %0;" : "=r" (teb); }
192 else
193 static assert(false);
194 return teb;
195 }
196 else
197 {
198 static assert(false);
199 }
200 }
201
202 // get the stack bottom (the top address) of the thread with the given handle
203 static void* getThreadStackBottom( HANDLE hnd ) nothrow @nogc
204 {
205 void** teb = getTEB( hnd );
206 return teb[1];
207 }
208
209 // get the stack bottom (the top address) of the thread with the given identifier
210 static void* getThreadStackBottom( uint id ) nothrow @nogc
211 {
212 void** teb = getTEB( id );
213 return teb[1];
214 }
215
216 // create a thread handle with full access to the thread with the given identifier
217 static HANDLE OpenThreadHandle( uint id ) nothrow @nogc
218 {
219 return OpenThread( SYNCHRONIZE|THREAD_GET_CONTEXT|THREAD_QUERY_INFORMATION|THREAD_SUSPEND_RESUME, FALSE, id );
220 }
221
222 ///////////////////////////////////////////////////////////////////
223 // enumerate threads of the given process calling the passed function on each thread
224 // using function instead of delegate here to avoid allocating closure
225 static bool enumProcessThreads( uint procid, bool function( uint id, void* context ) dg, void* context )
226 {
227 HANDLE hnd = GetModuleHandleA( "NTDLL" );
228 fnNtQuerySystemInformation fn = cast(fnNtQuerySystemInformation) GetProcAddress( hnd, "NtQuerySystemInformation" );
229 if ( !fn )
230 return false;
231
232 uint sz = 16384;
233 uint retLength;
234 HRESULT rc;
235 char* buf;
236 for ( ; ; )
237 {
238 buf = cast(char*) core.stdc.stdlib.malloc(sz);
239 if (!buf)
240 return false;
241 rc = fn( SystemProcessInformation, buf, sz, &retLength );
242 if ( rc != STATUS_INFO_LENGTH_MISMATCH )
243 break;
244 core.stdc.stdlib.free( buf );
245 sz *= 2;
246 }
247 scope(exit) core.stdc.stdlib.free( buf );
248
249 if (rc != 0)
250 return false;
251
252 auto pinfo = cast(_SYSTEM_PROCESS_INFORMATION*) buf;
253 auto pend = cast(_SYSTEM_PROCESS_INFORMATION*) (buf + retLength);
254 for ( ; pinfo < pend; )
255 {
256 if ( pinfo.ProcessId == procid )
257 {
258 auto tinfo = cast(_SYSTEM_THREAD_INFORMATION*)(pinfo + 1);
259 for ( int i = 0; i < pinfo.NumberOfThreads; i++, tinfo++ )
260 if ( tinfo.ProcessId == procid )
261 if ( !dg( cast(uint) tinfo.ThreadId, context ) ) // IDs are actually DWORDs
262 return false;
263 }
264 if ( pinfo.NextEntryOffset == 0 )
265 break;
266 pinfo = cast(_SYSTEM_PROCESS_INFORMATION*) (cast(char*) pinfo + pinfo.NextEntryOffset);
267 }
268 return true;
269 }
270
271 static bool enumProcessThreads( bool function( uint id, void* context ) dg, void* context )
272 {
273 return enumProcessThreads( GetCurrentProcessId(), dg, context );
274 }
275
276 // execute function on the TLS for the given thread
277 alias extern(C) void function() externCVoidFunc;
278 static void impersonate_thread( uint id, externCVoidFunc fn )
279 {
280 impersonate_thread(id, () => fn());
281 }
282
283 static void impersonate_thread( uint id, scope void delegate() dg)
284 {
285 if ( id == GetCurrentThreadId() )
286 {
287 dg();
288 return;
289 }
290
291 // temporarily set current TLS array pointer to the array pointer of the referenced thread
292 void** curteb = getTEB();
293 void** teb = getTEB( id );
294 assert( teb && curteb );
295
296 void** curtlsarray = cast(void**) curteb[11];
297 void** tlsarray = cast(void**) teb[11];
298 if ( !curtlsarray || !tlsarray )
299 return;
300
301 curteb[11] = tlsarray;
302
303 // swap out the TLS slots aswell
304 version (Win64)
305 {
306 enum TEB_offset_TlsSlots = 0x1480;
307 enum TEB_offset_TlsExpansionSlots = 0x1780;
308 }
309 else
310 {
311 enum TEB_offset_TlsSlots = 0xE10;
312 enum TEB_offset_TlsExpansionSlots = 0xF94;
313 }
314 void* tlsSlotsAdr(void** teb) { return cast(void*) teb + TEB_offset_TlsSlots; }
315 ref void* tlsExpansionSlots(void** teb) { return *cast(void**)(cast(void*) teb + TEB_offset_TlsExpansionSlots); }
316
317 import core.stdc.string;
318 void*[64] slots = void;
319 memcpy(slots.ptr, tlsSlotsAdr(curteb), slots.sizeof);
320 void* extraSlots = tlsExpansionSlots(curteb);
321
322 memcpy(tlsSlotsAdr(curteb), tlsSlotsAdr(teb), slots.sizeof);
323 tlsExpansionSlots(curteb) = tlsExpansionSlots(teb);
324
325 dg();
326
327 curteb[11] = curtlsarray;
328
329 // copy the TLS slots back in case they have been changed in dg
330 memcpy(tlsSlotsAdr(teb), tlsSlotsAdr(curteb), slots.sizeof);
331 tlsExpansionSlots(teb) = tlsExpansionSlots(curteb);
332
333 memcpy(tlsSlotsAdr(curteb), slots.ptr, slots.sizeof);
334 tlsExpansionSlots(curteb) = extraSlots;
335 }
336 }
337
338 public:
339 // forward as few symbols as possible into the "global" name space
340 alias thread_aux.getTEB getTEB;
341 alias thread_aux.getThreadStackBottom getThreadStackBottom;
342 alias thread_aux.OpenThreadHandle OpenThreadHandle;
343 alias thread_aux.enumProcessThreads enumProcessThreads;
344 alias thread_aux.impersonate_thread impersonate_thread;
345
346 // get the start of the TLS memory of the thread with the given handle
347 void* GetTlsDataAddress( HANDLE hnd ) nothrow
348 {
349 if ( void** teb = getTEB( hnd ) )
350 if ( void** tlsarray = cast(void**) teb[11] )
351 return tlsarray[_tls_index];
352 return null;
353 }
354
355 // get the start of the TLS memory of the thread with the given identifier
356 void* GetTlsDataAddress( uint id ) nothrow
357 {
358 HANDLE hnd = OpenThread( thread_aux.THREAD_QUERY_INFORMATION, FALSE, id );
359 assert( hnd, "OpenThread failed" );
360
361 void* tls = GetTlsDataAddress( hnd );
362 CloseHandle( hnd );
363 return tls;
364 }
365
366 ///////////////////////////////////////////////////////////////////
367 // run rt_moduleTlsCtor in the context of the given thread
368 void thread_moduleTlsCtor( uint id )
369 {
370 thread_aux.impersonate_thread(id, &rt_moduleTlsCtor);
371 }
372
373 ///////////////////////////////////////////////////////////////////
374 // run rt_moduleTlsDtor in the context of the given thread
375 void thread_moduleTlsDtor( uint id )
376 {
377 thread_aux.impersonate_thread(id, &rt_moduleTlsDtor);
378 }