Win32.Objects.Mod 45 KB

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