systhrd.inc 25 KB

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