Win64.Objects.Mod 45 KB

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