Win32.Objects.Mod 45 KB

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