Win32.Objects.Mod 46 KB

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