Win64.Objects.Mod 47 KB

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