Win32.Objects.Mod 44 KB

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