Win32.Objects.Mod 46 KB

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