Windows.AMD64.Objects.Mod 46 KB

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