Win64.Objects.Mod 47 KB

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