classes.inc 53 KB

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