Windows.I386.Objects.Mod 46 KB

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