Win32.Objects.Mod 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  1. (* Aos, Copyright 2001, Pieter Muller, ETH Zurich; this module ported for the windows version, fof. *)
  2. MODULE Objects; (** AUTHOR "pjm, ejz, fof"; PURPOSE "Active object runtime support"; *)
  3. IMPORT SYSTEM, Trace, Kernel32, Machine, Modules, Heaps;
  4. CONST
  5. HandleExcp = TRUE; (* FALSE -> we asume that it is done correctly by Traps *)
  6. TraceVerbose = FALSE;
  7. StrongChecks = FALSE; defaultStackSize = 0;
  8. TraceOpenClose = FALSE;
  9. CONST
  10. (* Process flags *)
  11. Restart* = 0; (* Restart/Destroy process on exception *)
  12. PleaseHalt* = 10; (* Process requested to Halt itself soon *)
  13. Unbreakable* = 11;
  14. SelfTermination* = 12;
  15. Preempted* = 27; (* Has been preempted. *)
  16. Resistant* = 28; (* Can only be destroyed by itself *)
  17. PleaseStop* = 31; (* Process requested to Terminate or Halt itself soon *)
  18. InActive* = 26; (* needed to prevent processes to call finalizers while in await or lock or unlock, see Kernel.GC *)
  19. (** Process modes *)
  20. Unknown* = 0; Ready* = 1; (* for compatibility with native A2 *)
  21. Running* = 2; AwaitingLock* = 3; AwaitingCond* = 4; AwaitingEvent* = 5; Suspended* = 6; Terminated* = 7;
  22. (** Process priorities *)
  23. MinPriority = 0; (* only system idle processes run at this priority level *)
  24. Low* = 1; Normal* = 2; High* = 3; (* "user" priorities *)
  25. GCPriority* = 4; (* priority of garbage collector *)
  26. Realtime* = 5; (* reserved for interrupt handling and realtime apps, these processes are not allowed to allocate memory *)
  27. (* Process termination halt codes *)
  28. halt* = 2222;
  29. haltUnbreakable* = 2223;
  30. (* constant used in GC Process.FindPointers *)
  31. InitDiff = MAX(LONGINT);
  32. AddressSize = SIZEOF (ADDRESS);
  33. TYPE
  34. CpuCyclesArray* = ARRAY Machine.MaxCPU OF HUGEINT;
  35. ProtectedObject = POINTER TO RECORD END; (* protected object (10000) *)
  36. ProcessQueue = Heaps.ProcessQueue;
  37. Body = PROCEDURE (self: ProtectedObject);
  38. Condition = PROCEDURE (slink: ADDRESS): BOOLEAN;
  39. EventHandler* = PROCEDURE {DELEGATE};
  40. RealtimeEventHandler* = PROCEDURE {DELEGATE, REALTIME};
  41. Timer* = POINTER TO RECORD
  42. next, prev : Timer;
  43. trigger: LONGINT;
  44. handler: EventHandler
  45. END;
  46. RealtimeTimer* = POINTER TO RECORD
  47. next, prev: RealtimeTimer;
  48. trigger: LONGINT;
  49. handler: RealtimeEventHandler
  50. END;
  51. Clock = OBJECT
  52. VAR h: Timer;
  53. ticks: LONGINT;
  54. hevent: Kernel32.HANDLE;
  55. res: Kernel32.BOOL;
  56. mode: LONGINT;
  57. process: Process;
  58. PROCEDURE Wakeup;
  59. VAR res: Kernel32.BOOL;
  60. BEGIN {EXCLUSIVE}
  61. res := Kernel32.SetEvent(hevent)
  62. END Wakeup;
  63. PROCEDURE Finalize(ptr: ANY);
  64. VAR res: Kernel32.BOOL;
  65. BEGIN
  66. IF hevent # 0 THEN res := Kernel32.CloseHandle(hevent); hevent := 0 END
  67. END Finalize;
  68. PROCEDURE &Init*;
  69. VAR fn: Heaps.FinalizerNode;
  70. BEGIN
  71. hevent := Kernel32.CreateEvent(NIL, 0, 0, NIL);
  72. ASSERT(hevent # 0);
  73. NEW(fn); fn.finalizer := SELF.Finalize; Heaps.AddFinalizer(SELF, fn)
  74. END Init;
  75. BEGIN {ACTIVE, SAFE, PRIORITY(High)}
  76. process := CurrentProcess();
  77. mode := process.mode;
  78. LOOP
  79. Machine.Acquire(Machine.Objects);
  80. process.mode := mode;
  81. LOOP
  82. h := event.next; (* event: head of timer event queue *)
  83. ticks := Kernel32.GetTickCount();
  84. IF (h = event) OR (h.trigger - ticks > 0) THEN EXIT END;
  85. event.next := h.next; event.next.prev := event; (* unlink *)
  86. h.next := NIL; h.prev := NIL;
  87. Machine.Release(Machine.Objects);
  88. h.handler(); (* assume handler will return promptly *)
  89. Machine.Acquire(Machine.Objects)
  90. END;
  91. mode := process.mode;
  92. process.mode := AwaitingEvent;
  93. Machine.Release(Machine.Objects);
  94. IF h = event THEN (* sentinel head of timer event queue: wait forever until a new event has been entered in queue *)
  95. res := Kernel32.WaitForSingleObject(hevent, MAX(LONGINT));
  96. ELSE
  97. res := Kernel32.WaitForSingleObject(hevent, h.trigger - ticks);
  98. END;
  99. END
  100. END Clock;
  101. TYPE
  102. Win32Event = Kernel32.HANDLE;
  103. Process* = OBJECT(Heaps.ProcessLink)
  104. VAR
  105. rootedNext : Process; (* to prevent process to be GCed in WinAos *)
  106. obj-: ProtectedObject; (* associated active object *)
  107. state-: Kernel32.Context;
  108. (*
  109. sse: SSEState; (* fpu and sse state of preempted process (only valid if Preempted IN flag) *)
  110. sseAdr: LONGINT;
  111. *)
  112. condition-: Condition; (* awaited process' condition *)
  113. condFP-: LONGINT; (* awaited process' condition's context *)
  114. mode-: LONGINT; (* process state *) (* only changed inside Objects lock ??? *)
  115. procID-: LONGINT; (* processor ID where running, exported for compatibilty , useless in WinAos *)
  116. waitingOn-: ProtectedObject; (* obj this process is waiting on (for lock or condition) *)
  117. id-: LONGINT; (* unique process ID for tracing *)
  118. flags*: SET; (* process flags *)
  119. priority-: LONGINT; (* process priority *)
  120. (*
  121. currPri: LONGINT;
  122. stack*: Machine.Stack; (** user-level stack of process *)
  123. *)
  124. stackBottom: LONGINT;
  125. handle-: Kernel32.HANDLE; (* handle to corresponding Windows thread *)
  126. body: Body;
  127. event: Win32Event;
  128. restartPC-: LONGINT; (** entry point of body, for SAFE exception recovery *)
  129. restartSP-: LONGINT; (** stack level at start of body, for SAFE exception recovery *)
  130. (*
  131. perfCyc*: ARRAY Machine.MaxCPU OF HUGEINT;
  132. priInvCnt: LONGINT; (* counts the nummber of object locks hold that increased currPri of the process *)
  133. exp*: Machine.ExceptionState;
  134. oldReturnPC: LONGINT;
  135. *)
  136. lastThreadTimes: HUGEINT; (*ALEX 2005.12.12*)
  137. PROCEDURE FindRoots; (* override, called while GC, replaces Threads.CheckStacks *)
  138. VAR sp: LONGINT; res: Kernel32.BOOL; pc, bp, curbp: ADDRESS;
  139. n,adr: ADDRESS; desc: Modules.ProcedureDescPointer; i: LONGINT; p {UNTRACED}: ANY;
  140. name: ARRAY 256 OF CHAR;
  141. BEGIN
  142. IF (handle = 0) OR (mode = Terminated) OR (mode < Ready) (* procedure Wrapper not yet started *)
  143. OR (priority > High) (* stack of GC and realtime processes not traced *) THEN
  144. RETURN
  145. END;
  146. state.ContextFlags := Kernel32.ContextControl + Kernel32.ContextInteger;
  147. res := Kernel32.GetThreadContext( handle, state );
  148. IF SYSTEM.VAL( Process, Kernel32.TlsGetValue( tlsIndex ) ) = SELF THEN
  149. sp := Machine.CurrentSP(); bp :=Machine.CurrentBP(); pc := Machine.CurrentPC();
  150. ELSE
  151. sp := state.SP; bp := state.BP; pc := state.PC;
  152. END;
  153. ASSERT ( res # 0, 1004 );
  154. (* stack garbage collection *)
  155. IF Heaps.GCType= Heaps.HeuristicStackInspectionGC THEN
  156. Heaps.Candidate( state.EDI ); Heaps.Candidate( state.ESI );
  157. Heaps.Candidate( state.EBX ); Heaps.Candidate( state.EDX );
  158. Heaps.Candidate( state.ECX ); Heaps.Candidate( state.EAX );
  159. IF (stackBottom # 0) & (sp # 0) THEN
  160. Heaps.RegisterCandidates( sp, stackBottom - sp );
  161. END;
  162. ELSIF Heaps.GCType = Heaps.MetaDataForStackGC THEN
  163. WHILE (bp # Heaps.NilVal) & (sp <= bp) & (bp < stackBottom) DO
  164. SYSTEM.GET(bp, n);
  165. IF ODD(n) THEN (* procedure descriptor at bp *)
  166. DEC(n);
  167. desc := SYSTEM.VAL(Modules.ProcedureDescPointer, n);
  168. IF desc # NIL THEN
  169. (*TRACE(desc.pcFrom, desc.pcLimit, desc.offsets);*)
  170. FOR i := 0 TO LEN(desc.offsets)-1 DO
  171. adr := bp + desc.offsets[i]; (* pointer at offset *)
  172. SYSTEM.GET(adr, p); (* load pointer *)
  173. IF p # NIL THEN
  174. Heaps.Mark(p);
  175. END;
  176. END;
  177. END;
  178. SYSTEM.GET(bp + SIZEOF(ADDRESS), bp);
  179. ELSE (* classical stack frame *)
  180. bp := n;
  181. END;
  182. END;
  183. END;
  184. END FindRoots;
  185. END Process;
  186. TYPE
  187. ExceptionHandler* = PROCEDURE( VAR context: Kernel32.Context;
  188. VAR excpRec: Kernel32.ExceptionRecord;
  189. VAR handled: BOOLEAN);
  190. GCStatusExt = OBJECT(Heaps.GCStatus)
  191. VAR
  192. (*
  193. gcOngoing: BOOLEAN;
  194. event: Kernel32.HANDLE;
  195. caller: Process;
  196. PROCEDURE &Init;
  197. BEGIN
  198. gcOngoing := FALSE;
  199. event := Kernel32.CreateEvent( NIL, Kernel32.False (* auto-reset *), Kernel32.False, NIL ); (* manual set event with initial state = reset *)
  200. ASSERT(event # 0);
  201. END Init;
  202. *)
  203. (*
  204. (* called from Heaps.InvokeGC, i.e. this is a hidden upcall. However, it is necessary to take the Machine.Objects lock here since writing
  205. the set of variables here must not be interrupted, i.e. atomic writing of the set of variables is absolutely necessary. They system may hang
  206. if the lock is not taken. *)
  207. PROCEDURE SetgcOngoing(value: BOOLEAN);
  208. VAR p: Heaps.ProcessLink; cur, r: Process; res: Kernel32.BOOL; num: LONGINT;
  209. BEGIN (* serialize writers *)
  210. IF value THEN
  211. (* Low, Medium or High priority process calls this *)
  212. Machine.Acquire(Machine.Objects);
  213. Machine.Acquire(Machine.Heaps); (* to protect agains concurrent LazySweep *)
  214. r := CurrentProcess();
  215. caller := r;
  216. r.mode := AwaitingEvent;
  217. num := 0;
  218. IF ~gcOngoing THEN
  219. gcOngoing := TRUE;
  220. p := ready.head;
  221. WHILE p # NIL DO
  222. cur := p(Process);
  223. IF ((cur.mode = Ready) OR (cur.mode = Running)) & (cur.priority <= High) & (cur # r) THEN
  224. res := Kernel32.SuspendThread(cur.handle);
  225. cur.mode := Suspended
  226. ELSE INC(num);
  227. END;
  228. p := p.next
  229. END;
  230. (* start GC *)
  231. gcActivity.Activate;
  232. END;
  233. Machine.Release(Machine.Heaps);
  234. Machine.Release(Machine.Objects);
  235. (* no process is running except the caller process and the GC process, no race here *)
  236. res := Kernel32.WaitForSingleObject(event, Kernel32.Infinite); (* block execution *)
  237. ASSERT(res = Kernel32.WaitObject0)
  238. ELSE
  239. (* gcProcess calls this *)
  240. Machine.Acquire(Machine.Objects);
  241. gcOngoing := FALSE;
  242. p := ready.head;
  243. WHILE (p # NIL) DO
  244. cur := p(Process);
  245. (* only suspended and awaiting processes of ready queue are resumed *)
  246. IF cur.mode = Suspended THEN
  247. res := Kernel32.ResumeThread(cur.handle);
  248. cur.mode := Running
  249. END;
  250. p := p.next
  251. END;
  252. caller.mode := Running;
  253. Kernel32.SetEvent(event);
  254. r := CurrentProcess();
  255. ASSERT(r = gcActivity.process);
  256. r.mode := AwaitingEvent;
  257. Machine.Release(Machine.Objects);
  258. END;
  259. END SetgcOngoing;
  260. *)
  261. (* called from Heaps.InvokeGC, i.e. this is a hidden upcall. However, it is necessary to take the Machine.Objects lock here since writing
  262. the set of variables here must not be interrupted, i.e. atomic writing of the set of variables is absolutely necessary. They system may hang
  263. if the lock is not taken. *)
  264. PROCEDURE SetgcOngoing(value: BOOLEAN);
  265. VAR p: Heaps.ProcessLink; cur, r: Process; res: Kernel32.BOOL; num: LONGINT; time: LONGINT;
  266. BEGIN (* serialize writers *)
  267. IF value THEN
  268. (* Low, Medium or High priority process calls this *)
  269. time := Kernel32.GetTickCount();
  270. Machine.Acquire(Machine.Objects);
  271. Machine.Acquire(Machine.Heaps); (* to protect agains concurrent LazySweep *)
  272. r := CurrentProcess();
  273. num := 0;
  274. p := ready.head;
  275. WHILE p # NIL DO
  276. cur := p(Process);
  277. IF ((cur.mode = Ready) OR (cur.mode = Running)) & (cur.priority <= High) & (cur # r) THEN
  278. res := Kernel32.SuspendThread(cur.handle);
  279. cur.mode := Suspended
  280. ELSE INC(num);
  281. END;
  282. p := p.next
  283. END;
  284. Heaps.CollectGarbage(Modules.root);
  285. p := ready.head;
  286. WHILE (p # NIL) DO
  287. cur := p(Process);
  288. (* only suspended and awaiting processes of ready queue are resumed *)
  289. IF cur.mode = Suspended THEN
  290. res := Kernel32.ResumeThread(cur.handle);
  291. cur.mode := Running
  292. END;
  293. p := p.next
  294. END;
  295. Machine.Release(Machine.Heaps);
  296. Machine.Release(Machine.Objects);
  297. time := Kernel32.GetTickCount()-time;
  298. IF Heaps.trace THEN Trace.String("GC Called -- duration "); Trace.Int(time,0); Trace.String(" ms."); Trace.Ln END;
  299. IF finalizerCaller # NIL THEN finalizerCaller.Activate() END;
  300. END;
  301. END SetgcOngoing;
  302. END GCStatusExt;
  303. GCActivity = OBJECT
  304. (*
  305. VAR
  306. res: Kernel32.BOOL;
  307. event: Kernel32.HANDLE;
  308. process: Process;
  309. PROCEDURE &Init;
  310. BEGIN
  311. ASSERT(gcActivity = NIL); (* should only exist once *)
  312. event := Kernel32.CreateEvent( NIL, Kernel32.False (* auto-reset *), Kernel32.False, NIL ); (* manual set event with initial state = reset *)
  313. END Init;
  314. PROCEDURE Activate;
  315. BEGIN
  316. process.mode := Running;
  317. res := Kernel32.SetEvent(event);
  318. END Activate;
  319. PROCEDURE Wait;
  320. BEGIN
  321. process.mode := AwaitingEvent;
  322. res := Kernel32.WaitForSingleObject(event, Kernel32.Infinite); (* block execution *)
  323. ASSERT(res = Kernel32.WaitObject0);
  324. END Wait;
  325. BEGIN {ACTIVE, SAFE, PRIORITY(GCPriority)}
  326. Machine.Acquire(Machine.Objects);
  327. process := CurrentProcess();
  328. process.mode := AwaitingEvent;
  329. Machine.Release(Machine.Objects);
  330. LOOP
  331. Wait;
  332. (* process is scheduled -> perform garbage collection now *)
  333. Heaps.CollectGarbage(Modules.root);
  334. Heaps.gcStatus.SetgcOngoing(FALSE); (* resumes waiting processes and suspends itself *)
  335. IF finalizerCaller # NIL THEN finalizerCaller.Activate() END;
  336. END
  337. *)
  338. END GCActivity;
  339. FinalizedCollection* = OBJECT
  340. PROCEDURE RemoveAll*(obj: ANY); (** abstract *)
  341. BEGIN HALT(301) END RemoveAll;
  342. END FinalizedCollection;
  343. FinalizerNode* = POINTER TO RECORD (Heaps.FinalizerNode)
  344. c*: FinalizedCollection (* base type for collection containing object *)
  345. END;
  346. FinalizerCaller = OBJECT (* separate active object that calls finalizers *)
  347. VAR n: Heaps.FinalizerNode;
  348. event: Kernel32.HANDLE;
  349. process: Process;
  350. PROCEDURE &Init;
  351. BEGIN
  352. event := Kernel32.CreateEvent( NIL, Kernel32.False (* automatic *), Kernel32.False, NIL );
  353. ASSERT(event # 0);
  354. END Init;
  355. PROCEDURE Wait;
  356. VAR res: Kernel32.BOOL; mode: LONGINT;
  357. BEGIN
  358. mode := process.mode;
  359. process.mode := AwaitingEvent;
  360. res := Kernel32.WaitForSingleObject(event, Kernel32.Infinite);
  361. ASSERT(res = Kernel32.WaitObject0);
  362. process.mode := mode;
  363. END Wait;
  364. PROCEDURE Activate;
  365. VAR res: Kernel32.BOOL;
  366. BEGIN
  367. res := Kernel32.SetEvent(event);
  368. END Activate;
  369. BEGIN {ACTIVE, SAFE, PRIORITY(High)}
  370. process := CurrentProcess();
  371. LOOP
  372. Wait;
  373. LOOP
  374. n := Heaps.GetFinalizer();
  375. IF n = NIL THEN EXIT END;
  376. IF n IS FinalizerNode THEN
  377. n( FinalizerNode ).c.RemoveAll( n.objStrong ) (* remove it if it is not removed yet *)
  378. END;
  379. IF n.finalizer # NIL THEN
  380. n.finalizer( n.objStrong ) (* may acquire locks *)
  381. END
  382. END
  383. END;
  384. END FinalizerCaller;
  385. VAR
  386. awc-, awl-: LONGINT;
  387. oberonLoop*: ANY; (* Oberon Loop Process temporary workaround for Threads.oberonLoop *)
  388. break: ARRAY 16 OF CHAR;
  389. terminateProc: PROCEDURE;
  390. ready: ProcessQueue; (* contains running processes in this implementation *)
  391. numberOfProcessors: LONGINT; (* cached value of Machine.NumberOfProcessors() *)
  392. finalizerCaller: FinalizerCaller; (* active object for finalizer process, regarded as aprt of GC *)
  393. gcActivity: GCActivity;
  394. event: Timer; (* list of events *)
  395. clock: Clock;
  396. tlsIndex: LONGINT;
  397. nProcs: LONGINT;
  398. excplock: Kernel32.CriticalSection; exceptionhandler: ExceptionHandler;
  399. (* Set the current process' priority. *)
  400. PROCEDURE SetPriority*( priority: LONGINT );
  401. VAR r: Process; prio: LONGINT; res: Kernel32.BOOL;
  402. BEGIN
  403. ASSERT((priority >= Low) & (priority <= Realtime)); (* priority in bounds *)
  404. r := CurrentProcess(); r.priority := priority;
  405. CASE priority OF
  406. MinPriority:
  407. prio := Kernel32.ThreadPriorityIdle
  408. | Low:
  409. prio := Kernel32.ThreadPriorityBelowNormal
  410. | High:
  411. prio := Kernel32.ThreadPriorityAboveNormal
  412. | GCPriority, Realtime:
  413. prio := Kernel32.ThreadPriorityTimeCritical
  414. ELSE (* Normal *)
  415. prio := Kernel32.ThreadPriorityNormal
  416. END;
  417. res := Kernel32.SetThreadPriority( r.handle, prio );
  418. ASSERT(r.handle # 0);
  419. ASSERT(res # 0)
  420. END SetPriority;
  421. (** Return TRUE iff the specified protected object is locked exclusive to the current process. *)
  422. PROCEDURE LockedByCurrent*( obj: ANY ): BOOLEAN;
  423. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; res: BOOLEAN;
  424. BEGIN
  425. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  426. ASSERT(hdr IS Heaps.ProtRecBlock);
  427. Machine.Acquire(Machine.Objects);
  428. res := (hdr.lockedBy = ActiveObject());
  429. Machine.Release(Machine.Objects);
  430. RETURN res
  431. END LockedByCurrent;
  432. PROCEDURE Yield*;
  433. BEGIN
  434. Kernel32.Sleep(0)
  435. END Yield;
  436. (** Return current process. (DEPRECATED, use ActiveObject) *)
  437. PROCEDURE CurrentProcess*( ): Process;
  438. BEGIN
  439. RETURN SYSTEM.VAL(Process, Kernel32.TlsGetValue(tlsIndex));
  440. END CurrentProcess;
  441. (* Return stack bottom of process. For compatibility WinAos/UnixAos/NativeAos *)
  442. PROCEDURE GetStackBottom*(p: Process): ADDRESS;
  443. BEGIN
  444. RETURN p.stackBottom
  445. END GetStackBottom;
  446. (** Return the active object currently executing. *)
  447. PROCEDURE ActiveObject* (): ANY;
  448. VAR r: Process;
  449. BEGIN
  450. r := SYSTEM.VAL(Process, Kernel32.TlsGetValue(tlsIndex));
  451. RETURN r.obj
  452. END ActiveObject;
  453. (** Return the ID of the active currently executing process. *)
  454. PROCEDURE GetProcessID* (): LONGINT;
  455. VAR r: Process;
  456. BEGIN
  457. r := SYSTEM.VAL (Process, Kernel32.TlsGetValue( tlsIndex ));
  458. RETURN r.id
  459. END GetProcessID;
  460. (* Get a process from a queue (NIL if none). Caller must hold lock for specific queue. *)
  461. PROCEDURE Get(VAR queue: ProcessQueue; VAR new: Process);
  462. VAR t: Heaps.ProcessLink;
  463. BEGIN
  464. t := queue.head;
  465. IF t = NIL THEN (* zero elements in queue *)
  466. (* skip *)
  467. ELSIF t = queue.tail THEN (* one element in queue *)
  468. queue.head := NIL; queue.tail := NIL (* {(t.next = NIL) & (t.prev = NIL)} *)
  469. ELSE (* more than one element in queue *)
  470. queue.head := t.next; t.next := NIL; queue.head.prev := NIL
  471. END;
  472. ASSERT((t = NIL) OR (t.next = NIL ) & (t.prev = NIL)); (* temp strong check *)
  473. IF t = NIL THEN
  474. new := NIL
  475. ELSE
  476. ASSERT(t IS Process);
  477. new := t(Process)
  478. END
  479. END Get;
  480. (* Put a process in a queue. Caller must hold lock for specific queue. *)
  481. (* If t was running, be careful to protect Put and the subsequent SwitchTo with the ready lock. *)
  482. PROCEDURE Put(VAR queue: ProcessQueue; t: Process);
  483. BEGIN (* {t # NIL & t.next = NIL & t.prev = NIL} *)
  484. IF StrongChecks THEN
  485. ASSERT((t.next = NIL) & (t.prev = NIL))
  486. END;
  487. t.next := NIL; t.prev := NIL; (* ug *)
  488. IF queue.head = NIL THEN (* queue empty *)
  489. queue.head := t
  490. ELSE (* queue not empty *)
  491. queue.tail.next := t; t.prev := queue.tail
  492. END;
  493. queue.tail := t
  494. END Put;
  495. (* starting address of user stack for current thread, called stack top in TIB.H *)
  496. PROCEDURE -StackBottom*( ): LONGINT;
  497. CODE {SYSTEM.i386}
  498. DB 064H
  499. DB 08BH
  500. DB 005H
  501. DB 004H
  502. DB 000H
  503. DB 000H
  504. DB 000H
  505. END StackBottom;
  506. PROCEDURE {WINAPI} ExcpFrmHandler( VAR excpRec: Kernel32.ExceptionRecord; excpFrame: Kernel32.ExcpFrmPtr;
  507. VAR context: Kernel32.Context; dispatch: LONGINT ): LONGINT;
  508. VAR m: Modules.Module; eip, ebp, stack: LONGINT; pc, handler, fp, sp: LONGINT; handled: BOOLEAN; t: Process;
  509. BEGIN
  510. handled := FALSE;
  511. Kernel32.EnterCriticalSection( excplock );
  512. (*
  513. fof: commenting this resolved a problem with multiple traps that a are catched with FINALLY statements in Windows Vista
  514. in Windows XP not necessary if Kernel32.SetThreadContext is not used (better to return gracefully from this handler)
  515. SetCurrent(excpFrame);
  516. *)
  517. t := CurrentProcess();
  518. IF exceptionhandler = NIL THEN
  519. Trace.StringLn ( "Objects: No exception handler installed" );
  520. IF HandleExcp THEN
  521. Trace.String( "EXCEPTION " ); Trace.Hex( excpRec.ExceptionCode, 1 );
  522. Trace.String( " at " ); Trace.Hex( excpRec.ExceptionAddress, 1 );
  523. Trace.Ln(); Trace.String( "EAX " ); Trace.Hex( context.EAX, 1 );
  524. Trace.String( " EBX " ); Trace.Hex( context.EBX, 1 ); Trace.Ln();
  525. Trace.String( "ECX " ); Trace.Hex( context.ECX, 1 ); Trace.String( " EDX " );
  526. Trace.Hex( context.EDX, 1 ); Trace.Ln(); Trace.String( "EDI " );
  527. Trace.Hex( context.EDI, 1 ); Trace.String( " ESI " );
  528. Trace.Hex( context.ESI, 1 ); Trace.Ln(); Trace.String( "EBP " );
  529. Trace.Hex( context.BP, 1 ); Trace.String( " ESP " );
  530. Trace.Hex( context.SP, 1 ); Trace.Ln(); Trace.String( "EIP " );
  531. Trace.Hex( context.PC, 1 ); Trace.Ln(); Trace.Ln();
  532. eip := excpRec.ExceptionAddress; ebp := context.BP;
  533. IF eip = 0 THEN SYSTEM.GET( context.SP, eip ) END;
  534. stack := StackBottom();
  535. LOOP
  536. Trace.String( "at ebp= " ); Trace.Hex( ebp, 1 ); Trace.String( "H : " );
  537. m := Modules.ThisModuleByAdr( eip );
  538. IF m # NIL THEN
  539. Trace.String( m.name ); Trace.String( " " );
  540. Trace.Hex( eip - SYSTEM.VAL( LONGINT, ADDRESSOF( m.code[0] ) ), 1 );
  541. ELSE Trace.String( "EIP " ); Trace.Hex( eip, 1 )
  542. END;
  543. Trace.Ln();
  544. IF (ebp # 0) & (ebp < stack) THEN (* if ebp is 0 in first frame *)
  545. SYSTEM.GET( ebp + 4, eip ); (* return addr from stack *)
  546. SYSTEM.GET( ebp, ebp ); (* follow dynamic link *)
  547. ELSE EXIT
  548. END
  549. END;
  550. Trace.Ln();
  551. handled := FALSE; fp := context.BP; sp := context.SP;
  552. pc := context.PC; handler := Modules.GetExceptionHandler( pc );
  553. IF handler # -1 THEN (* Handler in the current PAF *)
  554. context.PC := handler; handled := TRUE;
  555. (*SetTrapVariable(pc, fp); SetLastExceptionState(exc)*)
  556. ELSE
  557. WHILE (fp # 0) & (handler = -1) DO
  558. SYSTEM.GET( fp + 4, pc );
  559. pc := pc - 1; (* CALL instruction, machine dependant!!! *)
  560. handler := Modules.GetExceptionHandler( pc );
  561. sp := fp; (* Save the old framepointer into the stack pointer *)
  562. SYSTEM.GET( fp, fp ) (* Unwind PAF *)
  563. END;
  564. IF handler = -1 THEN handled := FALSE;
  565. ELSE
  566. context.PC := handler; context.BP := fp; context.SP := sp;
  567. (* SetTrapVariable(pc, fp); SetLastExceptionState(exc);*)
  568. handled := TRUE
  569. END
  570. END;
  571. ELSE Trace.StringLn ( "Warning: FINALLY statement cannot be treated !" );
  572. END
  573. ELSE exceptionhandler( context, excpRec, handled );
  574. END;
  575. IF ~handled THEN
  576. context.PC := t.restartPC; context.SP := t.restartSP;
  577. context.BP := t.stackBottom;
  578. ELSIF TraceVerbose THEN Trace.StringLn ( "trying to jump to FINALLY pc..." );
  579. END;
  580. Kernel32.LeaveCriticalSection( excplock );
  581. IF TraceVerbose THEN
  582. Machine.Acquire (Machine.TraceOutput);
  583. Trace.String( "recover process; eip=" ); Trace.Int( context.PC, 10 );
  584. Trace.String( "; sp= " ); Trace.Int( context.SP, 10 ); Trace.String( "; ebp= " );
  585. Trace.Int( context.BP, 10 ); Trace.Ln;
  586. Machine.Release (Machine.TraceOutput);
  587. END;
  588. RETURN Kernel32.ExceptionContinueSearch; (* sets thread context and continues where specified in context *)
  589. END ExcpFrmHandler;
  590. (* get the currently installed execption frame *)
  591. (* PROCEDURE -GetCur 64H, 8BH, 0DH, 0, 0, 0, 0; (* MOV ECX, FS:[0] *) *)
  592. (* Better *)
  593. PROCEDURE -GetCur;
  594. CODE {SYSTEM.i386}
  595. DB 064H, 08BH, 00DH, 000H, 000H, 000H, 000H
  596. END GetCur;
  597. PROCEDURE GetCurrent( ): Kernel32.ExcpFrmPtr;
  598. VAR cur: Kernel32.ExcpFrmPtr;
  599. BEGIN
  600. GetCur;
  601. cur := SYSTEM.VAL(Kernel32.ExcpFrmPtr,Machine.GetECX());
  602. (* RETURN ECX *)
  603. RETURN cur
  604. END GetCurrent;
  605. (* install a new exception frame *)
  606. (* PROCEDURE -SetCur 64H, 0A3H, 0, 0, 0, 0; (* MOV FS:[0], EAX *)*)
  607. (* Better *)
  608. PROCEDURE -SetCur;
  609. CODE {SYSTEM.i386}
  610. DB 064H, 0A3H, 000H, 000H, 000H, 000H
  611. END SetCur;
  612. PROCEDURE SetCurrent( cur: Kernel32.ExcpFrmPtr );
  613. BEGIN
  614. Machine.SetEAX(SYSTEM.VAL(LONGINT,cur));
  615. (* EAX := cur *)
  616. SetCur
  617. END SetCurrent;
  618. PROCEDURE RemoveExcpFrm( VAR excpfrm: Kernel32.ExcpFrm );
  619. VAR this: Kernel32.ExcpFrmPtr;
  620. BEGIN
  621. this := GetCurrent();
  622. (* ASSERT ( this = ADDRESSOF( excpfrm ) ); *)
  623. IF this # ADDRESSOF( excpfrm ) THEN Trace.StringLn ( "RemoveExcpFrm: Problem with excpfrm pointer" );
  624. ELSE SetCurrent( excpfrm.link )
  625. END;
  626. END RemoveExcpFrm;
  627. PROCEDURE InstallExcpFrm( VAR excpfrm: Kernel32.ExcpFrm );
  628. BEGIN
  629. excpfrm.link := GetCurrent(); excpfrm.handler := ExcpFrmHandler;
  630. SetCurrent( ADDRESSOF( excpfrm ) )
  631. END InstallExcpFrm;
  632. PROCEDURE InQueue( queue: ProcessQueue; t: Process ): BOOLEAN;
  633. VAR p: Heaps.ProcessLink;
  634. BEGIN
  635. p := queue.head;
  636. WHILE (p # NIL ) & (p # t) DO p := p.next; END;
  637. RETURN (p = t);
  638. END InQueue;
  639. (* Remove a process from a queue that contains it. Caller must hold lock for specific queue. *)
  640. (* Not intended for frequent use. *)
  641. (* does not check if queue contained t ! *)
  642. PROCEDURE Remove( VAR queue: ProcessQueue; t: Process );
  643. BEGIN
  644. IF StrongChecks THEN
  645. ASSERT(InQueue(queue, t));
  646. ASSERT(t # NIL);
  647. END;
  648. IF t.prev # NIL THEN t.prev.next := t.next END;
  649. IF t.next # NIL THEN t.next.prev := t.prev END;
  650. IF t = queue.head THEN queue.head := t.next END;
  651. IF t = queue.tail THEN queue.tail := t.prev END;
  652. ASSERT((queue.head = NIL) OR (queue.head.prev = NIL) & (queue.tail.next = NIL));
  653. t.prev := NIL; t.next := NIL
  654. END Remove;
  655. PROCEDURE WriteType(obj: ANY);
  656. VAR type: LONGINT;
  657. BEGIN
  658. IF obj = NIL THEN Trace.String(" > NIL");
  659. ELSE
  660. Trace.String(" > "); SYSTEM.GET(SYSTEM.VAL(LONGINT, obj) + Heaps.TypeDescOffset, type);
  661. Heaps.WriteType(type);
  662. END;
  663. END WriteType;
  664. PROCEDURE terminate( t: Process );
  665. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; res: Kernel32.BOOL; shutdown: BOOLEAN;
  666. BEGIN
  667. IF t = NIL THEN RETURN END;
  668. (* see Objects.TerminateThis *)
  669. Machine.Acquire( Machine.Objects );
  670. IF TraceVerbose OR TraceOpenClose THEN
  671. Machine.Acquire (Machine.TraceOutput);
  672. Trace.String( "Terminating process " ); Trace.Int( t.id, 1 ); WriteType( t.obj ); Trace.Ln;
  673. Machine.Release (Machine.TraceOutput);
  674. END;
  675. IF (t.mode = Ready) OR (t.mode = Running) THEN Remove( ready, t );
  676. ELSIF t.mode = AwaitingLock THEN
  677. SYSTEM.GET(SYSTEM.VAL(ADDRESS, t.waitingOn) + Heaps.HeapBlockOffset, hdr);
  678. ASSERT(hdr IS Heaps.ProtRecBlock);
  679. Remove( hdr.awaitingLock, t ); Machine.Release( Machine.Objects );
  680. HALT( 97 )
  681. ELSIF t.mode = AwaitingCond THEN
  682. SYSTEM.GET(SYSTEM.VAL(ADDRESS, t.waitingOn) + Heaps.HeapBlockOffset, hdr);
  683. ASSERT(hdr IS Heaps.ProtRecBlock);
  684. Remove( hdr.awaitingCond, t ); Machine.Release( Machine.Objects );
  685. HALT( 98 )
  686. ELSE Machine.Release( Machine.Objects );
  687. HALT( 99 )
  688. END;
  689. t.mode := Terminated; (* a process can also be "terminated" if the queue containing it is garbage collected *)
  690. t.stackBottom := 0; t.state.SP := 0;
  691. t.restartPC := 0;
  692. IF t.event # 0 THEN res := Kernel32.CloseHandle( t.event ); t.event := 0 END;
  693. DEC( nProcs ); shutdown := (nProcs = 0);
  694. Machine.Release( Machine.Objects );
  695. IF shutdown THEN
  696. Trace.StringLn ( " Objects: shutdown" ); Modules.Shutdown( -1 );
  697. Kernel32.ExitProcess( 0 )
  698. END
  699. END terminate;
  700. PROCEDURE {WINAPI} Wrapper( lpParameter: ANY ): LONGINT;
  701. VAR t: Process; obj: ProtectedObject; res: Kernel32.BOOL; bp,sp: LONGINT;
  702. excpfrm: Kernel32.ExcpFrm;
  703. BEGIN
  704. (* it may happen that the garbage collector runs right here and ignores this procedure.
  705. This is not a problem since lpParameter (being a reference to a process) is protected by the process lists *)
  706. Machine.Acquire(Machine.Objects);
  707. res := Kernel32.TlsSetValue(tlsIndex, SYSTEM.VAL(LONGINT, lpParameter));
  708. t := lpParameter(Process); obj := t.obj;
  709. ASSERT(res # 0);
  710. InstallExcpFrm(excpfrm);
  711. SetPriority(t.priority);
  712. bp := Machine.CurrentBP();
  713. sp := Machine.CurrentSP();
  714. t.restartSP := sp;
  715. t.stackBottom := bp;
  716. IF t.restartPC = SYSTEM.VAL(ADDRESS, terminateProc) THEN DEC(t.restartSP, 4)
  717. ELSE DEC(t.restartSP, 8)
  718. END;
  719. IF TraceVerbose THEN
  720. Machine.Acquire(Machine.TraceOutput);
  721. Trace.String("New process; restartPC= "); Trace.Int(t.restartPC, 15);
  722. Trace.String("; restartSP= "); Trace.Int(t.restartSP, 15); Trace.String("; stackBottom= ");
  723. Trace.Int(t.stackBottom, 15); Trace.Ln;
  724. Machine.Release(Machine.TraceOutput);
  725. END;
  726. t.mode := Running;
  727. (* now gc is enabled for this process stack *)
  728. Machine.Release(Machine.Objects);
  729. (* loop all processes that the GC did not see during process suspending because they were in the very moment being generated (just before the locked section) *)
  730. (*! should not be necessary any more as GC runs immediately and without scheduling decisions
  731. WHILE (gcActivity # NIL) & (gcActivity.process # NIL) & (gcActivity.process.mode = Running) DO END;
  732. *)
  733. t.body(obj);
  734. terminate(t);
  735. RemoveExcpFrm(excpfrm);
  736. RETURN 0
  737. END Wrapper;
  738. PROCEDURE FinalizeProcess(t: ANY);
  739. VAR p: Process; res: Kernel32.BOOL;
  740. BEGIN
  741. p := t(Process);
  742. IF TraceVerbose THEN
  743. Machine.Acquire (Machine.TraceOutput);
  744. Trace.String("Finalizing Process"); Trace.Int(p.id, 1);
  745. WriteType(p.obj); Trace.Ln;
  746. Machine.Release (Machine.TraceOutput);
  747. END;
  748. IF p.mode # Terminated THEN
  749. IF p.mode = AwaitingLock THEN DEC(awl);
  750. ELSIF p.mode = AwaitingCond THEN DEC(awc);
  751. END;
  752. (* no reference to the object any more *)
  753. Trace.String ("Closing unreferenced process"); (*Trace.Int(p.mode,20); Trace.Int( p.id, 20 ); *) Trace.Ln; (* Trace.Ln *)
  754. (* this usually happens, when an objects process waits on its own objtec and no reference exists any more. Then the object is discarded and
  755. consequently the process is unreferenced (except in the object). This cannot happen when there are still other references on the object.
  756. example:
  757. TYPE
  758. Object= OBJECT VAR active: BOOLEAN; BEGIN{ACTIVE} active := FALSE; AWAIT(active) END Object;
  759. VAR o: Object;
  760. BEGIN NEW(o);
  761. END;
  762. *)
  763. END;
  764. p.mode := Terminated; (* fof for GC problem *)
  765. IF p.handle # 0 THEN
  766. res := Kernel32.CloseHandle(p.handle); p.handle := 0
  767. END
  768. END FinalizeProcess;
  769. PROCEDURE TerminateProc;
  770. BEGIN
  771. terminate(CurrentProcess());
  772. Kernel32.ExitThread(0);
  773. Kernel32.Sleep(999999); (* wait until dependent threads terminated *)
  774. END TerminateProc;
  775. (* Allocate a new process associated with "obj". Must be outside lock region, because of potential GC. *)
  776. PROCEDURE NewProcess(body: Body; priority: LONGINT; flags: SET; obj: ProtectedObject; VAR new: Process);
  777. VAR t,r: Process; fn: Heaps.FinalizerNode;
  778. BEGIN
  779. NEW(t);
  780. t.handle := 0;
  781. IF priority = 0 THEN (* no priority specified *)
  782. r := CurrentProcess();
  783. t.priority := r.priority (* inherit priority of creator *)
  784. ELSIF priority > 0 THEN (* positive priority specified *)
  785. t.priority := priority
  786. ELSE (* negative priority specified (only for Idle process) *)
  787. t.priority := MinPriority
  788. END;
  789. NEW(fn); (* implicit call Heaps.NewRec -> might invoke GC *)
  790. Machine.Acquire(Machine.Objects);
  791. t.next := NIL; t.prev := NIL; t.rootedNext := NIL;
  792. t.waitingOn := NIL; t.flags := flags; t.obj := obj; t.mode := Unknown;
  793. t.body := body; t.event := 0; fn.finalizer := FinalizeProcess;
  794. Heaps.AddFinalizer(t, fn);
  795. IF Restart IN flags THEN (* restart object body *)
  796. t.restartPC := SYSTEM.VAL(ADDRESS, body);
  797. ELSE (* terminate process *)
  798. t.restartPC := SYSTEM.VAL(ADDRESS, terminateProc);
  799. END;
  800. t.handle := Kernel32.CreateThread(0, defaultStackSize, Wrapper, t, {}, t.id);
  801. IF TraceVerbose OR TraceOpenClose THEN
  802. Machine.Acquire(Machine.TraceOutput);
  803. Trace.String("NewProcess: " ); Trace.Int(t.id, 1); WriteType(obj); Trace.Ln;
  804. Machine.Release(Machine.TraceOutput);
  805. END;
  806. ASSERT(t.handle # 0);
  807. new := t;
  808. END NewProcess;
  809. (* Create the process associated with an active object (kernel call). *)
  810. PROCEDURE CreateProcess*(body: Body; priority: LONGINT; flags: SET; obj: ProtectedObject);
  811. VAR t : Process; heapBlock {UNTRACED}: Heaps.HeapBlock;
  812. BEGIN
  813. ASSERT(priority >= 0, 1000); ASSERT(priority <=Realtime, 1001);
  814. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, heapBlock);
  815. ASSERT(heapBlock IS Heaps.ProtRecBlock); (* protected object *)
  816. IF Restart IN flags THEN INCL(flags, Resistant) END; (* SAFE => Restart & Resistant *)
  817. NewProcess(body, priority, flags, obj, t); INC(nProcs); (* acquires Machine.Objects lock *)
  818. t.mode := Ready; Put(ready, t);
  819. Machine.Release(Machine.Objects)
  820. END CreateProcess;
  821. (* The procedure Lock, Unlock and Await do not use header locks since it turned out that the header locks sometimes were finalized
  822. too early. *)
  823. PROCEDURE Lock*(obj: ProtectedObject; exclusive: BOOLEAN );
  824. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; r: Process; res: LONGINT;
  825. BEGIN (* {called from user level} *)
  826. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  827. IF StrongChecks THEN
  828. ASSERT(hdr IS Heaps.ProtRecBlock); (* protected object *)
  829. ASSERT(exclusive) (* shared not implemented yet *)
  830. END;
  831. r := CurrentProcess();
  832. IF StrongChecks THEN
  833. ASSERT(hdr # NIL, 1001);
  834. ASSERT(r # NIL, 1002);
  835. END;
  836. Machine.Acquire(Machine.Objects);
  837. IF hdr.count = 0 THEN (* not locked *)
  838. hdr.count := -1; hdr.lockedBy := r;
  839. Machine.Release(Machine.Objects)
  840. ELSE (* already locked *)
  841. IF hdr.lockedBy = r THEN
  842. Machine.Release(Machine.Objects);
  843. HALT(2203) (* nested locks not allowed *)
  844. END;
  845. ASSERT(r.waitingOn = NIL); (* sanity check *)
  846. Remove(ready, r);
  847. IF r.event = 0 THEN
  848. r.event := Kernel32.CreateEvent( NIL, Kernel32.False (* auto *), Kernel32.False, NIL ); (* auto reset event with initial state = reset *)
  849. ASSERT ( r.event # 0, 1239 );
  850. END;
  851. r.waitingOn := obj; r.mode := AwaitingLock;
  852. Put(hdr.awaitingLock, r); INC(awl);
  853. Machine.Release(Machine.Objects);
  854. res := Kernel32.WaitForSingleObject(r.event, Kernel32.Infinite); (* block execution *)
  855. ASSERT(res = Kernel32.WaitObject0);
  856. IF StrongChecks THEN
  857. ASSERT(hdr.lockedBy = r); (* at this moment only this process can own the lock and only this process can release it*)
  858. END;
  859. END
  860. END Lock;
  861. (* Find the first true condition from the queue and remove it. Assume the object is currently locked. *)
  862. PROCEDURE FindCondition( VAR q: ProcessQueue ): Process;
  863. VAR first, cand: Process;
  864. BEGIN
  865. Get( q, first );
  866. IF first.condition( first.condFP ) THEN RETURN first END;
  867. Put( q, first );
  868. WHILE q.head # first DO
  869. Get( q, cand );
  870. IF cand.condition( cand.condFP ) THEN RETURN cand END;
  871. Put( q, cand )
  872. END;
  873. RETURN NIL
  874. END FindCondition;
  875. (* The procedure Lock, Unlock and Await do not use header locks since it turned out that the header locks sometimes were finalized
  876. too early. *)
  877. PROCEDURE Unlock*( obj: ProtectedObject; dummy: BOOLEAN );
  878. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; t, c: Process; res: LONGINT;
  879. BEGIN
  880. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  881. IF StrongChecks THEN
  882. ASSERT(hdr IS Heaps.ProtRecBlock) (* protected object *)
  883. END;
  884. ASSERT(hdr.count = -1); (* exclusive locked *)
  885. Machine.Acquire(Machine.Objects);
  886. IF hdr.awaitingCond.head # NIL THEN (* evaluate the waiting conditions *)
  887. (* we are holding the lock, so the queue can not change (to do: except in TerminateThis) *)
  888. c := FindCondition(hdr.awaitingCond); (* interrupts should be on during this call *)
  889. ELSE
  890. c := NIL
  891. END;
  892. IF c = NIL THEN (* no true condition found, check the lock queue *)
  893. Get(hdr.awaitingLock, t);
  894. IF t # NIL THEN
  895. hdr.lockedBy := t;
  896. t.waitingOn := NIL;
  897. ELSE
  898. hdr.lockedBy := NIL; hdr.count := 0
  899. END
  900. ELSE (* true condition found, transfer the lock *)
  901. c.waitingOn := NIL; hdr.lockedBy := c;
  902. t := NIL
  903. END;
  904. IF c # NIL THEN
  905. Put(ready, c); c.mode := Running; DEC(awc);
  906. res := Kernel32.SetEvent(c.event);
  907. ASSERT (res # 0, 1001);
  908. ELSIF t # NIL THEN
  909. Put(ready, t); t.mode := Running; DEC(awl);
  910. res := Kernel32.SetEvent(t.event);
  911. ASSERT (res # 0, 1002);
  912. END;
  913. Machine.Release( Machine.Objects )
  914. END Unlock;
  915. (* The procedure Lock, Unlock and Await do not use header locks since it turned out that the header locks sometimes were finalized
  916. too early. *)
  917. PROCEDURE Await*( cond: Condition; slink: LONGINT; obj: ProtectedObject; flags: SET );
  918. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; r, c, t: Process; res: LONGINT;
  919. BEGIN
  920. IF 1 IN flags THEN (* compiler did not generate IF *)
  921. IF cond(slink) THEN
  922. RETURN (* condition already true *)
  923. END
  924. END;
  925. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  926. IF StrongChecks THEN
  927. ASSERT(hdr IS Heaps.ProtRecBlock) (* protected object *)
  928. END;
  929. r := CurrentProcess();
  930. Machine.Acquire(Machine.Objects);
  931. IF hdr.lockedBy = r THEN (* current process holds exclusive lock *)
  932. IF StrongChecks THEN ASSERT(hdr.count = -1) END; (* exclusive locked *)
  933. IF hdr.awaitingCond.head # NIL THEN (* evaluate the waiting conditions *)
  934. (* we are holding the lock, so the queue can not change (to do: except in TerminateThis) *)
  935. c := FindCondition(hdr.awaitingCond) (* interrupts should be on during this call *)
  936. ELSE
  937. c := NIL
  938. END;
  939. IF c = NIL THEN
  940. Get(hdr.awaitingLock, t);
  941. IF t = NIL THEN (* none waiting - remove lock *)
  942. hdr.count := 0; hdr.lockedBy := NIL;
  943. ELSE (* transfer lock to first waiting process *)
  944. IF StrongChecks THEN ASSERT(t.mode = AwaitingLock) END;
  945. t.waitingOn := NIL;
  946. hdr.lockedBy := t;
  947. END;
  948. ELSE
  949. c.waitingOn := NIL; hdr.lockedBy := c;
  950. t := NIL;
  951. END;
  952. ELSE (* no lock, or some other process may hold the lock, but that's the user's indaba (may be monotonic condition) *)
  953. Machine.Release(Machine.Objects);
  954. HALT( 2204 ) (* await must be exclusive region *)
  955. END;
  956. r.condition := cond; r.condFP := slink;
  957. r.waitingOn := obj; r.mode := AwaitingCond;
  958. Remove(ready, r);
  959. IF r.event = 0 THEN
  960. r.event := Kernel32.CreateEvent( NIL, Kernel32.False (* auto *), Kernel32.False, NIL ); (* auto-reset event with initial state = reset *)
  961. ASSERT ( r.event # 0, 1239 );
  962. END;
  963. IF c # NIL THEN
  964. DEC(awc); Put(ready, c); c.mode := Running;
  965. res := Kernel32.SetEvent(c.event); (* restart execution *)
  966. ASSERT(res # 0, 1002);
  967. END;
  968. IF t # NIL THEN
  969. DEC(awl); Put(ready, t); t.mode := Running;
  970. res := Kernel32.SetEvent( t.event ); (* restart execution *)
  971. ASSERT(res # 0, 1003);
  972. END;
  973. Put(hdr.awaitingCond, r); INC(awc);
  974. Machine.Release(Machine.Objects);
  975. res := Kernel32.WaitForSingleObject(r.event, Kernel32.Infinite); (* block execution *)
  976. ASSERT(res = Kernel32.WaitObject0);
  977. IF StrongChecks THEN
  978. ASSERT(cond(slink));
  979. ASSERT(hdr.lockedBy = r) (* lock held again *)
  980. END
  981. END Await;
  982. PROCEDURE Break*( t: Process );
  983. CONST MaxTry = 50;
  984. VAR mod: Modules.Module; try: LONGINT; retBOOL: Kernel32.BOOL; (* Dan 09.11.05 *)
  985. PROCEDURE SafeForBreak( mod: Modules.Module ): BOOLEAN;
  986. BEGIN
  987. Trace.String( "Safe for break?: " );
  988. IF mod # NIL THEN
  989. Trace.StringLn ( mod.name );
  990. IF (mod.name = "Trace") OR (mod.name = "Machine") OR
  991. (mod.name = "Heaps") OR (mod.name = "Modules") OR
  992. (mod.name = "Objects") OR (mod.name = "Kernel") THEN
  993. Trace.StringLn ( " - no" ); RETURN FALSE
  994. ELSE Trace.StringLn ( " - yes" ); RETURN TRUE
  995. END
  996. ELSE Trace.StringLn ( "unknown module" ); RETURN FALSE
  997. END
  998. END SafeForBreak;
  999. BEGIN
  1000. IF CurrentProcess() # t THEN
  1001. Machine.Acquire( Machine.Objects );
  1002. LOOP
  1003. retBOOL := Kernel32.SuspendThread( t.handle );
  1004. t.state.ContextFlags := Kernel32.ContextControl;
  1005. retBOOL := Kernel32.GetThreadContext( t.handle, t.state );
  1006. mod := Modules.ThisModuleByAdr( t.state.PC ); Trace.String( "Objects Break at adr: " );
  1007. Trace.Int( t.state.PC, 5 ); Trace.Ln;
  1008. IF mod # NIL THEN
  1009. Trace.String( "In module: " ); Trace.StringLn ( mod.name );
  1010. END;
  1011. IF ~SafeForBreak( mod ) (* we do not break Kernel modules *) THEN
  1012. retBOOL := Kernel32.ResumeThread( t.handle ); INC( try );
  1013. IF try > MaxTry THEN
  1014. Trace.StringLn ( "Threads.Break: failed " );
  1015. Machine.Release( Machine.Objects );
  1016. RETURN
  1017. END
  1018. ELSE EXIT
  1019. END;
  1020. END;
  1021. (* push cont.Eip *) break[0] := 68X;
  1022. SYSTEM.MOVE( ADDRESSOF( t.state.PC ), ADDRESSOF( break[1] ), 4 );
  1023. (* push ebp *) break[5] := 055X;
  1024. (* mov ebp, esp *) break[6] := 08BX; break[7] := 0ECX;
  1025. (* push 13 *) break[8] := 06AX; break[9] := 0DX;
  1026. (* int 3 *) break[10] := 0CCX;
  1027. (* mov esp, ebp *) break[11] := 08BX; break[12] := 0E5X;
  1028. (* pop ebp *) break[13] := 05DX;
  1029. (* ret *) break[14] := 0C3X; t.state.PC := ADDRESSOF( break[0] );
  1030. retBOOL := Kernel32.SetThreadContext( t.handle, t.state );
  1031. retBOOL := Kernel32.ResumeThread( t.handle ); (* INC( Kernel.GClevel ); *)
  1032. Machine.Release( Machine.Objects );
  1033. ELSE HALT( 99 )
  1034. END;
  1035. END Break;
  1036. (* Attempt to terminate a specific process (mostly ignoring its locks). DEPRECATED *)
  1037. PROCEDURE TerminateThis*( t: Process; halt: BOOLEAN );
  1038. BEGIN
  1039. terminate(t);
  1040. END TerminateThis;
  1041. PROCEDURE Terminate*;
  1042. BEGIN
  1043. TerminateProc();
  1044. END Terminate;
  1045. PROCEDURE Init; (* can not use NEW *)
  1046. VAR lock: PROCEDURE(obj: ProtectedObject; exclusive: BOOLEAN);
  1047. unlock: PROCEDURE(obj: ProtectedObject; dummy: BOOLEAN);
  1048. await: PROCEDURE(cond: Condition; slink: LONGINT; obj: ProtectedObject; flags: SET);
  1049. create: PROCEDURE(body: Body; priority: LONGINT; flags: SET; obj: ProtectedObject);
  1050. VAR t: Process; fn: Heaps.FinalizerNode; proc: Kernel32.HANDLE;
  1051. res: Kernel32.BOOL;
  1052. BEGIN
  1053. Kernel32.InitializeCriticalSection(excplock);
  1054. numberOfProcessors := Machine.NumberOfProcessors();
  1055. lock := Lock; unlock := Unlock; await := Await; create := CreateProcess;
  1056. NEW(t); NEW(fn);
  1057. Machine.Acquire(Machine.Objects);
  1058. nProcs := 1;
  1059. t.next := NIL; t.prev := NIL;
  1060. t.waitingOn := NIL; t.flags := {}; t.obj := NIL;
  1061. t.mode := Unknown; t.body := NIL;
  1062. t.priority := Normal;
  1063. fn.finalizer := FinalizeProcess;
  1064. Heaps.AddFinalizer(t, fn);
  1065. t.handle := Kernel32.GetCurrentThread();
  1066. t.id := Kernel32.GetCurrentThreadId();
  1067. proc := Kernel32.GetCurrentProcess();
  1068. res := Kernel32.DuplicateHandle(proc, t.handle, proc, t.handle, {}, 0, {Kernel32.DuplicateSameAccess});
  1069. ASSERT(res # 0);
  1070. res := Kernel32.TlsSetValue(tlsIndex, SYSTEM.VAL(LONGINT, t));
  1071. ASSERT(res # 0);
  1072. t.stackBottom := StackBottom(); t.mode := Running;
  1073. Put( ready, t );
  1074. ASSERT(t.handle # 0);
  1075. Machine.Release(Machine.Objects);
  1076. InitEventHandling; (* implicit call of NewProcess! *)
  1077. InitGCHandling; (* do. *)
  1078. Heaps.gcStatus := GCStatusFactory()
  1079. END Init;
  1080. (** Set (or reset) an event handler object's timeout value. *)
  1081. PROCEDURE SetTimeout*(t: Timer; h: EventHandler; ms: LONGINT );
  1082. VAR e: Timer; trigger: LONGINT;
  1083. BEGIN
  1084. ASSERT(Machine.Second= 1000); (* assume milliseconds for now *)
  1085. ASSERT((t # NIL) & (h # NIL));
  1086. ASSERT(ms >= 0);
  1087. Machine.Acquire(Machine.Objects);
  1088. trigger := Kernel32.GetTickCount() + ms; (* ignore overflow *)
  1089. IF t.next # NIL THEN (* cancel previous timeout *)
  1090. t.next.prev := t.prev; t.prev.next := t.next
  1091. END;
  1092. t.trigger := trigger; t.handler := h;
  1093. e := event.next; (* performance: linear search! *)
  1094. WHILE (e # event) & (e.trigger - trigger <= 0) DO e := e.next END;
  1095. t.prev := e.prev; e.prev := t; t.next := e; t.prev.next := t;
  1096. Machine.Release(Machine.Objects);
  1097. clock.Wakeup()
  1098. END SetTimeout;
  1099. (** Set (or reset) an event handler object's timeout value. Here ms is absolute *)
  1100. PROCEDURE SetTimeoutAt*(t: Timer; h: EventHandler; ms: LONGINT);
  1101. VAR e: Timer; trigger: LONGINT;
  1102. BEGIN
  1103. ASSERT(Machine.Second= 1000); (* assume milliseconds for now *)
  1104. ASSERT((t # NIL) & (h # NIL));
  1105. Machine.Acquire(Machine.Objects);
  1106. trigger := ms; (* ignore overflow *)
  1107. IF t.next # NIL THEN (* cancel previous timeout *)
  1108. t.next.prev := t.prev; t.prev.next := t.next
  1109. END;
  1110. t.trigger := trigger; t.handler := h;
  1111. e := event.next; (* performance: linear search! *)
  1112. WHILE (e # event) & (e.trigger - trigger <= 0) DO e := e.next END;
  1113. t.prev := e.prev; e.prev := t; t.next := e; t.prev.next := t;
  1114. Machine.Release(Machine.Objects);
  1115. clock.Wakeup()
  1116. END SetTimeoutAt;
  1117. (** Cancel an event handler object's timeout, if any. It is possible that the timer has expired, but not yet been scheduled to run. *)
  1118. PROCEDURE CancelTimeout*( t: Timer );
  1119. BEGIN
  1120. Machine.Acquire(Machine.Objects);
  1121. ASSERT (t # event );
  1122. IF t.next # NIL THEN
  1123. t.next.prev := t.prev; t.prev.next := t.next; t.next := NIL;
  1124. t.prev := NIL
  1125. END;
  1126. Machine.Release(Machine.Objects);
  1127. END CancelTimeout;
  1128. PROCEDURE InitEventHandling;
  1129. BEGIN
  1130. NEW(event); event.next := event; event.prev := event; (* event: head of timer event queue, only a sentinel *)
  1131. NEW(clock)
  1132. END InitEventHandling;
  1133. PROCEDURE InitGCHandling;
  1134. BEGIN
  1135. NEW(gcActivity);
  1136. NEW(finalizerCaller);
  1137. END InitGCHandling;
  1138. PROCEDURE GCStatusFactory(): Heaps.GCStatus;
  1139. VAR gcStatusExt : GCStatusExt;
  1140. BEGIN
  1141. ASSERT(Heaps.gcStatus = NIL);
  1142. NEW(gcStatusExt);
  1143. RETURN gcStatusExt
  1144. END GCStatusFactory;
  1145. PROCEDURE InstallExceptionHandler*( e: ExceptionHandler );
  1146. BEGIN
  1147. exceptionhandler := e;
  1148. END InstallExceptionHandler;
  1149. PROCEDURE UpdateProcessState*( p: Process );
  1150. VAR res: Kernel32.BOOL;
  1151. BEGIN
  1152. res := Kernel32.GetThreadContext( p.handle, p.state );
  1153. ASSERT (p.handle # 0);
  1154. END UpdateProcessState;
  1155. (*ALEX 2005.12.12 added for WMPerfMon needs*)
  1156. PROCEDURE NumReady*( ): LONGINT;
  1157. VAR n: LONGINT; p: Heaps.ProcessLink;
  1158. BEGIN
  1159. n := 0;
  1160. Machine.Acquire( Machine.Objects );
  1161. p := ready.head;
  1162. WHILE p # NIL DO INC( n ); p := p.next END;
  1163. Machine.Release( Machine.Objects );
  1164. RETURN n
  1165. END NumReady;
  1166. (** Return number of CPU cycles consumed by the specified process. If all is TRUE,
  1167. return the number of cycles since the process has been created. If FALSE, return the number of cycles
  1168. consumed since the last time asked. *)
  1169. PROCEDURE GetCpuCycles*(process : Process; VAR cpuCycles : CpuCyclesArray; all : BOOLEAN);
  1170. VAR res : Kernel32.BOOL; temp : HUGEINT; i : LONGINT;
  1171. BEGIN
  1172. ASSERT(process # NIL);
  1173. IF (Kernel32.QueryThreadCycleTime # NIL) THEN
  1174. res := Kernel32.QueryThreadCycleTime(process.handle, cpuCycles[0]);
  1175. ELSE
  1176. cpuCycles[0] := Machine.GetTimer(); res := Kernel32.True;
  1177. END;
  1178. IF ~all & (res = Kernel32.True) THEN
  1179. temp := process.lastThreadTimes;
  1180. process.lastThreadTimes := cpuCycles[0];
  1181. cpuCycles[0] := cpuCycles[0] - temp;
  1182. END;
  1183. END GetCpuCycles;
  1184. PROCEDURE CurrentProcessTime*(): HUGEINT;
  1185. VAR res: LONGINT; result: HUGEINT;
  1186. BEGIN
  1187. res := Kernel32.QueryThreadCycleTime(CurrentProcess().handle, result);
  1188. RETURN result;
  1189. END CurrentProcessTime;
  1190. PROCEDURE TimerFrequency*(): HUGEINT;
  1191. BEGIN
  1192. RETURN 1000000000;
  1193. END TimerFrequency;
  1194. BEGIN
  1195. exceptionhandler := NIL;
  1196. terminateProc := TerminateProc;
  1197. ready.head := NIL; ready.tail := NIL;
  1198. tlsIndex := Kernel32.TlsAlloc();
  1199. ASSERT ( tlsIndex # Kernel32.TLSOutOfIndexes );
  1200. Kernel32.SendToDebugger("Modules.root", ADDRESSOF(Modules.root));
  1201. Init
  1202. END Objects.
  1203. (*
  1204. 24.03.1998 pjm Started
  1205. 06.05.1998 pjm CreateProcess init process, page fault handler
  1206. 06.08.1998 pjm Moved exception interrupt handling here for current process
  1207. 17.08.1998 pjm FindRoots method
  1208. 02.10.1998 pjm Idle process
  1209. 06.11.1998 pjm snapshot
  1210. 25.03.1999 pjm Scope removed
  1211. 28.05.1999 pjm EventHandler object
  1212. 01.06.1999 pjm Fixed InterruptProcess lock error
  1213. 16.06.1999 pjm Flat IRQ priority model to avoid GC deadlock
  1214. 23.06.1999 pjm Flat IRQ priority experiment failed, rather do STI in FieldIRQ to avoid GC deadlock
  1215. 29.06.1999 pjm Timeout in EventHandler object
  1216. 13.01.2000 pjm Overed (Interrupt Objects, Event Handlers, Process ID, Process state, Process mode, Process stack, Await)
  1217. 17.10.2000 pjm Priorities
  1218. 22.10.2003 mib SSE2 extension
  1219. 24.10.2003 phk Priority inversion / cycle counters
  1220. Stack invariant for GC:
  1221. o if process is running, the processor registers contain its state
  1222. o if process is not running, at least state.ESP is valid, and between stack.adr and stack.high (for GC)
  1223. o when releasing the Ready lock, make sure the process state is up to date
  1224. *)
  1225. SystemTools.ShowStacks ~
  1226. Heaps.SetMetaData
  1227. StaticLinker.Link --fileFormat=PE32 --fileName=A2GC.exe --extension=GofW --displacement=401000H Runtime Trace Kernel32 Machine Heaps Modules Objects Kernel KernelLog Streams Commands FIles WinFS Clock Dates Reals Strings Diagnostics BitSets StringPool ObjectFile GenericLinker Reflection GenericLoader BootConsole ~