Win32.Objects.Mod 45 KB

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