classes.inc 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185
  1. {
  2. This file is part of the Free Component Library (FCL)
  3. Copyright (c) 1999-2000 by Michael Van Canneyt and Florian Klaempfl
  4. See the file COPYING.FPC, included in this distribution,
  5. for details about the copyright.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  9. **********************************************************************}
  10. {**********************************************************************
  11. * Class implementations are in separate files. *
  12. **********************************************************************}
  13. type
  14. {$ifdef CPU16}
  15. TFilerFlagsInt = Byte;
  16. {$else CPU16}
  17. TFilerFlagsInt = LongInt;
  18. {$endif CPU16}
  19. var
  20. ClassList : TThreadlist;
  21. ClassAliasList : TStringList;
  22. {
  23. Include all message strings
  24. Add a language with IFDEF LANG_NAME
  25. just befor the final ELSE. This way English will always be the default.
  26. }
  27. {$IFDEF LANG_GERMAN}
  28. {$i constsg.inc}
  29. {$ELSE}
  30. {$IFDEF LANG_SPANISH}
  31. {$i constss.inc}
  32. {$ENDIF}
  33. {$ENDIF}
  34. { Utility routines }
  35. {$i util.inc}
  36. { TBits implementation }
  37. {$i bits.inc}
  38. { All streams implementations: }
  39. { Tstreams THandleStream TFileStream TResourcseStreams TStringStream }
  40. { TCustomMemoryStream TMemoryStream }
  41. {$i streams.inc}
  42. { TParser implementation}
  43. {$i parser.inc}
  44. { TCollection and TCollectionItem implementations }
  45. {$i collect.inc}
  46. { TList and TThreadList implementations }
  47. {$i lists.inc}
  48. { TStrings and TStringList implementations }
  49. {$i stringl.inc}
  50. { TThread implementation }
  51. { system independend threading code }
  52. var
  53. { event executed by SychronizeInternal to wake main thread if it sleeps in
  54. CheckSynchronize }
  55. SynchronizeTimeoutEvent: PRtlEvent;
  56. { the head of the queue containing the entries to be Synchronized - Nil if the
  57. queue is empty }
  58. ThreadQueueHead: TThread.PThreadQueueEntry;
  59. { the tail of the queue containing the entries to be Synchronized - Nil if the
  60. queue is empty }
  61. ThreadQueueTail: TThread.PThreadQueueEntry;
  62. { used for serialized access to the queue }
  63. ThreadQueueLock: TRtlCriticalSection;
  64. { this list holds all instances of external threads that need to be freed at
  65. the end of the program }
  66. ExternalThreads: TThreadList;
  67. threadvar
  68. { the instance of the current thread; in case of an external thread this is
  69. Nil until TThread.GetCurrentThread was called once (the RTLs need to ensure
  70. that threadvars are initialized with 0!) }
  71. CurrentThreadVar: TThread;
  72. type
  73. { this type is used if a thread is created using
  74. TThread.CreateAnonymousThread }
  75. TAnonymousThread = class(TThread)
  76. private
  77. fProc: TProcedure;
  78. protected
  79. procedure Execute; override;
  80. public
  81. { as in TThread aProc needs to be changed to TProc once closures are
  82. supported }
  83. constructor Create(aProc: TProcedure);
  84. end;
  85. procedure TAnonymousThread.Execute;
  86. begin
  87. fProc();
  88. end;
  89. constructor TAnonymousThread.Create(aProc: TProcedure);
  90. begin
  91. { an anonymous thread is created suspended and with FreeOnTerminate set }
  92. inherited Create(True);
  93. FreeOnTerminate := True;
  94. fProc := aProc;
  95. end;
  96. type
  97. { this type is used by TThread.GetCurrentThread if the thread does not yet
  98. have a value in CurrentThreadVar (Note: the main thread is also created as
  99. a TExternalThread) }
  100. TExternalThread = class(TThread)
  101. protected
  102. { dummy method to remove the warning }
  103. procedure Execute; override;
  104. public
  105. constructor Create;
  106. end;
  107. procedure TExternalThread.Execute;
  108. begin
  109. { empty }
  110. end;
  111. constructor TExternalThread.Create;
  112. begin
  113. FExternalThread := True;
  114. { the parameter is unimportant if FExternalThread is True }
  115. inherited Create(False);
  116. end;
  117. function ThreadProc(ThreadObjPtr: Pointer): PtrInt;
  118. var
  119. FreeThread: Boolean;
  120. Thread: TThread absolute ThreadObjPtr;
  121. begin
  122. { if Suspend checks FSuspended before doing anything, make sure it }
  123. { knows we're currently not suspended (this flag may have been set }
  124. { to true if CreateSuspended was true) }
  125. // Thread.FSuspended:=false;
  126. // wait until AfterConstruction has been called, so we cannot
  127. // free ourselves before TThread.Create has finished
  128. // (since that one may check our VTM in case of $R+, and
  129. // will call the AfterConstruction method in all cases)
  130. // Thread.Suspend;
  131. try
  132. { The thread may be already terminated at this point, e.g. if it was intially
  133. suspended, or if it wasn't ever scheduled for execution for whatever reason.
  134. So bypass user code if terminated. }
  135. if not Thread.Terminated then begin
  136. CurrentThreadVar := Thread;
  137. Thread.Execute;
  138. end;
  139. except
  140. Thread.FFatalException := TObject(AcquireExceptionObject);
  141. end;
  142. FreeThread := Thread.FFreeOnTerminate;
  143. Result := Thread.FReturnValue;
  144. Thread.FFinished := True;
  145. Thread.DoTerminate;
  146. if FreeThread then
  147. Thread.Free;
  148. EndThread(Result);
  149. end;
  150. { system-dependent code }
  151. {$i tthread.inc}
  152. constructor TThread.Create(CreateSuspended: Boolean;
  153. const StackSize: SizeUInt);
  154. begin
  155. inherited Create;
  156. if FExternalThread then
  157. FThreadID := GetCurrentThreadID
  158. else
  159. SysCreate(CreateSuspended, StackSize);
  160. end;
  161. destructor TThread.Destroy;
  162. begin
  163. if not FExternalThread then begin
  164. SysDestroy;
  165. if FHandle <> TThreadID(0) then
  166. CloseThread(FHandle);
  167. end;
  168. RemoveQueuedEvents(Self);
  169. DoneSynchronizeEvent;
  170. { set CurrentThreadVar to Nil? }
  171. inherited Destroy;
  172. end;
  173. procedure TThread.Start;
  174. begin
  175. { suspend/resume are now deprecated in Delphi (they also don't work
  176. on most platforms in FPC), so a different method was required
  177. to start a thread if it's create with fSuspended=true -> that's
  178. what this method is for. }
  179. Resume;
  180. end;
  181. function TThread.GetSuspended: Boolean;
  182. begin
  183. GetSuspended:=FSuspended;
  184. end;
  185. procedure TThread.AfterConstruction;
  186. begin
  187. inherited AfterConstruction;
  188. // enable for all platforms once http://bugs.freepascal.org/view.php?id=16884
  189. // is fixed for all platforms (in case the fix for non-unix platforms also
  190. // requires this field at least)
  191. {$if defined(unix) or defined(windows)}
  192. if not FExternalThread and not FInitialSuspended then
  193. Resume;
  194. {$endif}
  195. end;
  196. procedure ExecuteThreadQueueEntry(aEntry: TThread.PThreadQueueEntry);
  197. begin
  198. if Assigned(aEntry^.Method) then
  199. aEntry^.Method()
  200. // enable once closures are supported
  201. {else
  202. aEntry^.ThreadProc();}
  203. end;
  204. procedure ThreadQueueAppend(aEntry: TThread.PThreadQueueEntry);
  205. begin
  206. { do we really need a synchronized call? }
  207. if GetCurrentThreadID = MainThreadID then begin
  208. ExecuteThreadQueueEntry(aEntry);
  209. if not Assigned(aEntry^.SyncEvent) then
  210. Dispose(aEntry);
  211. end else begin
  212. System.EnterCriticalSection(ThreadQueueLock);
  213. try
  214. { add the entry to the thread queue }
  215. if Assigned(ThreadQueueTail) then begin
  216. ThreadQueueTail^.Next := aEntry;
  217. end else
  218. ThreadQueueHead := aEntry;
  219. ThreadQueueTail := aEntry;
  220. finally
  221. System.LeaveCriticalSection(ThreadQueueLock);
  222. end;
  223. { ensure that the main thread knows that something awaits }
  224. RtlEventSetEvent(SynchronizeTimeoutEvent);
  225. if assigned(WakeMainThread) then
  226. WakeMainThread(aEntry^.Thread);
  227. { is this a Synchronize or Queue entry? }
  228. if Assigned(aEntry^.SyncEvent) then begin
  229. RtlEventWaitFor(aEntry^.SyncEvent);
  230. if Assigned(aEntry^.Exception) then
  231. raise aEntry^.Exception;
  232. end;
  233. end;
  234. end;
  235. procedure TThread.InitSynchronizeEvent;
  236. begin
  237. if Assigned(FSynchronizeEntry) then
  238. Exit;
  239. New(FSynchronizeEntry);
  240. FillChar(FSynchronizeEntry^, SizeOf(TThreadQueueEntry), 0);
  241. FSynchronizeEntry^.Thread := Self;
  242. FSynchronizeEntry^.SyncEvent := RtlEventCreate;
  243. end;
  244. procedure TThread.DoneSynchronizeEvent;
  245. begin
  246. if not Assigned(FSynchronizeEntry) then
  247. Exit;
  248. RtlEventDestroy(FSynchronizeEntry^.SyncEvent);
  249. Dispose(FSynchronizeEntry);
  250. FSynchronizeEntry := Nil;
  251. end;
  252. class procedure TThread.Synchronize(AThread: TThread; AMethod: TThreadMethod);
  253. begin
  254. { ensure that we have a TThread instance }
  255. if not Assigned(AThread) then
  256. AThread := CurrentThread;
  257. { the Synchronize event is instantiated on demand }
  258. AThread.InitSynchronizeEvent;
  259. AThread.FSynchronizeEntry^.Exception := Nil;
  260. AThread.FSynchronizeEntry^.Method := AMethod;
  261. ThreadQueueAppend(AThread.FSynchronizeEntry);
  262. AThread.FSynchronizeEntry^.Method := Nil;
  263. AThread.FSynchronizeEntry^.Next := Nil;
  264. end;
  265. procedure TThread.Synchronize(AMethod: TThreadMethod);
  266. begin
  267. TThread.Synchronize(self,AMethod);
  268. end;
  269. function CheckSynchronize(timeout : longint=0) : boolean;
  270. { assumes being called from GUI thread }
  271. var
  272. exceptobj: Exception;
  273. tmpentry: TThread.PThreadQueueEntry;
  274. begin
  275. result:=false;
  276. { first sanity check }
  277. if Not IsMultiThread then
  278. Exit
  279. { second sanity check }
  280. else if GetCurrentThreadID<>MainThreadID then
  281. raise EThread.CreateFmt(SCheckSynchronizeError,[GetCurrentThreadID])
  282. else
  283. begin
  284. if timeout>0 then
  285. begin
  286. RtlEventWaitFor(SynchronizeTimeoutEvent,timeout);
  287. end
  288. else
  289. RtlEventResetEvent(SynchronizeTimeoutEvent);
  290. System.EnterCriticalSection(ThreadQueueLock);
  291. try
  292. { Note: we don't need to pay attention to recursive calls to
  293. Synchronize as those calls will be executed in the context of
  294. the GUI thread and thus will be executed immediatly instead of
  295. queuing them }
  296. while Assigned(ThreadQueueHead) do begin
  297. { step 1: update the list }
  298. tmpentry := ThreadQueueHead;
  299. ThreadQueueHead := ThreadQueueHead^.Next;
  300. if not Assigned(ThreadQueueHead) then
  301. ThreadQueueTail := Nil;
  302. { step 2: execute the method }
  303. exceptobj := Nil;
  304. try
  305. ExecuteThreadQueueEntry(tmpentry);
  306. except
  307. exceptobj := Exception(AcquireExceptionObject);
  308. end;
  309. { step 3: error handling and cleanup }
  310. if Assigned(tmpentry^.SyncEvent) then begin
  311. { for Synchronize entries we pass back the Exception and trigger
  312. the event that Synchronize waits in }
  313. tmpentry^.Exception := exceptobj;
  314. RtlEventSetEvent(tmpentry^.SyncEvent)
  315. end else begin
  316. { for Queue entries we dispose the entry and raise the exception }
  317. Dispose(tmpentry);
  318. if Assigned(exceptobj) then
  319. raise exceptobj;
  320. end;
  321. end;
  322. finally
  323. System.LeaveCriticalSection(ThreadQueueLock);
  324. end;
  325. end;
  326. end;
  327. class function TThread.GetCurrentThread: TThread;
  328. begin
  329. { if this is the first time GetCurrentThread is called for an external thread
  330. we need to create a corresponding TExternalThread instance }
  331. Result := CurrentThreadVar;
  332. if not Assigned(Result) then begin
  333. Result := TExternalThread.Create;
  334. CurrentThreadVar := Result;
  335. end;
  336. end;
  337. class function TThread.GetIsSingleProcessor: Boolean;
  338. begin
  339. Result := FProcessorCount <= 1;
  340. end;
  341. procedure TThread.Queue(aMethod: TThreadMethod);
  342. begin
  343. Queue(Self, aMethod);
  344. end;
  345. class procedure TThread.Queue(aThread: TThread; aMethod: TThreadMethod); static;
  346. var
  347. queueentry: PThreadQueueEntry;
  348. begin
  349. { ensure that we have a valid TThread instance }
  350. if not Assigned(aThread) then
  351. aThread := CurrentThread;
  352. New(queueentry);
  353. FillChar(queueentry^, SizeOf(TThreadQueueEntry), 0);
  354. queueentry^.Thread := aThread;
  355. queueentry^.Method := aMethod;
  356. { the queueentry is freed by CheckSynchronize (or by RemoveQueuedEvents) }
  357. ThreadQueueAppend(queueentry);
  358. end;
  359. class procedure TThread.RemoveQueuedEvents(aThread: TThread; aMethod: TThreadMethod);
  360. var
  361. entry, tmpentry, lastentry: PThreadQueueEntry;
  362. begin
  363. { anything to do at all? }
  364. if not Assigned(aThread) or not Assigned(aMethod) then
  365. Exit;
  366. System.EnterCriticalSection(ThreadQueueLock);
  367. try
  368. lastentry := Nil;
  369. entry := ThreadQueueHead;
  370. while Assigned(entry) do begin
  371. { first check for the thread }
  372. if Assigned(aThread) and (entry^.Thread <> aThread) then begin
  373. lastentry := entry;
  374. entry := entry^.Next;
  375. Continue;
  376. end;
  377. { then check for the method }
  378. if entry^.Method <> aMethod then begin
  379. lastentry := entry;
  380. entry := entry^.Next;
  381. Continue;
  382. end;
  383. { skip entries added by Synchronize }
  384. if Assigned(entry^.SyncEvent) then begin
  385. lastentry := entry;
  386. entry := entry^.Next;
  387. Continue;
  388. end;
  389. { ok, we need to remove this entry }
  390. tmpentry := entry;
  391. if Assigned(lastentry) then
  392. lastentry^.Next := entry^.Next;
  393. entry := entry^.Next;
  394. if ThreadQueueHead = tmpentry then
  395. ThreadQueueHead := entry;
  396. if ThreadQueueTail = tmpentry then
  397. ThreadQueueTail := lastentry;
  398. { only dispose events added by Queue }
  399. if not Assigned(tmpentry^.SyncEvent) then
  400. Dispose(tmpentry);
  401. end;
  402. finally
  403. System.LeaveCriticalSection(ThreadQueueLock);
  404. end;
  405. end;
  406. class procedure TThread.RemoveQueuedEvents(aMethod: TThreadMethod);
  407. begin
  408. RemoveQueuedEvents(Nil, aMethod);
  409. end;
  410. class procedure TThread.RemoveQueuedEvents(aThread: TThread);
  411. begin
  412. RemoveQueuedEvents(aThread, Nil);
  413. end;
  414. class function TThread.CheckTerminated: Boolean;
  415. begin
  416. { this method only works with threads created by TThread, so we can make a
  417. shortcut here }
  418. if not Assigned(CurrentThreadVar) then
  419. raise EThreadExternalException.Create(SThreadExternal);
  420. Result := CurrentThreadVar.FTerminated;
  421. end;
  422. class procedure TThread.SetReturnValue(aValue: Integer);
  423. begin
  424. { this method only works with threads created by TThread, so we can make a
  425. shortcut here }
  426. if not Assigned(CurrentThreadVar) then
  427. raise EThreadExternalException.Create(SThreadExternal);
  428. CurrentThreadVar.FReturnValue := aValue;
  429. end;
  430. class function TThread.CreateAnonymousThread(aProc: TProcedure): TThread;
  431. begin
  432. if not Assigned(aProc) then
  433. raise Exception.Create(SNoProcGiven);
  434. Result := TAnonymousThread.Create(aProc);
  435. end;
  436. {$ifdef THREADNAME_IS_ANSISTRING}
  437. { the platform implements the AnsiString variant and the UnicodeString variant
  438. simply calls the AnsiString variant }
  439. class procedure TThread.NameThreadForDebugging(aThreadName: UnicodeString; aThreadID: TThreadID);
  440. begin
  441. NameThreadForDebugging(AnsiString(aThreadName), aThreadID);
  442. end;
  443. {$ifndef HAS_TTHREAD_NAMETHREADFORDEBUGGING}
  444. class procedure TThread.NameThreadForDebugging(aThreadName: AnsiString; aThreadID: TThreadID);
  445. begin
  446. { empty }
  447. end;
  448. {$endif}
  449. {$else}
  450. {$ifndef HAS_TTHREAD_NAMETHREADFORDEBUGGING}
  451. { the platform implements the UnicodeString variant and the AnsiString variant
  452. simply calls the UnicodeString variant }
  453. class procedure TThread.NameThreadForDebugging(aThreadName: UnicodeString; aThreadID: TThreadID);
  454. begin
  455. { empty }
  456. end;
  457. {$endif}
  458. class procedure TThread.NameThreadForDebugging(aThreadName: AnsiString; aThreadID: TThreadID);
  459. begin
  460. NameThreadForDebugging(UnicodeString(aThreadName), aThreadID);
  461. end;
  462. {$endif}
  463. class procedure TThread.Yield;
  464. begin
  465. ThreadSwitch;
  466. end;
  467. class procedure TThread.Sleep(aMilliseconds: Cardinal);
  468. begin
  469. SysUtils.Sleep(aMilliseconds);
  470. end;
  471. class procedure TThread.SpinWait(aIterations: LongWord);
  472. begin
  473. { yes, it's just a simple busy wait to burn some cpu cycles... and as the job
  474. of this loop is to burn CPU cycles we switch off any optimizations that
  475. could interfere with this (e.g. loop unrolling) }
  476. {$PUSH}
  477. {$OPTIMIZATION OFF}
  478. while aIterations > 0 do
  479. Dec(aIterations);
  480. {$POP}
  481. end;
  482. {$ifndef HAS_TTHREAD_GETSYSTEMTIMES}
  483. class procedure TThread.GetSystemTimes(out aSystemTimes: TSystemTimes);
  484. begin
  485. { by default we just return a zeroed out record }
  486. FillChar(aSystemTimes, SizeOf(aSystemTimes), 0);
  487. end;
  488. {$endif}
  489. class function TThread.GetTickCount: LongWord;
  490. begin
  491. Result := SysUtils.GetTickCount;
  492. end;
  493. class function TThread.GetTickCount64: QWord;
  494. begin
  495. Result := SysUtils.GetTickCount64;
  496. end;
  497. { TPersistent implementation }
  498. {$i persist.inc }
  499. {$i sllist.inc}
  500. {$i resref.inc}
  501. { TComponent implementation }
  502. {$i compon.inc}
  503. { TBasicAction implementation }
  504. {$i action.inc}
  505. { TDataModule implementation }
  506. {$i dm.inc}
  507. { Class and component registration routines }
  508. {$I cregist.inc}
  509. { Interface related stuff }
  510. {$I intf.inc}
  511. {**********************************************************************
  512. * Miscellaneous procedures and functions *
  513. **********************************************************************}
  514. function ExtractStrings(Separators, WhiteSpace: TSysCharSet; Content: PChar; Strings: TStrings; AddEmptyStrings : Boolean = False): Integer;
  515. var
  516. b, c : pchar;
  517. procedure SkipWhitespace;
  518. begin
  519. while (c^ in Whitespace) do
  520. inc (c);
  521. end;
  522. procedure AddString;
  523. var
  524. l : integer;
  525. s : string;
  526. begin
  527. l := c-b;
  528. if (l > 0) or AddEmptyStrings then
  529. begin
  530. if assigned(Strings) then
  531. begin
  532. setlength(s, l);
  533. if l>0 then
  534. move (b^, s[1],l*SizeOf(char));
  535. Strings.Add (s);
  536. end;
  537. inc (result);
  538. end;
  539. end;
  540. var
  541. quoted : char;
  542. begin
  543. result := 0;
  544. c := Content;
  545. Quoted := #0;
  546. Separators := Separators + [#13, #10] - ['''','"'];
  547. SkipWhitespace;
  548. b := c;
  549. while (c^ <> #0) do
  550. begin
  551. if (c^ = Quoted) then
  552. begin
  553. if ((c+1)^ = Quoted) then
  554. inc (c)
  555. else
  556. Quoted := #0
  557. end
  558. else if (Quoted = #0) and (c^ in ['''','"']) then
  559. Quoted := c^;
  560. if (Quoted = #0) and (c^ in Separators) then
  561. begin
  562. AddString;
  563. inc (c);
  564. SkipWhitespace;
  565. b := c;
  566. end
  567. else
  568. inc (c);
  569. end;
  570. if (c <> b) then
  571. AddString;
  572. end;
  573. { Point and rectangle constructors }
  574. function Point(AX, AY: Integer): TPoint;
  575. begin
  576. with Result do
  577. begin
  578. X := AX;
  579. Y := AY;
  580. end;
  581. end;
  582. function SmallPoint(AX, AY: SmallInt): TSmallPoint;
  583. begin
  584. with Result do
  585. begin
  586. X := AX;
  587. Y := AY;
  588. end;
  589. end;
  590. function Rect(ALeft, ATop, ARight, ABottom: Integer): TRect;
  591. begin
  592. with Result do
  593. begin
  594. Left := ALeft;
  595. Top := ATop;
  596. Right := ARight;
  597. Bottom := ABottom;
  598. end;
  599. end;
  600. function Bounds(ALeft, ATop, AWidth, AHeight: Integer): TRect;
  601. begin
  602. with Result do
  603. begin
  604. Left := ALeft;
  605. Top := ATop;
  606. Right := ALeft + AWidth;
  607. Bottom := ATop + AHeight;
  608. end;
  609. end;
  610. function PointsEqual(const P1, P2: TPoint): Boolean; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  611. begin
  612. { lazy, but should work }
  613. result:=QWord(P1)=QWord(P2);
  614. end;
  615. function PointsEqual(const P1, P2: TSmallPoint): Boolean; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  616. begin
  617. { lazy, but should work }
  618. result:=DWord(P1)=DWord(P2);
  619. end;
  620. function InvalidPoint(X, Y: Integer): Boolean;
  621. begin
  622. result:=(X=-1) and (Y=-1);
  623. end;
  624. function InvalidPoint(const At: TPoint): Boolean;
  625. begin
  626. result:=(At.x=-1) and (At.y=-1);
  627. end;
  628. function InvalidPoint(const At: TSmallPoint): Boolean;
  629. begin
  630. result:=(At.x=-1) and (At.y=-1);
  631. end;
  632. { Object filing routines }
  633. var
  634. IntConstList: TThreadList;
  635. type
  636. TIntConst = class
  637. IntegerType: PTypeInfo; // The integer type RTTI pointer
  638. IdentToIntFn: TIdentToInt; // Identifier to Integer conversion
  639. IntToIdentFn: TIntToIdent; // Integer to Identifier conversion
  640. constructor Create(AIntegerType: PTypeInfo; AIdentToInt: TIdentToInt;
  641. AIntToIdent: TIntToIdent);
  642. end;
  643. constructor TIntConst.Create(AIntegerType: PTypeInfo; AIdentToInt: TIdentToInt;
  644. AIntToIdent: TIntToIdent);
  645. begin
  646. IntegerType := AIntegerType;
  647. IdentToIntFn := AIdentToInt;
  648. IntToIdentFn := AIntToIdent;
  649. end;
  650. procedure RegisterIntegerConsts(IntegerType: Pointer; IdentToIntFn: TIdentToInt;
  651. IntToIdentFn: TIntToIdent);
  652. begin
  653. IntConstList.Add(TIntConst.Create(IntegerType, IdentToIntFn, IntToIdentFn));
  654. end;
  655. function FindIntToIdent(AIntegerType: Pointer): TIntToIdent;
  656. var
  657. i: Integer;
  658. begin
  659. with IntConstList.LockList do
  660. try
  661. for i := 0 to Count - 1 do
  662. if TIntConst(Items[i]).IntegerType = AIntegerType then
  663. exit(TIntConst(Items[i]).IntToIdentFn);
  664. Result := nil;
  665. finally
  666. IntConstList.UnlockList;
  667. end;
  668. end;
  669. function FindIdentToInt(AIntegerType: Pointer): TIdentToInt;
  670. var
  671. i: Integer;
  672. begin
  673. with IntConstList.LockList do
  674. try
  675. for i := 0 to Count - 1 do
  676. with TIntConst(Items[I]) do
  677. if TIntConst(Items[I]).IntegerType = AIntegerType then
  678. exit(IdentToIntFn);
  679. Result := nil;
  680. finally
  681. IntConstList.UnlockList;
  682. end;
  683. end;
  684. function IdentToInt(const Ident: String; var Int: LongInt;
  685. const Map: array of TIdentMapEntry): Boolean;
  686. var
  687. i: Integer;
  688. begin
  689. for i := Low(Map) to High(Map) do
  690. if CompareText(Map[i].Name, Ident) = 0 then
  691. begin
  692. Int := Map[i].Value;
  693. exit(True);
  694. end;
  695. Result := False;
  696. end;
  697. function IntToIdent(Int: LongInt; var Ident: String;
  698. const Map: array of TIdentMapEntry): Boolean;
  699. var
  700. i: Integer;
  701. begin
  702. for i := Low(Map) to High(Map) do
  703. if Map[i].Value = Int then
  704. begin
  705. Ident := Map[i].Name;
  706. exit(True);
  707. end;
  708. Result := False;
  709. end;
  710. function GlobalIdentToInt(const Ident: String; var Int: LongInt):boolean;
  711. var
  712. i : Integer;
  713. begin
  714. with IntConstList.LockList do
  715. try
  716. for i := 0 to Count - 1 do
  717. if TIntConst(Items[I]).IdentToIntFn(Ident, Int) then
  718. Exit(True);
  719. Result := false;
  720. finally
  721. IntConstList.UnlockList;
  722. end;
  723. end;
  724. { TPropFixup }
  725. // Tainted. TPropFixup is being removed.
  726. Type
  727. TInitHandler = Class(TObject)
  728. AHandler : TInitComponentHandler;
  729. AClass : TComponentClass;
  730. end;
  731. {$ifndef i8086}
  732. type
  733. TCodePtrList = TList;
  734. {$endif i8086}
  735. Var
  736. InitHandlerList : TList;
  737. FindGlobalComponentList : TCodePtrList;
  738. procedure RegisterFindGlobalComponentProc(AFindGlobalComponent: TFindGlobalComponent);
  739. begin
  740. if not(assigned(FindGlobalComponentList)) then
  741. FindGlobalComponentList:=TCodePtrList.Create;
  742. if FindGlobalComponentList.IndexOf(CodePointer(AFindGlobalComponent))<0 then
  743. FindGlobalComponentList.Add(CodePointer(AFindGlobalComponent));
  744. end;
  745. procedure UnregisterFindGlobalComponentProc(AFindGlobalComponent: TFindGlobalComponent);
  746. begin
  747. if assigned(FindGlobalComponentList) then
  748. FindGlobalComponentList.Remove(CodePointer(AFindGlobalComponent));
  749. end;
  750. function FindGlobalComponent(const Name: string): TComponent;
  751. var
  752. i : sizeint;
  753. begin
  754. FindGlobalComponent:=nil;
  755. if assigned(FindGlobalComponentList) then
  756. begin
  757. for i:=FindGlobalComponentList.Count-1 downto 0 do
  758. begin
  759. FindGlobalComponent:=TFindGlobalComponent(FindGlobalComponentList[i])(name);
  760. if assigned(FindGlobalComponent) then
  761. break;
  762. end;
  763. end;
  764. end;
  765. procedure RegisterInitComponentHandler(ComponentClass: TComponentClass; Handler: TInitComponentHandler);
  766. Var
  767. I : Integer;
  768. H: TInitHandler;
  769. begin
  770. If (InitHandlerList=Nil) then
  771. InitHandlerList:=TList.Create;
  772. H:=TInitHandler.Create;
  773. H.Aclass:=ComponentClass;
  774. H.AHandler:=Handler;
  775. try
  776. With InitHandlerList do
  777. begin
  778. I:=0;
  779. While (I<Count) and not H.AClass.InheritsFrom(TInitHandler(Items[I]).AClass) do
  780. Inc(I);
  781. { override? }
  782. if (I<Count) and (TInitHandler(Items[I]).AClass=H.AClass) then
  783. begin
  784. TInitHandler(Items[I]).AHandler:=Handler;
  785. H.Free;
  786. end
  787. else
  788. InitHandlerList.Insert(I,H);
  789. end;
  790. except
  791. H.Free;
  792. raise;
  793. end;
  794. end;
  795. { all targets should at least include the sysres.inc dummy in the system unit to compile this }
  796. function CreateComponentfromRes(const res : string;Inst : THandle;var Component : TComponent) : Boolean;
  797. var
  798. ResStream : TResourceStream;
  799. begin
  800. result:=true;
  801. if Inst=0 then
  802. Inst:=HInstance;
  803. try
  804. ResStream:=TResourceStream.Create(Inst,res,RT_RCDATA);
  805. try
  806. Component:=ResStream.ReadComponent(Component);
  807. finally
  808. ResStream.Free;
  809. end;
  810. except
  811. on EResNotFound do
  812. result:=false;
  813. end;
  814. end;
  815. function DefaultInitHandler(Instance: TComponent; RootAncestor: TClass): Boolean;
  816. function doinit(_class : TClass) : boolean;
  817. begin
  818. result:=false;
  819. if (_class.ClassType=TComponent) or (_class.ClassType=RootAncestor) then
  820. exit;
  821. result:=doinit(_class.ClassParent);
  822. result:=CreateComponentfromRes(_class.ClassName,0,Instance) or result;
  823. end;
  824. begin
  825. GlobalNameSpace.BeginWrite;
  826. try
  827. result:=doinit(Instance.ClassType);
  828. finally
  829. GlobalNameSpace.EndWrite;
  830. end;
  831. end;
  832. function InitInheritedComponent(Instance: TComponent; RootAncestor: TClass): Boolean;
  833. Var
  834. I : Integer;
  835. begin
  836. I:=0;
  837. if not Assigned(InitHandlerList) then begin
  838. Result := True;
  839. Exit;
  840. end;
  841. Result:=False;
  842. With InitHandlerList do
  843. begin
  844. I:=0;
  845. // Instance is the normally the lowest one, so that one should be used when searching.
  846. While Not result and (I<Count) do
  847. begin
  848. If (Instance.InheritsFrom(TInitHandler(Items[i]).AClass)) then
  849. Result:=TInitHandler(Items[i]).AHandler(Instance,RootAncestor);
  850. Inc(I);
  851. end;
  852. end;
  853. end;
  854. function InitComponentRes(const ResName: String; Instance: TComponent): Boolean;
  855. begin
  856. { !!!: Too Win32-specific }
  857. InitComponentRes := False;
  858. end;
  859. function ReadComponentRes(const ResName: String; Instance: TComponent): TComponent;
  860. begin
  861. { !!!: Too Win32-specific }
  862. ReadComponentRes := nil;
  863. end;
  864. function ReadComponentResEx(HInstance: THandle; const ResName: String): TComponent;
  865. begin
  866. { !!!: Too Win32-specific in VCL }
  867. ReadComponentResEx := nil;
  868. end;
  869. function ReadComponentResFile(const FileName: String; Instance: TComponent): TComponent;
  870. var
  871. FileStream: TStream;
  872. begin
  873. FileStream := TFileStream.Create(FileName, fmOpenRead {!!!:or fmShareDenyWrite});
  874. try
  875. Result := FileStream.ReadComponentRes(Instance);
  876. finally
  877. FileStream.Free;
  878. end;
  879. end;
  880. procedure WriteComponentResFile(const FileName: String; Instance: TComponent);
  881. var
  882. FileStream: TStream;
  883. begin
  884. FileStream := TFileStream.Create(FileName, fmCreate);
  885. try
  886. FileStream.WriteComponentRes(Instance.ClassName, Instance);
  887. finally
  888. FileStream.Free;
  889. end;
  890. end;
  891. Function FindNestedComponent(Root : TComponent; APath : String; CStyle : Boolean = True) : TComponent;
  892. Function GetNextName : String; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE}
  893. Var
  894. P : Integer;
  895. CM : Boolean;
  896. begin
  897. P:=Pos('.',APath);
  898. CM:=False;
  899. If (P=0) then
  900. begin
  901. If CStyle then
  902. begin
  903. P:=Pos('->',APath);
  904. CM:=P<>0;
  905. end;
  906. If (P=0) Then
  907. P:=Length(APath)+1;
  908. end;
  909. Result:=Copy(APath,1,P-1);
  910. Delete(APath,1,P+Ord(CM));
  911. end;
  912. Var
  913. C : TComponent;
  914. S : String;
  915. begin
  916. If (APath='') then
  917. Result:=Nil
  918. else
  919. begin
  920. Result:=Root;
  921. While (APath<>'') And (Result<>Nil) do
  922. begin
  923. C:=Result;
  924. S:=Uppercase(GetNextName);
  925. Result:=C.FindComponent(S);
  926. If (Result=Nil) And (S='OWNER') then
  927. Result:=C;
  928. end;
  929. end;
  930. end;
  931. threadvar
  932. GlobalLoaded, GlobalLists: TFpList;
  933. procedure BeginGlobalLoading;
  934. begin
  935. if not Assigned(GlobalLists) then
  936. GlobalLists := TFpList.Create;
  937. GlobalLists.Add(GlobalLoaded);
  938. GlobalLoaded := TFpList.Create;
  939. end;
  940. { Notify all global components that they have been loaded completely }
  941. procedure NotifyGlobalLoading;
  942. var
  943. i: Integer;
  944. begin
  945. for i := 0 to GlobalLoaded.Count - 1 do
  946. TComponent(GlobalLoaded[i]).Loaded;
  947. end;
  948. procedure EndGlobalLoading;
  949. begin
  950. { Free the memory occupied by BeginGlobalLoading }
  951. GlobalLoaded.Free;
  952. GlobalLoaded := TFpList(GlobalLists.Last);
  953. GlobalLists.Delete(GlobalLists.Count - 1);
  954. if GlobalLists.Count = 0 then
  955. begin
  956. GlobalLists.Free;
  957. GlobalLists := nil;
  958. end;
  959. end;
  960. function CollectionsEqual(C1, C2: TCollection): Boolean;
  961. begin
  962. // !!!: Implement this
  963. CollectionsEqual:=false;
  964. end;
  965. function CollectionsEqual(C1, C2: TCollection; Owner1, Owner2: TComponent): Boolean;
  966. procedure stream_collection(s : tstream;c : tcollection;o : tcomponent);
  967. var
  968. w : twriter;
  969. begin
  970. w:=twriter.create(s,4096);
  971. try
  972. w.root:=o;
  973. w.flookuproot:=o;
  974. w.writecollection(c);
  975. finally
  976. w.free;
  977. end;
  978. end;
  979. var
  980. s1,s2 : tmemorystream;
  981. begin
  982. result:=false;
  983. if (c1.classtype<>c2.classtype) or
  984. (c1.count<>c2.count) then
  985. exit;
  986. if c1.count = 0 then
  987. begin
  988. result:= true;
  989. exit;
  990. end;
  991. s1:=tmemorystream.create;
  992. try
  993. s2:=tmemorystream.create;
  994. try
  995. stream_collection(s1,c1,owner1);
  996. stream_collection(s2,c2,owner2);
  997. result:=(s1.size=s2.size) and (CompareChar(s1.memory^,s2.memory^,s1.size)=0);
  998. finally
  999. s2.free;
  1000. end;
  1001. finally
  1002. s1.free;
  1003. end;
  1004. end;
  1005. { Object conversion routines }
  1006. type
  1007. CharToOrdFuncty = Function(var charpo: Pointer): Cardinal;
  1008. function CharToOrd(var P: Pointer): Cardinal;
  1009. begin
  1010. result:= ord(pchar(P)^);
  1011. inc(pchar(P));
  1012. end;
  1013. function WideCharToOrd(var P: Pointer): Cardinal;
  1014. begin
  1015. result:= ord(pwidechar(P)^);
  1016. inc(pwidechar(P));
  1017. end;
  1018. function Utf8ToOrd(var P:Pointer): Cardinal;
  1019. begin
  1020. // Should also check for illegal utf8 combinations
  1021. Result := Ord(PChar(P)^);
  1022. Inc(P);
  1023. if (Result and $80) <> 0 then
  1024. if (Ord(Result) and %11100000) = %11000000 then begin
  1025. Result := ((Result and %00011111) shl 6)
  1026. or (ord(PChar(P)^) and %00111111);
  1027. Inc(P);
  1028. end else if (Ord(Result) and %11110000) = %11100000 then begin
  1029. Result := ((Result and %00011111) shl 12)
  1030. or ((ord(PChar(P)^) and %00111111) shl 6)
  1031. or (ord((PChar(P)+1)^) and %00111111);
  1032. Inc(P,2);
  1033. end else begin
  1034. Result := ((ord(Result) and %00011111) shl 18)
  1035. or ((ord(PChar(P)^) and %00111111) shl 12)
  1036. or ((ord((PChar(P)+1)^) and %00111111) shl 6)
  1037. or (ord((PChar(P)+2)^) and %00111111);
  1038. Inc(P,3);
  1039. end;
  1040. end;
  1041. procedure ObjectBinaryToText(Input, Output: TStream; Encoding: TObjectTextEncoding);
  1042. procedure OutStr(s: String);
  1043. begin
  1044. if Length(s) > 0 then
  1045. Output.Write(s[1], Length(s));
  1046. end;
  1047. procedure OutLn(s: String);
  1048. begin
  1049. OutStr(s + LineEnding);
  1050. end;
  1051. procedure Outchars(P, LastP : Pointer; CharToOrdFunc: CharToOrdFuncty;
  1052. UseBytes: boolean = false);
  1053. var
  1054. res, NewStr: String;
  1055. w: Cardinal;
  1056. InString, NewInString: Boolean;
  1057. begin
  1058. if p = nil then begin
  1059. res:= '''''';
  1060. end
  1061. else
  1062. begin
  1063. res := '';
  1064. InString := False;
  1065. while P < LastP do
  1066. begin
  1067. NewInString := InString;
  1068. w := CharToOrdfunc(P);
  1069. if w = ord('''') then
  1070. begin //quote char
  1071. if not InString then
  1072. NewInString := True;
  1073. NewStr := '''''';
  1074. end
  1075. else if (Ord(w) >= 32) and ((Ord(w) < 127) or (UseBytes and (Ord(w)<256))) then
  1076. begin //printable ascii or bytes
  1077. if not InString then
  1078. NewInString := True;
  1079. NewStr := char(w);
  1080. end
  1081. else
  1082. begin //ascii control chars, non ascii
  1083. if InString then
  1084. NewInString := False;
  1085. NewStr := '#' + IntToStr(w);
  1086. end;
  1087. if NewInString <> InString then
  1088. begin
  1089. NewStr := '''' + NewStr;
  1090. InString := NewInString;
  1091. end;
  1092. res := res + NewStr;
  1093. end;
  1094. if InString then
  1095. res := res + '''';
  1096. end;
  1097. OutStr(res);
  1098. end;
  1099. procedure OutString(s: String);
  1100. begin
  1101. OutChars(Pointer(S),PChar(S)+Length(S),@CharToOrd,Encoding=oteLFM);
  1102. end;
  1103. procedure OutWString(W: WideString);
  1104. begin
  1105. OutChars(Pointer(W),pwidechar(W)+Length(W),@WideCharToOrd);
  1106. end;
  1107. procedure OutUString(W: UnicodeString);
  1108. begin
  1109. OutChars(Pointer(W),pwidechar(W)+Length(W),@WideCharToOrd);
  1110. end;
  1111. procedure OutUtf8Str(s: String);
  1112. begin
  1113. if Encoding=oteLFM then
  1114. OutChars(Pointer(S),PChar(S)+Length(S),@CharToOrd)
  1115. else
  1116. OutChars(Pointer(S),PChar(S)+Length(S),@Utf8ToOrd);
  1117. end;
  1118. function ReadWord : word; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1119. begin
  1120. Result:=Input.ReadWord;
  1121. Result:=LEtoN(Result);
  1122. end;
  1123. function ReadDWord : longword; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1124. begin
  1125. Result:=Input.ReadDWord;
  1126. Result:=LEtoN(Result);
  1127. end;
  1128. function ReadQWord : qword; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1129. begin
  1130. Input.ReadBuffer(Result,sizeof(Result));
  1131. Result:=LEtoN(Result);
  1132. end;
  1133. {$ifndef FPUNONE}
  1134. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  1135. function ExtendedToDouble(e : pointer) : double;
  1136. var mant : qword;
  1137. exp : smallint;
  1138. sign : boolean;
  1139. d : qword;
  1140. begin
  1141. move(pbyte(e)[0],mant,8); //mantissa : bytes 0..7
  1142. move(pbyte(e)[8],exp,2); //exponent and sign: bytes 8..9
  1143. mant:=LEtoN(mant);
  1144. exp:=LetoN(word(exp));
  1145. sign:=(exp and $8000)<>0;
  1146. if sign then exp:=exp and $7FFF;
  1147. case exp of
  1148. 0 : mant:=0; //if denormalized, value is too small for double,
  1149. //so it's always zero
  1150. $7FFF : exp:=2047 //either infinity or NaN
  1151. else
  1152. begin
  1153. dec(exp,16383-1023);
  1154. if (exp>=-51) and (exp<=0) then //can be denormalized
  1155. begin
  1156. mant:=mant shr (-exp);
  1157. exp:=0;
  1158. end
  1159. else
  1160. if (exp<-51) or (exp>2046) then //exponent too large.
  1161. begin
  1162. Result:=0;
  1163. exit;
  1164. end
  1165. else //normalized value
  1166. mant:=mant shl 1; //hide most significant bit
  1167. end;
  1168. end;
  1169. d:=word(exp);
  1170. d:=d shl 52;
  1171. mant:=mant shr 12;
  1172. d:=d or mant;
  1173. if sign then d:=d or $8000000000000000;
  1174. Result:=pdouble(@d)^;
  1175. end;
  1176. {$ENDIF}
  1177. {$endif}
  1178. function ReadInt(ValueType: TValueType): Int64;
  1179. begin
  1180. case ValueType of
  1181. vaInt8: Result := ShortInt(Input.ReadByte);
  1182. vaInt16: Result := SmallInt(ReadWord);
  1183. vaInt32: Result := LongInt(ReadDWord);
  1184. vaInt64: Result := Int64(ReadQWord);
  1185. end;
  1186. end;
  1187. function ReadInt: Int64;
  1188. begin
  1189. Result := ReadInt(TValueType(Input.ReadByte));
  1190. end;
  1191. {$ifndef FPUNONE}
  1192. function ReadExtended : extended;
  1193. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  1194. var ext : array[0..9] of byte;
  1195. {$ENDIF}
  1196. begin
  1197. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  1198. Input.ReadBuffer(ext[0],10);
  1199. Result:=ExtendedToDouble(@(ext[0]));
  1200. {$ELSE}
  1201. Input.ReadBuffer(Result,sizeof(Result));
  1202. {$ENDIF}
  1203. end;
  1204. {$endif}
  1205. function ReadSStr: String;
  1206. var
  1207. len: Byte;
  1208. begin
  1209. len := Input.ReadByte;
  1210. SetLength(Result, len);
  1211. if (len > 0) then
  1212. Input.ReadBuffer(Result[1], len);
  1213. end;
  1214. function ReadLStr: String;
  1215. var
  1216. len: DWord;
  1217. begin
  1218. len := ReadDWord;
  1219. SetLength(Result, len);
  1220. if (len > 0) then
  1221. Input.ReadBuffer(Result[1], len);
  1222. end;
  1223. function ReadWStr: WideString;
  1224. var
  1225. len: DWord;
  1226. {$IFDEF ENDIAN_BIG}
  1227. i : integer;
  1228. {$ENDIF}
  1229. begin
  1230. len := ReadDWord;
  1231. SetLength(Result, len);
  1232. if (len > 0) then
  1233. begin
  1234. Input.ReadBuffer(Pointer(@Result[1])^, len*2);
  1235. {$IFDEF ENDIAN_BIG}
  1236. for i:=1 to len do
  1237. Result[i]:=widechar(SwapEndian(word(Result[i])));
  1238. {$ENDIF}
  1239. end;
  1240. end;
  1241. function ReadUStr: UnicodeString;
  1242. var
  1243. len: DWord;
  1244. {$IFDEF ENDIAN_BIG}
  1245. i : integer;
  1246. {$ENDIF}
  1247. begin
  1248. len := ReadDWord;
  1249. SetLength(Result, len);
  1250. if (len > 0) then
  1251. begin
  1252. Input.ReadBuffer(Pointer(@Result[1])^, len*2);
  1253. {$IFDEF ENDIAN_BIG}
  1254. for i:=1 to len do
  1255. Result[i]:=widechar(SwapEndian(word(Result[i])));
  1256. {$ENDIF}
  1257. end;
  1258. end;
  1259. procedure ReadPropList(indent: String);
  1260. procedure ProcessValue(ValueType: TValueType; Indent: String);
  1261. procedure ProcessBinary;
  1262. var
  1263. ToDo, DoNow, i: LongInt;
  1264. lbuf: array[0..31] of Byte;
  1265. s: String;
  1266. begin
  1267. ToDo := ReadDWord;
  1268. OutLn('{');
  1269. while ToDo > 0 do begin
  1270. DoNow := ToDo;
  1271. if DoNow > 32 then DoNow := 32;
  1272. Dec(ToDo, DoNow);
  1273. s := Indent + ' ';
  1274. Input.ReadBuffer(lbuf, DoNow);
  1275. for i := 0 to DoNow - 1 do
  1276. s := s + IntToHex(lbuf[i], 2);
  1277. OutLn(s);
  1278. end;
  1279. OutLn(indent + '}');
  1280. end;
  1281. var
  1282. s: String;
  1283. { len: LongInt; }
  1284. IsFirst: Boolean;
  1285. {$ifndef FPUNONE}
  1286. ext: Extended;
  1287. {$endif}
  1288. begin
  1289. case ValueType of
  1290. vaList: begin
  1291. OutStr('(');
  1292. IsFirst := True;
  1293. while True do begin
  1294. ValueType := TValueType(Input.ReadByte);
  1295. if ValueType = vaNull then break;
  1296. if IsFirst then begin
  1297. OutLn('');
  1298. IsFirst := False;
  1299. end;
  1300. OutStr(Indent + ' ');
  1301. ProcessValue(ValueType, Indent + ' ');
  1302. end;
  1303. OutLn(Indent + ')');
  1304. end;
  1305. vaInt8: OutLn(IntToStr(ShortInt(Input.ReadByte)));
  1306. vaInt16: OutLn( IntToStr(SmallInt(ReadWord)));
  1307. vaInt32: OutLn(IntToStr(LongInt(ReadDWord)));
  1308. vaInt64: OutLn(IntToStr(Int64(ReadQWord)));
  1309. {$ifndef FPUNONE}
  1310. vaExtended: begin
  1311. ext:=ReadExtended;
  1312. Str(ext,S);// Do not use localized strings.
  1313. OutLn(S);
  1314. end;
  1315. {$endif}
  1316. vaString: begin
  1317. OutString(ReadSStr);
  1318. OutLn('');
  1319. end;
  1320. vaIdent: OutLn(ReadSStr);
  1321. vaFalse: OutLn('False');
  1322. vaTrue: OutLn('True');
  1323. vaBinary: ProcessBinary;
  1324. vaSet: begin
  1325. OutStr('[');
  1326. IsFirst := True;
  1327. while True do begin
  1328. s := ReadSStr;
  1329. if Length(s) = 0 then break;
  1330. if not IsFirst then OutStr(', ');
  1331. IsFirst := False;
  1332. OutStr(s);
  1333. end;
  1334. OutLn(']');
  1335. end;
  1336. vaLString:
  1337. begin
  1338. OutString(ReadLStr);
  1339. OutLn('');
  1340. end;
  1341. vaWString:
  1342. begin
  1343. OutWString(ReadWStr);
  1344. OutLn('');
  1345. end;
  1346. vaUString:
  1347. begin
  1348. OutWString(ReadWStr);
  1349. OutLn('');
  1350. end;
  1351. vaNil:
  1352. OutLn('nil');
  1353. vaCollection: begin
  1354. OutStr('<');
  1355. while Input.ReadByte <> 0 do begin
  1356. OutLn(Indent);
  1357. Input.Seek(-1, soFromCurrent);
  1358. OutStr(indent + ' item');
  1359. ValueType := TValueType(Input.ReadByte);
  1360. if ValueType <> vaList then
  1361. OutStr('[' + IntToStr(ReadInt(ValueType)) + ']');
  1362. OutLn('');
  1363. ReadPropList(indent + ' ');
  1364. OutStr(indent + ' end');
  1365. end;
  1366. OutLn('>');
  1367. end;
  1368. {vaSingle: begin OutLn('!!Single!!'); exit end;
  1369. vaCurrency: begin OutLn('!!Currency!!'); exit end;
  1370. vaDate: begin OutLn('!!Date!!'); exit end;}
  1371. vaUTF8String: begin
  1372. OutUtf8Str(ReadLStr);
  1373. OutLn('');
  1374. end;
  1375. else
  1376. Raise EReadError.CreateFmt(SErrInvalidPropertyType,[Ord(ValueType)]);
  1377. end;
  1378. end;
  1379. begin
  1380. while Input.ReadByte <> 0 do begin
  1381. Input.Seek(-1, soFromCurrent);
  1382. OutStr(indent + ReadSStr + ' = ');
  1383. ProcessValue(TValueType(Input.ReadByte), Indent);
  1384. end;
  1385. end;
  1386. procedure ReadObject(indent: String);
  1387. var
  1388. b: Byte;
  1389. ObjClassName, ObjName: String;
  1390. ChildPos: LongInt;
  1391. begin
  1392. // Check for FilerFlags
  1393. b := Input.ReadByte;
  1394. if (b and $f0) = $f0 then begin
  1395. if (b and 2) <> 0 then ChildPos := ReadInt;
  1396. end else begin
  1397. b := 0;
  1398. Input.Seek(-1, soFromCurrent);
  1399. end;
  1400. ObjClassName := ReadSStr;
  1401. ObjName := ReadSStr;
  1402. OutStr(Indent);
  1403. if (b and 1) <> 0 then OutStr('inherited')
  1404. else
  1405. if (b and 4) <> 0 then OutStr('inline')
  1406. else OutStr('object');
  1407. OutStr(' ');
  1408. if ObjName <> '' then
  1409. OutStr(ObjName + ': ');
  1410. OutStr(ObjClassName);
  1411. if (b and 2) <> 0 then OutStr('[' + IntToStr(ChildPos) + ']');
  1412. OutLn('');
  1413. ReadPropList(indent + ' ');
  1414. while Input.ReadByte <> 0 do begin
  1415. Input.Seek(-1, soFromCurrent);
  1416. ReadObject(indent + ' ');
  1417. end;
  1418. OutLn(indent + 'end');
  1419. end;
  1420. type
  1421. PLongWord = ^LongWord;
  1422. const
  1423. signature: PChar = 'TPF0';
  1424. begin
  1425. if Input.ReadDWord <> PLongWord(Pointer(signature))^ then
  1426. raise EReadError.Create('Illegal stream image' {###SInvalidImage});
  1427. ReadObject('');
  1428. end;
  1429. procedure ObjectBinaryToText(Input, Output: TStream);
  1430. begin
  1431. ObjectBinaryToText(Input,Output,oteDFM);
  1432. end;
  1433. procedure ObjectTextToBinary(Input, Output: TStream);
  1434. var
  1435. parser: TParser;
  1436. procedure WriteWord(w : word); {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1437. begin
  1438. w:=NtoLE(w);
  1439. Output.WriteWord(w);
  1440. end;
  1441. procedure WriteDWord(lw : longword); {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1442. begin
  1443. lw:=NtoLE(lw);
  1444. Output.WriteDWord(lw);
  1445. end;
  1446. procedure WriteQWord(qw : qword); {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1447. begin
  1448. qw:=NtoLE(qw);
  1449. Output.WriteBuffer(qw,sizeof(qword));
  1450. end;
  1451. {$ifndef FPUNONE}
  1452. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  1453. procedure DoubleToExtended(d : double; e : pointer);
  1454. var mant : qword;
  1455. exp : smallint;
  1456. sign : boolean;
  1457. begin
  1458. mant:=(qword(d) and $000FFFFFFFFFFFFF) shl 12;
  1459. exp :=(qword(d) shr 52) and $7FF;
  1460. sign:=(qword(d) and $8000000000000000)<>0;
  1461. case exp of
  1462. 0 : begin
  1463. if mant<>0 then //denormalized value: hidden bit is 0. normalize it
  1464. begin
  1465. exp:=16383-1022;
  1466. while (mant and $8000000000000000)=0 do
  1467. begin
  1468. dec(exp);
  1469. mant:=mant shl 1;
  1470. end;
  1471. dec(exp); //don't shift, most significant bit is not hidden in extended
  1472. end;
  1473. end;
  1474. 2047 : exp:=$7FFF //either infinity or NaN
  1475. else
  1476. begin
  1477. inc(exp,16383-1023);
  1478. mant:=(mant shr 1) or $8000000000000000; //unhide hidden bit
  1479. end;
  1480. end;
  1481. if sign then exp:=exp or $8000;
  1482. mant:=NtoLE(mant);
  1483. exp:=NtoLE(word(exp));
  1484. move(mant,pbyte(e)[0],8); //mantissa : bytes 0..7
  1485. move(exp,pbyte(e)[8],2); //exponent and sign: bytes 8..9
  1486. end;
  1487. {$ENDIF}
  1488. procedure WriteExtended(e : extended);
  1489. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  1490. var ext : array[0..9] of byte;
  1491. {$ENDIF}
  1492. begin
  1493. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  1494. DoubleToExtended(e,@(ext[0]));
  1495. Output.WriteBuffer(ext[0],10);
  1496. {$ELSE}
  1497. Output.WriteBuffer(e,sizeof(e));
  1498. {$ENDIF}
  1499. end;
  1500. {$endif}
  1501. procedure WriteString(s: String);
  1502. var size : byte;
  1503. begin
  1504. if length(s)>255 then size:=255
  1505. else size:=length(s);
  1506. Output.WriteByte(size);
  1507. if Length(s) > 0 then
  1508. Output.WriteBuffer(s[1], size);
  1509. end;
  1510. procedure WriteLString(Const s: String);
  1511. begin
  1512. WriteDWord(Length(s));
  1513. if Length(s) > 0 then
  1514. Output.WriteBuffer(s[1], Length(s));
  1515. end;
  1516. procedure WriteWString(Const s: WideString);
  1517. var len : longword;
  1518. {$IFDEF ENDIAN_BIG}
  1519. i : integer;
  1520. ws : widestring;
  1521. {$ENDIF}
  1522. begin
  1523. len:=Length(s);
  1524. WriteDWord(len);
  1525. if len > 0 then
  1526. begin
  1527. {$IFDEF ENDIAN_BIG}
  1528. setlength(ws,len);
  1529. for i:=1 to len do
  1530. ws[i]:=widechar(SwapEndian(word(s[i])));
  1531. Output.WriteBuffer(ws[1], len*sizeof(widechar));
  1532. {$ELSE}
  1533. Output.WriteBuffer(s[1], len*sizeof(widechar));
  1534. {$ENDIF}
  1535. end;
  1536. end;
  1537. procedure WriteInteger(value: Int64);
  1538. begin
  1539. if (value >= -128) and (value <= 127) then begin
  1540. Output.WriteByte(Ord(vaInt8));
  1541. Output.WriteByte(byte(value));
  1542. end else if (value >= -32768) and (value <= 32767) then begin
  1543. Output.WriteByte(Ord(vaInt16));
  1544. WriteWord(word(value));
  1545. end else if (value >= -2147483648) and (value <= 2147483647) then begin
  1546. Output.WriteByte(Ord(vaInt32));
  1547. WriteDWord(longword(value));
  1548. end else begin
  1549. Output.WriteByte(ord(vaInt64));
  1550. WriteQWord(qword(value));
  1551. end;
  1552. end;
  1553. procedure ProcessWideString(const left : widestring);
  1554. var ws : widestring;
  1555. begin
  1556. ws:=left+parser.TokenWideString;
  1557. while parser.NextToken = '+' do
  1558. begin
  1559. parser.NextToken; // Get next string fragment
  1560. if not (parser.Token in [toString,toWString]) then
  1561. parser.CheckToken(toWString);
  1562. ws:=ws+parser.TokenWideString;
  1563. end;
  1564. Output.WriteByte(Ord(vaWstring));
  1565. WriteWString(ws);
  1566. end;
  1567. procedure ProcessProperty; forward;
  1568. procedure ProcessValue;
  1569. var
  1570. {$ifndef FPUNONE}
  1571. flt: Extended;
  1572. {$endif}
  1573. s: String;
  1574. stream: TMemoryStream;
  1575. begin
  1576. case parser.Token of
  1577. toInteger:
  1578. begin
  1579. WriteInteger(parser.TokenInt);
  1580. parser.NextToken;
  1581. end;
  1582. {$ifndef FPUNONE}
  1583. toFloat:
  1584. begin
  1585. Output.WriteByte(Ord(vaExtended));
  1586. flt := Parser.TokenFloat;
  1587. WriteExtended(flt);
  1588. parser.NextToken;
  1589. end;
  1590. {$endif}
  1591. toString:
  1592. begin
  1593. s := parser.TokenString;
  1594. while parser.NextToken = '+' do
  1595. begin
  1596. parser.NextToken; // Get next string fragment
  1597. case parser.Token of
  1598. toString : s:=s+parser.TokenString;
  1599. toWString : begin
  1600. ProcessWideString(s);
  1601. exit;
  1602. end
  1603. else parser.CheckToken(toString);
  1604. end;
  1605. end;
  1606. if (length(S)>255) then
  1607. begin
  1608. Output.WriteByte(Ord(vaLString));
  1609. WriteLString(S);
  1610. end
  1611. else
  1612. begin
  1613. Output.WriteByte(Ord(vaString));
  1614. WriteString(s);
  1615. end;
  1616. end;
  1617. toWString:
  1618. ProcessWideString('');
  1619. toSymbol:
  1620. begin
  1621. if CompareText(parser.TokenString, 'True') = 0 then
  1622. Output.WriteByte(Ord(vaTrue))
  1623. else if CompareText(parser.TokenString, 'False') = 0 then
  1624. Output.WriteByte(Ord(vaFalse))
  1625. else if CompareText(parser.TokenString, 'nil') = 0 then
  1626. Output.WriteByte(Ord(vaNil))
  1627. else
  1628. begin
  1629. Output.WriteByte(Ord(vaIdent));
  1630. WriteString(parser.TokenComponentIdent);
  1631. end;
  1632. Parser.NextToken;
  1633. end;
  1634. // Set
  1635. '[':
  1636. begin
  1637. parser.NextToken;
  1638. Output.WriteByte(Ord(vaSet));
  1639. if parser.Token <> ']' then
  1640. while True do
  1641. begin
  1642. parser.CheckToken(toSymbol);
  1643. WriteString(parser.TokenString);
  1644. parser.NextToken;
  1645. if parser.Token = ']' then
  1646. break;
  1647. parser.CheckToken(',');
  1648. parser.NextToken;
  1649. end;
  1650. Output.WriteByte(0);
  1651. parser.NextToken;
  1652. end;
  1653. // List
  1654. '(':
  1655. begin
  1656. parser.NextToken;
  1657. Output.WriteByte(Ord(vaList));
  1658. while parser.Token <> ')' do
  1659. ProcessValue;
  1660. Output.WriteByte(0);
  1661. parser.NextToken;
  1662. end;
  1663. // Collection
  1664. '<':
  1665. begin
  1666. parser.NextToken;
  1667. Output.WriteByte(Ord(vaCollection));
  1668. while parser.Token <> '>' do
  1669. begin
  1670. parser.CheckTokenSymbol('item');
  1671. parser.NextToken;
  1672. // ConvertOrder
  1673. Output.WriteByte(Ord(vaList));
  1674. while not parser.TokenSymbolIs('end') do
  1675. ProcessProperty;
  1676. parser.NextToken; // Skip 'end'
  1677. Output.WriteByte(0);
  1678. end;
  1679. Output.WriteByte(0);
  1680. parser.NextToken;
  1681. end;
  1682. // Binary data
  1683. '{':
  1684. begin
  1685. Output.WriteByte(Ord(vaBinary));
  1686. stream := TMemoryStream.Create;
  1687. try
  1688. parser.HexToBinary(stream);
  1689. WriteDWord(stream.Size);
  1690. Output.WriteBuffer(Stream.Memory^, stream.Size);
  1691. finally
  1692. stream.Free;
  1693. end;
  1694. parser.NextToken;
  1695. end;
  1696. else
  1697. parser.Error(SInvalidProperty);
  1698. end;
  1699. end;
  1700. procedure ProcessProperty;
  1701. var
  1702. name: String;
  1703. begin
  1704. // Get name of property
  1705. parser.CheckToken(toSymbol);
  1706. name := parser.TokenString;
  1707. while True do begin
  1708. parser.NextToken;
  1709. if parser.Token <> '.' then break;
  1710. parser.NextToken;
  1711. parser.CheckToken(toSymbol);
  1712. name := name + '.' + parser.TokenString;
  1713. end;
  1714. WriteString(name);
  1715. parser.CheckToken('=');
  1716. parser.NextToken;
  1717. ProcessValue;
  1718. end;
  1719. procedure ProcessObject;
  1720. var
  1721. Flags: Byte;
  1722. ObjectName, ObjectType: String;
  1723. ChildPos: Integer;
  1724. begin
  1725. if parser.TokenSymbolIs('OBJECT') then
  1726. Flags :=0 { IsInherited := False }
  1727. else begin
  1728. if parser.TokenSymbolIs('INHERITED') then
  1729. Flags := 1 { IsInherited := True; }
  1730. else begin
  1731. parser.CheckTokenSymbol('INLINE');
  1732. Flags := 4;
  1733. end;
  1734. end;
  1735. parser.NextToken;
  1736. parser.CheckToken(toSymbol);
  1737. ObjectName := '';
  1738. ObjectType := parser.TokenString;
  1739. parser.NextToken;
  1740. if parser.Token = ':' then begin
  1741. parser.NextToken;
  1742. parser.CheckToken(toSymbol);
  1743. ObjectName := ObjectType;
  1744. ObjectType := parser.TokenString;
  1745. parser.NextToken;
  1746. if parser.Token = '[' then begin
  1747. parser.NextToken;
  1748. ChildPos := parser.TokenInt;
  1749. parser.NextToken;
  1750. parser.CheckToken(']');
  1751. parser.NextToken;
  1752. Flags := Flags or 2;
  1753. end;
  1754. end;
  1755. if Flags <> 0 then begin
  1756. Output.WriteByte($f0 or Flags);
  1757. if (Flags and 2) <> 0 then
  1758. WriteInteger(ChildPos);
  1759. end;
  1760. WriteString(ObjectType);
  1761. WriteString(ObjectName);
  1762. // Convert property list
  1763. while not (parser.TokenSymbolIs('END') or
  1764. parser.TokenSymbolIs('OBJECT') or
  1765. parser.TokenSymbolIs('INHERITED') or
  1766. parser.TokenSymbolIs('INLINE')) do
  1767. ProcessProperty;
  1768. Output.WriteByte(0); // Terminate property list
  1769. // Convert child objects
  1770. while not parser.TokenSymbolIs('END') do ProcessObject;
  1771. parser.NextToken; // Skip end token
  1772. Output.WriteByte(0); // Terminate property list
  1773. end;
  1774. const
  1775. signature: PChar = 'TPF0';
  1776. begin
  1777. parser := TParser.Create(Input);
  1778. try
  1779. Output.WriteBuffer(signature[0], 4);
  1780. ProcessObject;
  1781. finally
  1782. parser.Free;
  1783. end;
  1784. end;
  1785. procedure ObjectResourceToText(Input, Output: TStream);
  1786. begin
  1787. Input.ReadResHeader;
  1788. ObjectBinaryToText(Input, Output);
  1789. end;
  1790. procedure ObjectTextToResource(Input, Output: TStream);
  1791. var
  1792. StartPos, FixupInfo: LongInt;
  1793. parser: TParser;
  1794. name: String;
  1795. begin
  1796. // Get form type name
  1797. StartPos := Input.Position;
  1798. parser := TParser.Create(Input);
  1799. try
  1800. if not parser.TokenSymbolIs('OBJECT') then parser.CheckTokenSymbol('INHERITED');
  1801. parser.NextToken;
  1802. parser.CheckToken(toSymbol);
  1803. parser.NextToken;
  1804. parser.CheckToken(':');
  1805. parser.NextToken;
  1806. parser.CheckToken(toSymbol);
  1807. name := parser.TokenString;
  1808. finally
  1809. parser.Free;
  1810. Input.Position := StartPos;
  1811. end;
  1812. name := UpperCase(name);
  1813. Output.WriteResourceHeader(name,FixupInfo); // Write resource header
  1814. ObjectTextToBinary(Input, Output); // Convert the stuff!
  1815. Output.FixupResourceHeader(FixupInfo); // Insert real resource data size
  1816. end;
  1817. { Utility routines }
  1818. function LineStart(Buffer, BufPos: PChar): PChar;
  1819. begin
  1820. Result := BufPos;
  1821. while Result > Buffer do begin
  1822. Dec(Result);
  1823. if Result[0] = #10 then break;
  1824. end;
  1825. end;
  1826. procedure CommonInit;
  1827. begin
  1828. SynchronizeTimeoutEvent:=RtlEventCreate;
  1829. InitCriticalSection(ThreadQueueLock);
  1830. MainThreadID:=GetCurrentThreadID;
  1831. ExternalThreads := TThreadList.Create;
  1832. TThread.FProcessorCount := CPUCount;
  1833. InitCriticalsection(ResolveSection);
  1834. InitHandlerList:=Nil;
  1835. FindGlobalComponentList:=nil;
  1836. IntConstList := TThreadList.Create;
  1837. ClassList := TThreadList.Create;
  1838. ClassAliasList := TStringList.Create;
  1839. { on unix this maps to a simple rw synchornizer }
  1840. GlobalNameSpace := TMultiReadExclusiveWriteSynchronizer.Create;
  1841. RegisterInitComponentHandler(TComponent,@DefaultInitHandler);
  1842. end;
  1843. procedure CommonCleanup;
  1844. var
  1845. i: Integer;
  1846. tmpentry: TThread.PThreadQueueEntry;
  1847. begin
  1848. GlobalNameSpace.BeginWrite;
  1849. with IntConstList.LockList do
  1850. try
  1851. for i := 0 to Count - 1 do
  1852. TIntConst(Items[I]).Free;
  1853. finally
  1854. IntConstList.UnlockList;
  1855. end;
  1856. IntConstList.Free;
  1857. ClassList.Free;
  1858. ClassAliasList.Free;
  1859. RemoveFixupReferences(nil, '');
  1860. DoneCriticalsection(ResolveSection);
  1861. GlobalLists.Free;
  1862. ComponentPages.Free;
  1863. FreeAndNil(NeedResolving);
  1864. { GlobalNameSpace is an interface so this is enough }
  1865. GlobalNameSpace:=nil;
  1866. if (InitHandlerList<>Nil) then
  1867. for i := 0 to InitHandlerList.Count - 1 do
  1868. TInitHandler(InitHandlerList.Items[I]).Free;
  1869. InitHandlerList.Free;
  1870. InitHandlerList:=Nil;
  1871. FindGlobalComponentList.Free;
  1872. FindGlobalComponentList:=nil;
  1873. with ExternalThreads.LockList do
  1874. try
  1875. for i := 0 to Count - 1 do
  1876. TThread(Items[i]).Free;
  1877. finally
  1878. ExternalThreads.UnlockList;
  1879. end;
  1880. FreeAndNil(ExternalThreads);
  1881. RtlEventDestroy(SynchronizeTimeoutEvent);
  1882. { clean up the queue, but keep in mind that the entries used for Synchronize
  1883. are owned by the corresponding TThread }
  1884. while Assigned(ThreadQueueHead) do begin
  1885. tmpentry := ThreadQueueHead;
  1886. ThreadQueueHead := tmpentry^.Next;
  1887. if not Assigned(tmpentry^.SyncEvent) then
  1888. Dispose(tmpentry);
  1889. end;
  1890. DoneCriticalSection(ThreadQueueLock);
  1891. end;
  1892. { TFiler implementation }
  1893. {$i filer.inc}
  1894. { TReader implementation }
  1895. {$i reader.inc}
  1896. { TWriter implementations }
  1897. {$i writer.inc}
  1898. {$i twriter.inc}