Win32.Objects.Mod 43 KB

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