systhrd.inc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 2002 by Peter Vreman,
  4. member of the Free Pascal development team.
  5. Linux (pthreads) threading support implementation
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. **********************************************************************}
  12. {*****************************************************************************
  13. Local WINApi imports
  14. *****************************************************************************}
  15. {$ifndef WINCE}
  16. function TlsAlloc : DWord;
  17. stdcall;external KernelDLL name 'TlsAlloc';
  18. function TlsFree(dwTlsIndex : DWord) : LongBool;
  19. stdcall;external KernelDLL name 'TlsFree';
  20. {$endif WINCE}
  21. function TlsGetValue(dwTlsIndex : DWord) : pointer;
  22. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'TlsGetValue';
  23. function TlsSetValue(dwTlsIndex : DWord;lpTlsValue : pointer) : LongBool;
  24. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'TlsSetValue';
  25. function CreateThread(lpThreadAttributes : pointer;
  26. dwStackSize : SIZE_T; lpStartAddress : pointer;lpParameter : pointer;
  27. dwCreationFlags : DWord;var lpThreadId : DWord) : THandle;
  28. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'CreateThread';
  29. procedure ExitThread(dwExitCode : DWord);
  30. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'ExitThread';
  31. procedure Sleep(dwMilliseconds: DWord); {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'Sleep';
  32. function WinSuspendThread (threadHandle : THandle) : dword; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'SuspendThread';
  33. function WinResumeThread (threadHandle : THandle) : dword; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'ResumeThread';
  34. function WinCloseHandle (threadHandle : THandle) : dword; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'CloseHandle';
  35. function TerminateThread (threadHandle : THandle; var exitCode : dword) : boolean; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'TerminateThread';
  36. function WaitForSingleObject (hHandle : THandle;Milliseconds: dword): dword; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'WaitForSingleObject';
  37. function WinThreadSetPriority (threadHandle : THandle; Prio: longint): boolean; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'SetThreadPriority';
  38. function WinThreadGetPriority (threadHandle : THandle): LongInt; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'GetThreadPriority';
  39. {$ifndef WINCE}
  40. function WinGetCurrentThread: THandle; stdcall; external KernelDLL name 'GetCurrentThread';
  41. function WinOpenThread(dwDesiredAccess: DWord; bInheritHandle: Boolean; dwThreadId: DWord): THandle; stdcall; external KernelDLL name 'OpenThread';
  42. function WinIsDebuggerPresent: Boolean; stdcall; external KernelDLL name 'IsDebuggerPresent';
  43. type
  44. TSetThreadDescription = function(threadHandle: THandle; lpThreadDescription: PWideChar): HResult; stdcall;
  45. var
  46. WinSetThreadDescription: TSetThreadDescription;
  47. function CreateEvent(lpEventAttributes:pointer;bManualReset:longbool;bInitialState:longbool;lpName:PAnsiChar): THandle; stdcall; external KernelDLL name 'CreateEventA';
  48. function ResetEvent(hEvent:THandle):LONGBOOL; stdcall; external KernelDLL name 'ResetEvent';
  49. function SetEvent(hEvent:THandle):LONGBOOL; stdcall; external KernelDLL name 'SetEvent';
  50. {$endif WINCE}
  51. procedure WinInitCriticalSection(var cs : TRTLCriticalSection);
  52. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'InitializeCriticalSection';
  53. procedure WinDoneCriticalSection(var cs : TRTLCriticalSection);
  54. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'DeleteCriticalSection';
  55. procedure WinEnterCriticalSection(var cs : TRTLCriticalSection);
  56. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'EnterCriticalSection';
  57. procedure WinLeaveCriticalSection(var cs : TRTLCriticalSection);
  58. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'LeaveCriticalSection';
  59. CONST
  60. WAIT_OBJECT_0 = 0;
  61. WAIT_TIMEOUT = $102;
  62. function WinTryEnterCriticalSection(var cs : TRTLCriticalSection):longint;
  63. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'TryEnterCriticalSection';
  64. {*****************************************************************************
  65. Threadvar support
  66. *****************************************************************************}
  67. type
  68. { If IsLibrary, prepended to threadvar blocks allocated with HeapAlloc to forcefully free them in DLL_PROCESS_DETACH (SysFiniMultithreading). }
  69. PThreadvarNode=^TThreadvarNode;
  70. TThreadvarNode=record
  71. prev, next : PThreadvarNode;
  72. end;
  73. const
  74. { Align threadvars on 2 * sizeof(pointer)... HeapAlloc has this alignment, so no point in more. }
  75. AlignedThreadvarNodeSize=(sizeof(TThreadVarNode)+2*sizeof(pointer)-1) and -(2*sizeof(pointer));
  76. var
  77. // public names are used by heaptrc unit
  78. threadvarblocksize : dword; public name '_FPC_TlsSize';
  79. {$ifdef FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  80. TLSKey : PDword = nil; public name '_FPC_TlsKey';
  81. {$else FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  82. TLSKeyVar : DWord = $ffffffff;
  83. TLSKey : PDWord = @TLSKeyVar; public name '_FPC_TlsKey';
  84. {$endif FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  85. DllProcessAttachPerformed : boolean;
  86. { AllThreadvars* are used only when IsLibrary. (Careful!)
  87. Could be used when not IsLibrary as a no-op to simplify the code,
  88. but this would require publishing SysFiniMultithreading to be called from sysinit.pp:Exec_Tls_callback.DLL_PROCESS_DETACH. }
  89. AllThreadvarsLock : TRTLCriticalSection;
  90. AllThreadvars : PThreadvarNode;
  91. procedure SysInitThreadvar(var offset : dword;size : dword);
  92. begin
  93. offset:=threadvarblocksize;
  94. {$ifdef CPUARM}
  95. // Data must be allocated at 4 bytes boundary for ARM
  96. size:=(size + 3) and not dword(3);
  97. {$endif CPUARM}
  98. inc(threadvarblocksize,size);
  99. end;
  100. procedure SysAllocateThreadVars; public name '_FPC_SysAllocateThreadVars';
  101. var
  102. tn,nx : PThreadvarNode;
  103. prepend,errorsave : dword;
  104. begin
  105. { we've to allocate the memory from system }
  106. { because the FPC heap management uses }
  107. { exceptions which use threadvars but }
  108. { these aren't allocated yet ... }
  109. { allocate room on the heap for the thread vars }
  110. errorsave:=GetLastError;
  111. if tlskey^=$ffffffff then
  112. RunError(226);
  113. if TlsGetValue(tlskey^)=nil then
  114. begin
  115. prepend:=ord(IsLibrary)*AlignedThreadvarNodeSize;
  116. tn:=HeapAlloc(GetProcessHeap,HEAP_ZERO_MEMORY,prepend+threadvarblocksize);
  117. if tn=nil then
  118. RunError(226);
  119. TlsSetValue(tlskey^,pointer(tn)+prepend);
  120. if IsLibrary then
  121. begin
  122. { Add tn to AllThreadvars. }
  123. WinEnterCriticalSection(AllThreadvarsLock);
  124. nx:=AllThreadvars;
  125. tn^.next:=nx; { “tn^.prev := nil” can be omitted thanks to HEAP_ZERO_MEMORY. }
  126. if Assigned(nx) then
  127. nx^.prev:=tn;
  128. AllThreadvars:=tn;
  129. WinLeaveCriticalSection(AllThreadvarsLock);
  130. end;
  131. end;
  132. SetLastError(errorsave);
  133. end;
  134. function SysRelocateThreadvar(offset : dword) : pointer; forward;
  135. procedure SysInitTLS;
  136. begin
  137. { do not check IsMultiThread, as program could have altered it, out of Delphi habit }
  138. { the thread attach/detach code uses locks to avoid multiple calls of this }
  139. if TLSKey^=$ffffffff then
  140. begin
  141. { We're still running in single thread mode, setup the TLS }
  142. if IsLibrary then
  143. WinInitCriticalSection(AllThreadvarsLock);
  144. TLSKey^:=TlsAlloc;
  145. InitThreadVars(@SysRelocateThreadvar);
  146. end;
  147. end;
  148. procedure SysFiniMultithreading;
  149. var
  150. tn,nx : PThreadvarNode;
  151. begin
  152. if TLSKey^=$ffffffff then
  153. exit;
  154. TlsFree(TLSKey^);
  155. TLSKey^:=$ffffffff;
  156. if IsLibrary then
  157. begin
  158. { Purge all remaining threadvars! System doesn’t preface DLL_PROCESS_DETACH by sending DLL_THREAD_DETACH to all threads,
  159. so think of it as of emulating the threadvar destroying part of DLL_THREAD_DETACH for all threads that require it. }
  160. tn:=AllThreadvars;
  161. AllThreadvars:=nil;
  162. while Assigned(tn) do
  163. begin
  164. nx:=tn^.next;
  165. HeapFree(GetProcessHeap,0,tn);
  166. tn:=nx;
  167. end;
  168. WinDoneCriticalSection(AllThreadvarsLock);
  169. end;
  170. end;
  171. { Directly access thread environment block (TEB). If there is a value, use it. If there is not, jump to TrulyRelocateThreadvar that can allocate it.
  172. TrulyRelocateThreadvar is several (5+) times slower by itself; shortcutting SetLastError on errorsave = 0 helps a bit (reduces to 3.5× maybe :D).
  173. General info (in particular, stories about de facto stability guarantees):
  174. https://en.wikipedia.org/wiki/Win32_Thread_Information_Block
  175. TEB layout:
  176. https://github.com/wine-mirror/wine/blob/badaed641928edb8f2426d9f12d16c88b479e1e8/include/winternl.h#L431
  177. “Why load fs:[0x18] into a register and then dereference that, instead of just going for fs:[n] directly?”
  178. https://devblogs.microsoft.com/oldnewthing/20220919-00/?p=107195
  179. TL;DR: even in Windows sources, TlsGetValue is written in relatively high-level manner and not overly optimized. }
  180. {$undef FPC_HAS_SYSRELOCATETHREADVAR_ASM}
  181. {$ifndef wince} { Don’t know a thing, maybe WinCE TEB is compatible... :D https://stackoverflow.com/questions/1099311/windows-ce-internals-teb-thread-environment-block }
  182. {$if defined(cpui386)}
  183. {$define FPC_HAS_SYSRELOCATETHREADVAR_ASM}
  184. function TrulyRelocateThreadvar(offset : dword) : pointer; forward;
  185. function SysRelocateThreadvar(offset : dword) : pointer; assembler; nostackframe;
  186. { eax = offset }
  187. const
  188. TlsSlots = $E10; { void* TlsSlots[64] @ fs:[E10h]. }
  189. TlsExpansionSlots = $F94; { void** TlsExpansionSlots @ fs:[F94h] }
  190. asm
  191. mov TLSKey, %edx
  192. mov (%edx), %edx { edx = TLSKey^. }
  193. cmp $0x40, %edx { There are 64 static slots + 1024 dynamic slots. }
  194. jae .LExp
  195. mov %fs:TlsSlots(,%edx,4), %edx { Read TLSKey^-th slot. }
  196. test %edx, %edx
  197. jz .LOops
  198. add %edx, %eax { result := TlsGetValue(TLSKey^) + offset. }
  199. ret
  200. .LOops: jmp TrulyRelocateThreadvar { Save on relative jumps :) }
  201. .LExp: cmp $0x440, %edx
  202. jae .LOops { Will fail as 0x440 = 1088 = 64 static + 1024 dynamic is the limit on TLS indices. }
  203. mov %fs:TlsExpansionSlots, %ecx { ecx = TlsExpansionSlots. }
  204. test %ecx, %ecx
  205. jz .LOops { No TlsExpansionSlots allocated. }
  206. mov -0x100(%ecx,%edx,4), %edx { Read (TLSKey^ − 64)-th dynamic slot. }
  207. test %edx, %edx
  208. jz .LOops
  209. add %edx, %eax { result := TlsGetValue(TLSKey^) + offset. }
  210. end;
  211. {$elseif defined(cpux86_64)}
  212. {$define FPC_HAS_SYSRELOCATETHREADVAR_ASM}
  213. function TrulyRelocateThreadvar(offset : dword) : pointer; forward;
  214. function SysRelocateThreadvar(offset : dword) : pointer; assembler; nostackframe;
  215. { ecx = offset }
  216. const { Same as above but 64-bit: TEB pointer is in GS register, different offsets. }
  217. TlsSlots = $1480;
  218. TlsExpansionSlots = $1780;
  219. asm
  220. mov TLSKey(%rip), %rdx
  221. mov (%rdx), %edx { edx = TLSKey^. }
  222. cmp $0x40, %edx
  223. jae .LExp
  224. mov %gs:TlsSlots(,%rdx,8), %rax
  225. test %rax, %rax
  226. jz .LOops
  227. add %rcx, %rax { Hopefully offset is zero-extended on entry. }
  228. ret
  229. .LOops: jmp TrulyRelocateThreadvar
  230. .LExp: cmp $0x440, %edx
  231. jae .LOops
  232. mov %gs:TlsExpansionSlots, %rax
  233. test %rax, %rax
  234. jz .LOops
  235. mov -0x200(%rax,%rdx,8), %rax
  236. test %rax, %rax
  237. jz .LOops
  238. add %rcx, %rax
  239. end;
  240. {$endif implement SysRelocateThreadvar with assembly}
  241. {$endif not wince}
  242. function {$ifdef FPC_HAS_SYSRELOCATETHREADVAR_ASM} TrulyRelocateThreadvar {$else} SysRelocateThreadvar {$endif} (offset : dword) : pointer;
  243. var
  244. dataindex : pointer;
  245. errorsave : dword;
  246. begin
  247. errorsave:=GetLastError;
  248. dataindex:=TlsGetValue(tlskey^);
  249. if dataindex=nil then
  250. begin
  251. SysAllocateThreadVars;
  252. dataindex:=TlsGetValue(tlskey^);
  253. InitThread($1000000);
  254. end;
  255. SetLastError(errorsave);
  256. Result:=DataIndex+Offset;
  257. end;
  258. procedure SysReleaseThreadVars;
  259. var
  260. tn,prev,next: PThreadvarNode;
  261. begin
  262. if TLSKey^=$ffffffff then
  263. exit;
  264. tn:=TlsGetValue(TLSKey^);
  265. if tn=nil then
  266. exit;
  267. TlsSetValue(TLSKey^,nil);
  268. if IsLibrary then
  269. begin
  270. dec(pointer(tn),AlignedThreadvarNodeSize);
  271. { Remove tn from AllThreadvars. }
  272. WinEnterCriticalSection(AllThreadvarsLock);
  273. prev:=tn^.prev;
  274. next:=tn^.next;
  275. if Assigned(next) then
  276. next^.prev:=prev;
  277. if Assigned(prev) then
  278. prev^.next:=next
  279. else
  280. AllThreadvars:=next;
  281. WinLeaveCriticalSection(AllThreadvarsLock);
  282. end;
  283. HeapFree(GetProcessHeap,0,tn);
  284. end;
  285. {*****************************************************************************
  286. Thread starting
  287. *****************************************************************************}
  288. type
  289. pthreadinfo = ^tthreadinfo;
  290. tthreadinfo = record
  291. f : tthreadfunc;
  292. p : pointer;
  293. stklen : ptruint;
  294. end;
  295. function ThreadMain(param : pointer) : Longint; {$ifdef wince}cdecl{$else}stdcall{$endif};
  296. var
  297. ti : tthreadinfo;
  298. begin
  299. { Copy parameter to local data }
  300. ti:=pthreadinfo(param)^;
  301. { Handle all possible threadvar models:
  302. - dynamic threadvars: initialized either in DllMain,
  303. or upon accessing the threadvar ThreadID;
  304. - static threadvars+TLS callback: initialized in TLS callback;
  305. - static threadvars, no callback: ThreadID remains 0 and
  306. initialization happens here. }
  307. if ThreadID=TThreadID(0) then
  308. begin
  309. InitThread(ti.stklen);
  310. {$ifndef wince}
  311. {$ifdef win32}
  312. if Assigned(SetThreadStackGuarantee) then
  313. {$endif win32}
  314. SetThreadStackGuaranteeTo(StackMargin);
  315. {$endif wince}
  316. end;
  317. dispose(pthreadinfo(param));
  318. { Start thread function }
  319. {$ifdef DEBUG_MT}
  320. writeln('Jumping to thread function of thread ',Win32GetCurrentThreadId);
  321. {$endif DEBUG_MT}
  322. {$if defined(FPC_USE_WIN64_SEH) or defined(FPC_USE_WIN32_SEH)}
  323. { use special 'top-level' exception handler around the thread function }
  324. ThreadMain:=main_wrapper(ti.p,pointer(ti.f));
  325. {$else FPC_USE_WIN64_SEH}
  326. ThreadMain:=ti.f(ti.p);
  327. {$endif FPC_USE_WIN64_SEH or FPC_USE_WIN32_SEH}
  328. end;
  329. function SysBeginThread(sa : Pointer;stacksize : ptruint;
  330. ThreadFunction : tthreadfunc;p : pointer;
  331. creationFlags : dword;var ThreadId : TThreadID) : TThreadID;
  332. var
  333. ti : pthreadinfo;
  334. _threadid : dword;
  335. begin
  336. {$ifdef DEBUG_MT}
  337. writeln('Creating new thread');
  338. {$endif DEBUG_MT}
  339. { Initialize multithreading if not done }
  340. SysInitTLS;
  341. if not IsMultiThread then
  342. begin
  343. { lazy initialize thread support }
  344. LazyInitThreading;
  345. IsMultiThread:=true;
  346. end;
  347. { the only way to pass data to the newly created thread
  348. in a MT safe way, is to use the heap }
  349. new(ti);
  350. ti^.f:=ThreadFunction;
  351. ti^.p:=p;
  352. ti^.stklen:=stacksize;
  353. {$ifdef DEBUG_MT}
  354. writeln('Starting new thread');
  355. {$endif DEBUG_MT}
  356. _threadid:=0;
  357. SysBeginThread:=CreateThread(sa,stacksize,@ThreadMain,ti,creationflags,_threadid);
  358. { creation failed? if yes, we dispose the parameter record }
  359. if SysBeginThread=0 then
  360. begin
  361. {$ifdef DEBUG_MT}
  362. writeln('Thread creation failed');
  363. {$endif DEBUG_MT}
  364. dispose(ti);
  365. end;
  366. ThreadID:=_threadid;
  367. end;
  368. procedure SysEndThread(ExitCode : DWord);
  369. begin
  370. DoneThread;
  371. ExitThread(ExitCode);
  372. end;
  373. procedure SysThreadSwitch;
  374. begin
  375. Sleep(0);
  376. end;
  377. function SysSuspendThread (threadHandle : TThreadID) : dword;
  378. begin
  379. SysSuspendThread:=WinSuspendThread(threadHandle);
  380. end;
  381. function SysResumeThread (threadHandle : TThreadID) : dword;
  382. begin
  383. SysResumeThread:=WinResumeThread(threadHandle);
  384. end;
  385. function SysKillThread (threadHandle : TThreadID) : dword;
  386. var exitCode : dword;
  387. begin
  388. if not TerminateThread (threadHandle, exitCode) then
  389. SysKillThread := GetLastError
  390. else
  391. SysKillThread := 0;
  392. end;
  393. function SysCloseThread (threadHandle : TThreadID) : dword;
  394. begin
  395. SysCloseThread:=winCloseHandle(threadHandle);
  396. end;
  397. function SysWaitForThreadTerminate (threadHandle : TThreadID; TimeoutMs : longint) : dword;
  398. begin
  399. // shouldn't this be a msgwait in case the thread creates "Windows" See comment in waitforsingle?
  400. if timeoutMs = 0 then dec (timeoutMs); // $ffffffff is INFINITE
  401. // does waiting on thread require cowait too ?
  402. SysWaitForThreadTerminate := WaitForSingleObject(threadHandle, TimeoutMs);
  403. end;
  404. function SysThreadSetPriority (threadHandle : TThreadID; Prio: longint): boolean; {-15..+15, 0=normal}
  405. begin
  406. SysThreadSetPriority:=WinThreadSetPriority(threadHandle,Prio);
  407. end;
  408. function SysThreadGetPriority (threadHandle : TThreadID): longint;
  409. begin
  410. SysThreadGetPriority:=WinThreadGetPriority(threadHandle);
  411. end;
  412. function SysGetCurrentThreadId : TThreadID;
  413. begin
  414. SysGetCurrentThreadId:=Win32GetCurrentThreadId;
  415. end;
  416. {$ifndef WINCE}
  417. { following method is supported on older Windows versions AND currently only supported method by GDB }
  418. procedure RaiseMSVCExceptionMethod(threadHandle: TThreadID; const ThreadName: AnsiString);
  419. const
  420. MS_VC_EXCEPTION: DWord = $406D1388;
  421. type
  422. THREADNAME_INFO = record
  423. dwType: DWord; // Must be 0x1000.
  424. szName: PAnsiChar; // Pointer to name (in user addr space).
  425. dwThreadID: DWord; // Thread ID (-1=caller thread).
  426. dwFlags: DWord; // Reserved for future use, must be zero.
  427. end;
  428. var
  429. thrdinfo: THREADNAME_INFO;
  430. begin
  431. thrdinfo.dwType:=$1000;
  432. thrdinfo.szName:=@ThreadName[1];
  433. thrdinfo.dwThreadID:=threadHandle;
  434. thrdinfo.dwFlags:=0;
  435. try
  436. RaiseException(MS_VC_EXCEPTION, 0, SizeOf(thrdinfo) div SizeOf(PtrUInt), @thrdinfo);
  437. except
  438. {do nothing}
  439. end;
  440. end;
  441. { following method needs at least Windows 10 version 1607 or Windows Server 2016 }
  442. procedure SetThreadDescriptionMethod(threadHandle: TThreadID; const ThreadName: UnicodeString);
  443. var
  444. thrdhandle: THandle;
  445. ClosingNeeded: Boolean;
  446. begin
  447. if threadHandle=TThreadID(-1) then
  448. begin
  449. thrdhandle:=WinGetCurrentThread;
  450. ClosingNeeded:=False;
  451. end
  452. else
  453. begin
  454. thrdhandle:=WinOpenThread($0400, False, threadHandle);
  455. ClosingNeeded:=True;
  456. end;
  457. WinSetThreadDescription(thrdhandle, @ThreadName[1]);
  458. if ClosingNeeded then
  459. begin
  460. CloseHandle(thrdhandle);
  461. end;
  462. end;
  463. {$endif WINCE}
  464. procedure SysSetThreadDebugNameA(threadHandle: TThreadID; const ThreadName: AnsiString);
  465. begin
  466. {$ifndef WINCE}
  467. if ThreadName = '' then
  468. Exit;
  469. if WinIsDebuggerPresent then
  470. begin
  471. RaiseMSVCExceptionMethod(threadHandle, ThreadName);
  472. end;
  473. if Assigned(WinSetThreadDescription) then
  474. begin
  475. SetThreadDescriptionMethod(threadHandle, UnicodeString(ThreadName));
  476. end;
  477. {$else WINCE}
  478. {$Warning SetThreadDebugNameA needs to be implemented}
  479. {$endif WINCE}
  480. end;
  481. procedure SysSetThreadDebugNameU(threadHandle: TThreadID; const ThreadName: UnicodeString);
  482. begin
  483. {$ifndef WINCE}
  484. if ThreadName = '' then
  485. Exit;
  486. if WinIsDebuggerPresent then
  487. begin
  488. RaiseMSVCExceptionMethod(threadHandle, AnsiString(ThreadName));
  489. end;
  490. if Assigned(WinSetThreadDescription) then
  491. begin
  492. SetThreadDescriptionMethod(threadHandle, ThreadName);
  493. end;
  494. {$else WINCE}
  495. {$Warning SetThreadDebugNameU needs to be implemented}
  496. {$endif WINCE}
  497. end;
  498. {*****************************************************************************
  499. Delphi/Win32 compatibility
  500. *****************************************************************************}
  501. procedure SySInitCriticalSection(var cs);
  502. begin
  503. WinInitCriticalSection(PRTLCriticalSection(@cs)^);
  504. end;
  505. procedure SysDoneCriticalSection(var cs);
  506. begin
  507. WinDoneCriticalSection(PRTLCriticalSection(@cs)^);
  508. end;
  509. procedure SysEnterCriticalSection(var cs);
  510. begin
  511. WinEnterCriticalSection(PRTLCriticalSection(@cs)^);
  512. end;
  513. function SysTryEnterCriticalSection(var cs):longint;
  514. begin
  515. result:=WinTryEnterCriticalSection(PRTLCriticalSection(@cs)^);
  516. end;
  517. procedure SySLeaveCriticalSection(var cs);
  518. begin
  519. WinLeaveCriticalSection(PRTLCriticalSection(@cs)^);
  520. end;
  521. Const
  522. wrSignaled = 0;
  523. wrTimeout = 1;
  524. wrAbandoned= 2;
  525. wrError = 3;
  526. function intBasicEventCreate(EventAttributes : Pointer;
  527. AManualReset,InitialState : Boolean;const Name : ansistring):pEventState;
  528. begin
  529. Result := PEventState(CreateEvent(EventAttributes, AManualReset, InitialState,Pointer(Name)));
  530. end;
  531. procedure intbasiceventdestroy(state:peventstate);
  532. begin
  533. closehandle(THandle(state));
  534. end;
  535. procedure intbasiceventResetEvent(state:peventstate);
  536. begin
  537. ResetEvent(THandle(state))
  538. end;
  539. procedure intbasiceventSetEvent(state:peventstate);
  540. begin
  541. SetEvent(THandle(state));
  542. end;
  543. function FirstCoWaitForMultipleHandles(dwFlags, dwTimeout: DWORD; cHandles: uint32; pHandles: PWOHandleArray; out lpdwindex: DWORD): HRESULT; stdcall; forward;
  544. var
  545. Ole32Dll: THandle = 0; { Unloaded at win32 & win64 system_exit. }
  546. CoWaitForMultipleHandlesImpl: function(dwFlags, dwTimeout: DWORD; cHandles: uint32; pHandles: PWOHandleArray; out lpdwindex: DWORD): HRESULT; stdcall
  547. = @FirstCoWaitForMultipleHandles;
  548. function FirstCoWaitForMultipleHandles(dwFlags, dwTimeout: DWORD; cHandles: uint32; pHandles: PWOHandleArray; out lpdwindex: DWORD): HRESULT; stdcall;
  549. var
  550. LocalOle32Dll: THandle;
  551. begin
  552. if Ole32Dll = 0 then
  553. begin
  554. LocalOle32Dll := WinLoadLibraryW('ole32.dll');
  555. if InterlockedCompareExchange(Pointer(Ole32Dll), Pointer(LocalOle32Dll), nil) <> nil then
  556. WinFreeLibrary(LocalOle32Dll);
  557. end;
  558. CodePointer(CoWaitForMultipleHandlesImpl) := WinGetProcAddress(Ole32Dll, 'CoWaitForMultipleHandles');
  559. Result := CoWaitForMultipleHandlesImpl(dwFlags, dwTimeout, cHandles, pHandles, lpdwindex);
  560. end;
  561. function CoWaitForMultipleHandles(dwFlags, dwTimeout: DWORD; cHandles: uint32; pHandles: PWOHandleArray; out lpdwindex: DWORD): HRESULT;
  562. begin
  563. Result := CoWaitForMultipleHandlesImpl(dwFlags, dwTimeout, cHandles, pHandles, lpdwindex);
  564. end;
  565. function intbasiceventWaitFor(Timeout : Cardinal;state:peventstate;UseCOMWait: Boolean = False) : longint;
  566. const COWAIT_DEFAULT = 0;
  567. RPC_S_CALLPENDING = HRESULT($80010115);
  568. var SignaledIndex : DWORD;
  569. begin
  570. if UseComWait Then
  571. case CoWaitForMultipleHandles(COWAIT_DEFAULT, Timeout, 1, PWOHandleArray(@state), SignaledIndex) of
  572. S_OK: Result := wrSignaled;
  573. RPC_S_CALLPENDING: Result := wrTimeout;
  574. else Result := wrError;
  575. end
  576. else
  577. case WaitForSingleObject(THandle(state), Timeout) of
  578. WAIT_OBJECT_0: Result := wrSignaled;
  579. WAIT_TIMEOUT: Result := wrTimeout;
  580. else result := wrError; { WAIT_FAILED or any other value. Note that only mutex waits can return WAIT_ABANDONED. }
  581. end;
  582. end;
  583. function intRTLEventCreate: PRTLEvent;
  584. begin
  585. Result := PRTLEVENT(CreateEvent(nil, false, false, nil));
  586. end;
  587. procedure intRTLEventDestroy(AEvent: PRTLEvent);
  588. begin
  589. CloseHandle(THANDLE(AEvent));
  590. end;
  591. procedure intRTLEventSetEvent(AEvent: PRTLEvent);
  592. begin
  593. SetEvent(THANDLE(AEvent));
  594. end;
  595. procedure intRTLEventResetEvent(AEvent: PRTLEvent);
  596. begin
  597. ResetEvent(THANDLE(AEvent));
  598. end;
  599. procedure intRTLEventWaitFor(AEvent: PRTLEvent);
  600. const
  601. INFINITE=dword(-1);
  602. begin
  603. WaitForSingleObject(THANDLE(AEvent), INFINITE);
  604. end;
  605. procedure intRTLEventWaitForTimeout(AEvent: PRTLEvent;timeout : longint);
  606. begin
  607. WaitForSingleObject(THANDLE(AEvent), timeout);
  608. end;
  609. Procedure InitSystemThreads;public name '_FPC_InitSystemThreads';
  610. var
  611. WinThreadManager : TThreadManager;
  612. {$ifndef WINCE}
  613. KernelHandle : THandle;
  614. {$endif}
  615. begin
  616. With WinThreadManager do
  617. begin
  618. InitManager :=Nil;
  619. DoneManager :=Nil;
  620. BeginThread :=@SysBeginThread;
  621. EndThread :=@SysEndThread;
  622. SuspendThread :=@SysSuspendThread;
  623. ResumeThread :=@SysResumeThread;
  624. KillThread :=@SysKillThread;
  625. ThreadSwitch :=@SysThreadSwitch;
  626. CloseThread :=@SysCloseThread;
  627. WaitForThreadTerminate :=@SysWaitForThreadTerminate;
  628. ThreadSetPriority :=@SysThreadSetPriority;
  629. ThreadGetPriority :=@SysThreadGetPriority;
  630. GetCurrentThreadId :=@SysGetCurrentThreadId;
  631. SetThreadDebugNameA :=@SysSetThreadDebugNameA;
  632. SetThreadDebugNameU :=@SysSetThreadDebugNameU;
  633. InitCriticalSection :=@SysInitCriticalSection;
  634. DoneCriticalSection :=@SysDoneCriticalSection;
  635. EnterCriticalSection :=@SysEnterCriticalSection;
  636. TryEnterCriticalSection:=@SysTryEnterCriticalSection;
  637. LeaveCriticalSection :=@SysLeaveCriticalSection;
  638. InitThreadVar :=@SysInitThreadVar;
  639. RelocateThreadVar :=@SysRelocateThreadVar;
  640. AllocateThreadVars :=@SysAllocateThreadVars;
  641. ReleaseThreadVars :=@SysReleaseThreadVars;
  642. BasicEventCreate :=@intBasicEventCreate;
  643. BasicEventDestroy :=@intBasicEventDestroy;
  644. BasicEventResetEvent :=@intBasicEventResetEvent;
  645. BasicEventSetEvent :=@intBasicEventSetEvent;
  646. BasiceventWaitFor :=@intBasiceventWaitFor;
  647. RTLEventCreate :=@intRTLEventCreate;
  648. RTLEventDestroy :=@intRTLEventDestroy;
  649. RTLEventSetEvent :=@intRTLEventSetEvent;
  650. RTLEventResetEvent :=@intRTLEventResetEvent;
  651. RTLEventWaitFor :=@intRTLEventWaitFor;
  652. RTLEventWaitForTimeout :=@intRTLEventWaitForTimeout;
  653. end;
  654. SetThreadManager(WinThreadManager);
  655. ThreadID := GetCurrentThreadID;
  656. {$ifndef FPC_USE_TLS_DIRECTORY}
  657. if IsLibrary then
  658. {$endif}
  659. SysInitTLS;
  660. {$ifndef WINCE}
  661. KernelHandle:=GetModuleHandle(KernelDLL);
  662. {$endif}
  663. {$ifndef WINCE}
  664. if KernelHandle<>0 then
  665. begin
  666. WinSetThreadDescription:=TSetThreadDescription(WinGetProcAddress(KernelHandle, 'SetThreadDescription'));
  667. end;
  668. {$endif WINCE}
  669. end;