Win32.Objects.Mod 43 KB

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