Windows.Objects.Mod 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  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. (*#IF SHAREDLIB THEN*)
  19. External = 13; (* external (non A2) process attached in case of a DLL *)
  20. (*#END;*)
  21. InActive* = 26; (* needed to prevent processes to call finalizers while in await or lock or unlock, see Kernel.GC *)
  22. (** Process modes *)
  23. Unknown* = 0; Ready* = 1; (* for compatibility with native A2 *)
  24. Running* = 2; AwaitingLock* = 3; AwaitingCond* = 4; AwaitingEvent* = 5; Suspended* = 6; Terminated* = 7;
  25. (** Process priorities *)
  26. MinPriority = 0; (* only system idle processes run at this priority level *)
  27. Low* = 1; Normal* = 2; High* = 3; (* "user" priorities *)
  28. GCPriority* = 4; (* priority of garbage collector *)
  29. Realtime* = 5; (* reserved for interrupt handling and realtime apps, these processes are not allowed to allocate memory *)
  30. (* Process termination halt codes *)
  31. halt* = 2222;
  32. haltUnbreakable* = 2223;
  33. TYPE
  34. CpuCyclesArray* = ARRAY Machine.MaxCPU OF HUGEINT;
  35. ProtectedObject = POINTER TO RECORD END; (* protected object (10000) *)
  36. ProcessQueue = Heaps.ProcessQueue;
  37. Body = PROCEDURE (self: ProtectedObject);
  38. Condition = PROCEDURE (slink: ADDRESS): BOOLEAN;
  39. EventHandler* = PROCEDURE {DELEGATE};
  40. RealtimeEventHandler* = PROCEDURE {DELEGATE, REALTIME};
  41. Timer* = POINTER TO RECORD
  42. next, prev : Timer;
  43. trigger: LONGINT;
  44. handler: EventHandler
  45. END;
  46. RealtimeTimer* = POINTER TO RECORD
  47. next, prev: RealtimeTimer;
  48. trigger: LONGINT;
  49. handler: RealtimeEventHandler
  50. END;
  51. Clock = OBJECT
  52. VAR h: Timer;
  53. ticks: LONGINT;
  54. hevent: Kernel32.HANDLE;
  55. res: Kernel32.BOOL;
  56. mode: LONGINT;
  57. process: Process;
  58. exiting: BOOLEAN;
  59. PROCEDURE Wakeup;
  60. VAR res: Kernel32.BOOL;
  61. BEGIN {EXCLUSIVE}
  62. res := Kernel32.SetEvent(hevent)
  63. END Wakeup;
  64. PROCEDURE Exit;
  65. BEGIN
  66. exiting := TRUE;
  67. Wakeup;
  68. END Exit;
  69. PROCEDURE Finalize(ptr: ANY);
  70. BEGIN
  71. Exit;
  72. END Finalize;
  73. PROCEDURE &Init*;
  74. VAR fn: Heaps.FinalizerNode;
  75. BEGIN
  76. hevent := Kernel32.CreateEvent(NIL, 0, 0, NIL);
  77. ASSERT(hevent # 0);
  78. NEW(fn); fn.finalizer := SELF.Finalize; Heaps.AddFinalizer(SELF, fn)
  79. END Init;
  80. BEGIN {ACTIVE, SAFE, PRIORITY(High)}
  81. process := CurrentProcess();
  82. mode := process.mode;
  83. LOOP
  84. Machine.Acquire(Machine.Objects);
  85. process.mode := mode;
  86. LOOP
  87. h := event.next; (* event: head of timer event queue *)
  88. ticks := Kernel32.GetTickCount();
  89. IF (h = event) OR (h.trigger - ticks > 0) THEN EXIT END;
  90. event.next := h.next; event.next.prev := event; (* unlink *)
  91. h.next := NIL; h.prev := NIL;
  92. Machine.Release(Machine.Objects);
  93. h.handler(); (* assume handler will return promptly *)
  94. Machine.Acquire(Machine.Objects)
  95. END;
  96. mode := process.mode;
  97. process.mode := AwaitingEvent;
  98. Machine.Release(Machine.Objects);
  99. IF h = event THEN (* sentinel head of timer event queue: wait forever until a new event has been entered in queue *)
  100. res := Kernel32.WaitForSingleObject(hevent, MAX(LONGINT));
  101. ELSE
  102. res := Kernel32.WaitForSingleObject(hevent, h.trigger - ticks);
  103. END;
  104. IF exiting THEN EXIT; END;
  105. END;
  106. process.mode := Running; (*! avoid a trap in terminate *)
  107. IF hevent # 0 THEN res := Kernel32.CloseHandle(hevent); END;
  108. END Clock;
  109. TYPE
  110. Win32Event = Kernel32.HANDLE;
  111. GCContext = RECORD
  112. nextPos: SIZE; (* 0 to start with *)
  113. (*first,*) last: ARRAY 256 OF ADDRESS; (* first might be not required *)
  114. END;
  115. Process* = OBJECT(Heaps.ProcessLink)
  116. VAR
  117. rootedNext : Process; (* to prevent process to be GCed in WinAos *)
  118. obj-: ProtectedObject; (* associated active object *)
  119. state- {ALIGNED=16}: Kernel32.Context;
  120. condition-: Condition; (* awaited process' condition *)
  121. condFP-: ADDRESS; (* awaited process' condition's context *)
  122. mode-: LONGINT; (* process state *) (* only changed inside Objects lock ??? *)
  123. procID-: LONGINT; (* processor ID where running, exported for compatibilty , useless in WinAos *)
  124. waitingOn-: ProtectedObject; (* obj this process is waiting on (for lock or condition) *)
  125. id-: LONGINT; (* unique process ID for tracing *)
  126. flags*: SET; (* process flags *)
  127. priority-: LONGINT; (* process priority *)
  128. stackBottom: ADDRESS;
  129. handle-: Kernel32.HANDLE; (* handle to corresponding Windows thread *)
  130. body: Body;
  131. event: Win32Event;
  132. restartPC-: ADDRESS; (** entry point of body, for SAFE exception recovery *)
  133. restartSP-: ADDRESS; (** stack level at start of body, for SAFE exception recovery *)
  134. lastThreadTimes: HUGEINT; (*ALEX 2005.12.12*)
  135. gcContext: GCContext;
  136. context: ANY; (* commands contect *)
  137. PROCEDURE FindRoots; (* override, called while GC, replaces Threads.CheckStacks *)
  138. VAR sp: ADDRESS; res: Kernel32.BOOL; pc, bp: ADDRESS;
  139. n,adr: ADDRESS; desc {UNTRACED}: Modules.ProcedureDescPointer; p {UNTRACED}: ANY; i: SIZE;
  140. a0,a1, obp, osb, osbp, opc, gbp: ADDRESS;
  141. O: ANY; ID: LONGINT;
  142. mod {UNTRACED}: Modules.Module;
  143. proc {UNTRACED}: Modules.ProcedureDescPointer;
  144. modName: ARRAY 128 OF CHAR;
  145. contextPos: SIZE;
  146. BEGIN{UNCHECKED} (* avoid winapi call indirection *)
  147. O := obj; ID := id;
  148. IF (handle = 0) OR (mode = Terminated) OR (mode < Ready) (* procedure Wrapper not yet started *)
  149. OR (priority > High) (* stack of GC and realtime processes not traced *) THEN
  150. RETURN
  151. END;
  152. IF CurrentProcess() = SELF THEN
  153. sp := SYSTEM.GetStackPointer(); bp :=SYSTEM.GetFramePointer(); pc := Machine.CurrentPC();
  154. ELSE
  155. (*! this should never happen or must be changed with mode change eetc.
  156. res := Kernel32.SuspendThread(handle); (* can suspend a suspended thread -- no problem at all *)
  157. *)
  158. state.ContextFlags := Kernel32.ContextControl + Kernel32.ContextInteger;
  159. res := Kernel32.GetThreadContext( handle, state );
  160. IF res = 0 THEN Trace.String("could not get thread context:"); Trace.Int(Kernel32.GetLastError(),1) END;
  161. sp := state.SP; bp := state.BP; pc := state.PC;
  162. mod := Modules.ThisModuleByAdr0(pc);
  163. IF mod # NIL THEN
  164. COPY(mod.name, modName);
  165. proc := Modules.FindProc(pc,mod.procTable);
  166. END;
  167. obp := bp; osb := stackBottom; opc := pc;
  168. osbp := state.BP;
  169. END;
  170. IF TraceProcessHook # NIL THEN
  171. TraceProcessHook(SELF,pc,bp,sp,stackBottom);
  172. END;
  173. contextPos := gcContext.nextPos;
  174. IF contextPos < 0 THEN RETURN END; (* this thread is currently not active in A2 *)
  175. (* stack garbage collection *)
  176. IF Heaps.GCType= Heaps.HeuristicStackInspectionGC THEN
  177. #IF I386 THEN
  178. Heaps.Candidate( state.RDI ); Heaps.Candidate( state.RSI );
  179. Heaps.Candidate( state.RB ); Heaps.Candidate( state.RD );
  180. Heaps.Candidate( state.RC ); Heaps.Candidate( state.RA );
  181. #ELSIF AMD64 THEN
  182. Heaps.Candidate( state.RDI ); Heaps.Candidate( state.RSI );
  183. Heaps.Candidate( state.RB ); Heaps.Candidate( state.RD );
  184. Heaps.Candidate( state.RC ); Heaps.Candidate( state.RA );
  185. Heaps.Candidate( state.R9 ); Heaps.Candidate( state.R10 );
  186. Heaps.Candidate( state.R11 ); Heaps.Candidate( state.R12 );
  187. Heaps.Candidate( state.R13 ); Heaps.Candidate( state.R14 );
  188. Heaps.Candidate( state.R15 );
  189. #ELSE
  190. ASSERT(FALSE);
  191. #END
  192. IF (stackBottom # 0) & (sp # 0) THEN
  193. Heaps.RegisterCandidates( sp, stackBottom - sp );
  194. END;
  195. ELSIF Heaps.GCType = Heaps.MetaDataForStackGC THEN
  196. IF TraceVerbose THEN
  197. Trace.String("GC, process id = "); Trace.Int(id,1); Trace.Ln;
  198. END;
  199. LOOP
  200. IF (bp = NIL) OR (bp >= stackBottom) THEN EXIT END;
  201. IF Machine.ValidHeapAddress(pc) THEN
  202. (* ok, valid stack frame from A2, we can trace this *)
  203. ELSE
  204. (* no, cannot trace this Windows stack frame, we have to check if we recorded when we exited A2 previously *)
  205. bp := NIL;
  206. WHILE (contextPos > 0) & (bp = NIL) DO
  207. DEC(contextPos);
  208. bp := gcContext.last[contextPos];
  209. END;
  210. IF bp = NIL THEN
  211. EXIT;
  212. END;
  213. END;
  214. SYSTEM.GET(bp, n);
  215. IF ODD(n) THEN (* procedure descriptor at bp *)
  216. desc := SYSTEM.VAL(Modules.ProcedureDescPointer, n-1);
  217. IF desc # NIL THEN
  218. IF TraceVerbose THEN
  219. WriteType(desc); Trace.Ln;
  220. END;
  221. a0 := ADDRESSOF(desc.offsets);
  222. a1 := SYSTEM.VAL(ADDRESS, desc.offsets);
  223. ASSERT(a0+SIZEOF(ADDRESS)=a1,54321);
  224. FOR i := 0 TO LEN(desc.offsets)-1 DO
  225. adr := bp + desc.offsets[i]; (* pointer at offset *)
  226. SYSTEM.GET(adr, p); (* load pointer *)
  227. IF p # NIL THEN
  228. Heaps.Mark(p);
  229. END;
  230. END;
  231. END;
  232. SYSTEM.GET(bp + 2*SIZEOF(ADDRESS), pc);
  233. SYSTEM.GET(bp + SIZEOF(ADDRESS), bp);
  234. ELSE (* classical stack frame without procedure descriptor *)
  235. SYSTEM.GET(bp + SIZEOF(ADDRESS), pc);
  236. bp := n;
  237. END;
  238. END;
  239. (* ASSERT((bp = stackBottom) OR (bp=0) ,12345); can be violated when coming from windows *)
  240. END;
  241. IF (CurrentProcess() # SELF) (* & (mode # Suspended) *) THEN
  242. res := Kernel32.ResumeThread(handle);
  243. ASSERT(res # -1);
  244. END;
  245. END FindRoots;
  246. END Process;
  247. TYPE
  248. ExceptionHandler* = PROCEDURE( VAR context: Kernel32.Context;
  249. VAR excpRec: Kernel32.ExceptionRecord;
  250. VAR handled: BOOLEAN);
  251. GCStatusExt = OBJECT(Heaps.GCStatus)
  252. (* called from Heaps.InvokeGC, i.e. this is a hidden upcall. However, it is necessary to take the Machine.Objects lock here since writing
  253. 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
  254. if the lock is not taken. *)
  255. PROCEDURE SetgcOngoing(value: BOOLEAN);
  256. VAR p: Heaps.ProcessLink; cur, r: Process; res: Kernel32.BOOL; num: LONGINT; time: LONGINT;
  257. BEGIN (* serialize writers *)
  258. IF value THEN
  259. (* Low, Medium or High priority process calls this *)
  260. time := Kernel32.GetTickCount();
  261. Machine.Acquire(Machine.Objects);
  262. Machine.Acquire(Machine.Heaps); (* to protect agains concurrent LazySweep *)
  263. r := CurrentProcess();
  264. num := 0;
  265. p := ready.head;
  266. WHILE p # NIL DO
  267. cur := p(Process);
  268. IF ((cur.mode = Ready) OR (cur.mode = Running)) & (cur.priority <= High) & (cur # r) & (cur.gcContext.nextPos >= 0) THEN
  269. res := Kernel32.SuspendThread(cur.handle);
  270. ASSERT(res >= 0);
  271. cur.mode := Suspended
  272. ELSE INC(num);
  273. END;
  274. p := p.next
  275. END;
  276. Heaps.CollectGarbage(Modules.root);
  277. p := ready.head;
  278. WHILE (p # NIL) DO
  279. cur := p(Process);
  280. (* only suspended and awaiting processes of ready queue are resumed *)
  281. IF cur.mode = Suspended THEN
  282. res := Kernel32.ResumeThread(cur.handle);
  283. ASSERT(res >= 0);
  284. cur.mode := Running
  285. END;
  286. p := p.next
  287. END;
  288. Machine.Release(Machine.Heaps);
  289. Machine.Release(Machine.Objects);
  290. time := Kernel32.GetTickCount()-time;
  291. IF Heaps.trace THEN Trace.String("GC Called -- duration "); Trace.Int(time,0); Trace.String(" ms."); Trace.Ln END;
  292. IF finalizerCaller # NIL THEN finalizerCaller.Activate() END;
  293. END;
  294. END SetgcOngoing;
  295. END GCStatusExt;
  296. FinalizerCaller = OBJECT (* separate active object that calls finalizers *)
  297. VAR n: Heaps.FinalizerNode;
  298. event: Kernel32.HANDLE;
  299. process: Process;
  300. exiting: BOOLEAN;
  301. PROCEDURE &Init;
  302. BEGIN
  303. event := Kernel32.CreateEvent( NIL, Kernel32.False (* automatic *), Kernel32.False, NIL );
  304. ASSERT(event # 0);
  305. END Init;
  306. PROCEDURE Wait(): BOOLEAN;
  307. VAR res: Kernel32.BOOL; mode: LONGINT;
  308. BEGIN
  309. mode := process.mode;
  310. process.mode := AwaitingEvent;
  311. res := Kernel32.WaitForSingleObject(event, Kernel32.Infinite);
  312. process.mode := mode;
  313. ASSERT(res = Kernel32.WaitObject0);
  314. IF ~exiting THEN
  315. RETURN TRUE;
  316. ELSE
  317. RETURN FALSE;
  318. END;
  319. END Wait;
  320. PROCEDURE Activate;
  321. VAR res: Kernel32.BOOL;
  322. BEGIN
  323. res := Kernel32.SetEvent(event);
  324. END Activate;
  325. PROCEDURE Exit;
  326. BEGIN
  327. exiting := TRUE;
  328. Activate;
  329. END Exit;
  330. BEGIN {ACTIVE, SAFE, PRIORITY(High)}
  331. process := CurrentProcess();
  332. WHILE Wait() DO
  333. LOOP
  334. n := Heaps.GetFinalizer();
  335. IF n = NIL THEN EXIT END;
  336. IF n.collection # NIL THEN
  337. n.collection.RemoveAll(n.objStrong) (* remove it if it is not removed yet *)
  338. END;
  339. IF n.finalizer # NIL THEN
  340. n.finalizer( n.objStrong ) (* may acquire locks *)
  341. END
  342. END;
  343. END;
  344. IF event # 0 THEN IGNORE Kernel32.CloseHandle(event); END;
  345. END FinalizerCaller;
  346. VAR
  347. awc-, awl-: LONGINT;
  348. oberonLoop*: ANY; (* Oberon Loop Process temporary workaround for Threads.oberonLoop *)
  349. break: ARRAY 16 OF CHAR;
  350. terminateProc: PROCEDURE;
  351. ready: ProcessQueue; (* contains running processes in this implementation *)
  352. numberOfProcessors: LONGINT; (* cached value of Machine.NumberOfProcessors() *)
  353. finalizerCaller: FinalizerCaller; (* active object for finalizer process, regarded as aprt of GC *)
  354. event: Timer; (* list of events *)
  355. clock: Clock;
  356. tlsIndex: LONGINT;
  357. nProcs: LONGINT;
  358. excplock: Kernel32.CriticalSection; exceptionhandler: ExceptionHandler;
  359. (* Set the current process' priority. *)
  360. PROCEDURE SetPriority*( priority: LONGINT );
  361. VAR r: Process; prio: LONGINT; res: Kernel32.BOOL;
  362. BEGIN
  363. ASSERT((priority >= Low) & (priority <= Realtime)); (* priority in bounds *)
  364. r := CurrentProcess(); r.priority := priority;
  365. CASE priority OF
  366. MinPriority:
  367. prio := Kernel32.ThreadPriorityIdle
  368. | Low:
  369. prio := Kernel32.ThreadPriorityBelowNormal
  370. | High:
  371. prio := Kernel32.ThreadPriorityAboveNormal
  372. | GCPriority, Realtime:
  373. prio := Kernel32.ThreadPriorityTimeCritical
  374. ELSE (* Normal *)
  375. prio := Kernel32.ThreadPriorityNormal
  376. END;
  377. res := Kernel32.SetThreadPriority( r.handle, prio );
  378. ASSERT(r.handle # 0);
  379. ASSERT(res # 0)
  380. END SetPriority;
  381. (** Return TRUE iff the specified protected object is locked exclusive to the current process. *)
  382. PROCEDURE LockedByCurrent*( obj: ANY ): BOOLEAN;
  383. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; res: BOOLEAN;
  384. BEGIN
  385. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  386. ASSERT(hdr IS Heaps.ProtRecBlock);
  387. Machine.Acquire(Machine.Objects);
  388. res := (hdr.lockedBy = ActiveObject());
  389. Machine.Release(Machine.Objects);
  390. RETURN res
  391. END LockedByCurrent;
  392. PROCEDURE Yield*;
  393. BEGIN
  394. Kernel32.Sleep(0)
  395. END Yield;
  396. (** Return current process. (DEPRECATED, use ActiveObject) *)
  397. PROCEDURE CurrentProcess*( ): Process;
  398. BEGIN{UNCHECKED} (* makes sure that Enter and Leave are not emitted *)
  399. RETURN SYSTEM.VAL(Process, Kernel32.TlsGetValue(tlsIndex));
  400. END CurrentProcess;
  401. PROCEDURE CurrentContext*(): ANY;
  402. VAR p: Process;
  403. BEGIN
  404. p := CurrentProcess();
  405. IF p # NIL THEN RETURN p.context
  406. ELSE RETURN NIL
  407. END;
  408. END CurrentContext;
  409. PROCEDURE SetContext*(context: ANY);
  410. VAR p: Process;
  411. BEGIN
  412. p := CurrentProcess();
  413. IF p # NIL THEN p.context := context END;
  414. END SetContext;
  415. (* Return stack bottom of process. For compatibility WinAos/UnixAos/NativeAos *)
  416. PROCEDURE GetStackBottom*(p: Process): ADDRESS;
  417. BEGIN
  418. RETURN p.stackBottom
  419. END GetStackBottom;
  420. (** Return the active object currently executing. *)
  421. PROCEDURE ActiveObject* (): ANY;
  422. VAR r: Process;
  423. BEGIN
  424. r := SYSTEM.VAL(Process, Kernel32.TlsGetValue(tlsIndex));
  425. RETURN r.obj
  426. END ActiveObject;
  427. (** Return the ID of the active currently executing process. *)
  428. PROCEDURE GetProcessID* (): LONGINT;
  429. VAR r: Process;
  430. BEGIN
  431. r := SYSTEM.VAL (Process, Kernel32.TlsGetValue( tlsIndex ));
  432. RETURN r.id
  433. END GetProcessID;
  434. (* Get a process from a queue (NIL if none). Caller must hold lock for specific queue. *)
  435. PROCEDURE Get(VAR queue: ProcessQueue; VAR new: Process);
  436. VAR t: Heaps.ProcessLink;
  437. BEGIN
  438. t := queue.head;
  439. IF t = NIL THEN (* zero elements in queue *)
  440. (* skip *)
  441. ELSIF t = queue.tail THEN (* one element in queue *)
  442. queue.head := NIL; queue.tail := NIL (* {(t.next = NIL) & (t.prev = NIL)} *)
  443. ELSE (* more than one element in queue *)
  444. queue.head := t.next; t.next := NIL; queue.head.prev := NIL
  445. END;
  446. ASSERT((t = NIL) OR (t.next = NIL ) & (t.prev = NIL)); (* temp strong check *)
  447. IF t = NIL THEN
  448. new := NIL
  449. ELSE
  450. ASSERT(t IS Process);
  451. new := t(Process)
  452. END
  453. END Get;
  454. (* Put a process in a queue. Caller must hold lock for specific queue. *)
  455. (* If t was running, be careful to protect Put and the subsequent SwitchTo with the ready lock. *)
  456. PROCEDURE Put(VAR queue: ProcessQueue; t: Process);
  457. BEGIN (* {t # NIL & t.next = NIL & t.prev = NIL} *)
  458. IF StrongChecks THEN
  459. ASSERT((t.next = NIL) & (t.prev = NIL))
  460. END;
  461. t.next := NIL; t.prev := NIL; (* ug *)
  462. IF queue.head = NIL THEN (* queue empty *)
  463. queue.head := t
  464. ELSE (* queue not empty *)
  465. queue.tail.next := t; t.prev := queue.tail
  466. END;
  467. queue.tail := t
  468. END Put;
  469. PROCEDURE {WINAPI} ExcpFrmHandler( CONST exceptionPointers: Kernel32.ExceptionPointers): Kernel32.DWORD ;
  470. VAR m: Modules.Module; eip, ebp, stack: ADDRESS; pc, handler, fp, sp: ADDRESS; handled: BOOLEAN; t: Process;
  471. BEGIN
  472. handled := FALSE;
  473. Kernel32.EnterCriticalSection( excplock );
  474. (*
  475. fof: commenting this resolved a problem with multiple traps that a are catched with FINALLY statements in Windows Vista
  476. in Windows XP not necessary if Kernel32.SetThreadContext is not used (better to return gracefully from this handler)
  477. SetCurrent(excpFrame);
  478. *)
  479. t := CurrentProcess();
  480. IF exceptionhandler = NIL THEN
  481. Trace.StringLn ( "Objects: No exception handler installed" );
  482. IF HandleExcp THEN
  483. Trace.String( "EXCEPTION " ); Trace.Address(exceptionPointers.exception.ExceptionCode);
  484. Trace.String( " at " ); Trace.Address(exceptionPointers.exception.ExceptionAddress);
  485. #IF I386 THEN
  486. Trace.Ln(); Trace.String( "EAX " ); Trace.Hex( exceptionPointers.context.RA, 1 );
  487. Trace.String( " EBX " ); Trace.Hex( exceptionPointers.context.RB, 1 ); Trace.Ln();
  488. Trace.String( "ECX " ); Trace.Hex( exceptionPointers.context.RC, 1 ); Trace.String( " EDX " );
  489. Trace.Hex( exceptionPointers.context.RD, 1 ); Trace.Ln(); Trace.String( "EDI " );
  490. Trace.Hex( exceptionPointers.context.RDI, 1 ); Trace.String( " ESI " );
  491. Trace.Hex( exceptionPointers.context.RSI, 1 ); Trace.Ln();
  492. #ELSIF AMD64 THEN
  493. Trace.Ln(); Trace.String( "RAX " ); Trace.Address(exceptionPointers.context.RA);
  494. Trace.String( " RBX " ); Trace.Address(exceptionPointers.context.RB); Trace.Ln();
  495. Trace.String( "RCX " ); Trace.Address(exceptionPointers.context.RC); Trace.String( " RDX " );
  496. Trace.Address(exceptionPointers.context.RD); Trace.Ln(); Trace.String( "RDI " );
  497. Trace.Address(exceptionPointers.context.RDI); Trace.String( " RSI " );
  498. Trace.Address(exceptionPointers.context.RSI); Trace.Ln();
  499. Trace.String( "R8 " ); Trace.Address(exceptionPointers.context.R8);
  500. Trace.String( " R9 " ); Trace.Address(exceptionPointers.context.R9); Trace.Ln();
  501. Trace.String( "R10 " ); Trace.Address(exceptionPointers.context.R10);
  502. Trace.String( " R11 " ); Trace.Address(exceptionPointers.context.R11); Trace.Ln();
  503. Trace.String( "R12 " ); Trace.Address(exceptionPointers.context.R12);
  504. Trace.String( " R13 " ); Trace.Address(exceptionPointers.context.R13); Trace.Ln();
  505. Trace.String( "R14 " ); Trace.Address(exceptionPointers.context.R14);
  506. Trace.String( " R15 " ); Trace.Address(exceptionPointers.context.R15); Trace.Ln();
  507. Trace.Ln;
  508. #ELSE
  509. -- UNIMPLEMENTED --
  510. #END
  511. Trace.String( "BP " );
  512. Trace.Address(exceptionPointers.context.BP); Trace.String( " SP " );
  513. Trace.Address(exceptionPointers.context.SP); Trace.Ln(); Trace.String( "PC " );
  514. Trace.Address(exceptionPointers.context.PC); Trace.Ln();
  515. Trace.Ln();
  516. eip := exceptionPointers.exception.ExceptionAddress; ebp := exceptionPointers.context.BP;
  517. IF eip = 0 THEN SYSTEM.GET( exceptionPointers.context.SP, eip ) END;
  518. stack := t.stackBottom;
  519. LOOP
  520. Trace.String( "at ebp= " ); Trace.Address(ebp); Trace.String( "H : " );
  521. m := Modules.ThisModuleByAdr( eip );
  522. IF m # NIL THEN
  523. Trace.String( m.name ); Trace.String( " " );
  524. Trace.Address(eip - SYSTEM.VAL( LONGINT, ADDRESSOF( m.code[0] ) ));
  525. ELSE Trace.String( "EIP " ); Trace.Address(eip)
  526. END;
  527. Trace.Ln();
  528. IF (ebp # 0) & (ebp < stack) THEN (* if ebp is 0 in first frame *)
  529. SYSTEM.GET( ebp + SIZEOF(ADDRESS), eip ); (* return addr from stack *)
  530. SYSTEM.GET( ebp, ebp ); (* follow dynamic link *)
  531. ELSE EXIT
  532. END
  533. END;
  534. Trace.Ln();
  535. handled := FALSE; fp := exceptionPointers.context.BP; sp := exceptionPointers.context.SP;
  536. pc := exceptionPointers.context.PC; handler := Modules.GetExceptionHandler( pc );
  537. IF handler # -1 THEN (* Handler in the current PAF *)
  538. exceptionPointers.context.PC := handler; handled := TRUE;
  539. (*SetTrapVariable(pc, fp); SetLastExceptionState(exc)*)
  540. ELSE
  541. WHILE (fp # 0) & (handler = -1) DO
  542. SYSTEM.GET( fp + SIZEOF(ADDRESS), pc );
  543. pc := pc - 1; (* CALL instruction, machine dependant!!! *)
  544. handler := Modules.GetExceptionHandler( pc );
  545. sp := fp; (* Save the old framepointer into the stack pointer *)
  546. SYSTEM.GET( fp, fp ) (* Unwind PAF *)
  547. END;
  548. IF handler = -1 THEN handled := FALSE;
  549. ELSE
  550. exceptionPointers.context.PC := handler; exceptionPointers.context.BP := fp; exceptionPointers.context.SP := sp;
  551. (* SetTrapVariable(pc, fp); SetLastExceptionState(exc);*)
  552. handled := TRUE
  553. END
  554. END;
  555. ELSE Trace.StringLn ( "Warning: FINALLY statement cannot be treated !" );
  556. END
  557. ELSE exceptionhandler(exceptionPointers.context^, exceptionPointers.exception^,handled );
  558. END;
  559. IF ~handled THEN
  560. exceptionPointers.context.PC := t.restartPC ;
  561. exceptionPointers.context.SP := t.restartSP;
  562. exceptionPointers.context.BP := t.stackBottom;
  563. ELSIF TraceVerbose THEN Trace.StringLn ( "trying to jump to FINALLY pc..." );
  564. END;
  565. Kernel32.LeaveCriticalSection( excplock );
  566. IF TraceVerbose THEN
  567. Machine.Acquire (Machine.TraceOutput);
  568. Trace.String( "recover process; pc=" ); Trace.Address( exceptionPointers.context.PC );
  569. Trace.String( "; sp= " ); Trace.Address( exceptionPointers.context.SP); Trace.String( "; bp= " );
  570. Trace.Address( exceptionPointers.context.BP); Trace.Ln;
  571. Machine.Release (Machine.TraceOutput);
  572. END;
  573. RETURN Kernel32.ExceptionContinueExecution; (* sets thread context and continues where specified in context *)
  574. END ExcpFrmHandler;
  575. PROCEDURE RemoveExcpFrm( VAR excpfrm: Kernel32.ExcpFrm );
  576. VAR this: Kernel32.ExcpFrmPtr;
  577. BEGIN
  578. IGNORE Kernel32.RemoveVectoredContinueHandler(ExcpFrmHandler);
  579. END RemoveExcpFrm;
  580. PROCEDURE InstallExcpFrm( VAR excpfrm: Kernel32.ExcpFrm );
  581. BEGIN
  582. Kernel32.AddVectoredContinueHandler(1, ExcpFrmHandler);
  583. END InstallExcpFrm;
  584. PROCEDURE InQueue( queue: ProcessQueue; t: Process ): BOOLEAN;
  585. VAR p: Heaps.ProcessLink;
  586. BEGIN
  587. p := queue.head;
  588. WHILE (p # NIL ) & (p # t) DO p := p.next; END;
  589. RETURN (p = t);
  590. END InQueue;
  591. (* Remove a process from a queue that contains it. Caller must hold lock for specific queue. *)
  592. (* Not intended for frequent use. *)
  593. (* does not check if queue contained t ! *)
  594. PROCEDURE Remove( VAR queue: ProcessQueue; t: Process );
  595. BEGIN
  596. IF StrongChecks THEN
  597. ASSERT(InQueue(queue, t));
  598. ASSERT(t # NIL);
  599. END;
  600. IF t.prev # NIL THEN t.prev.next := t.next END;
  601. IF t.next # NIL THEN t.next.prev := t.prev END;
  602. IF t = queue.head THEN queue.head := t.next END;
  603. IF t = queue.tail THEN queue.tail := t.prev END;
  604. ASSERT((queue.head = NIL) OR (queue.head.prev = NIL) & (queue.tail.next = NIL));
  605. t.prev := NIL; t.next := NIL
  606. END Remove;
  607. PROCEDURE WriteType(obj: ANY);
  608. VAR type: LONGINT;
  609. BEGIN
  610. IF obj = NIL THEN Trace.String(" > NIL");
  611. ELSE
  612. Trace.String(" > "); SYSTEM.GET(SYSTEM.VAL(LONGINT, obj) + Heaps.TypeDescOffset, type);
  613. Heaps.WriteType(type);
  614. END;
  615. END WriteType;
  616. PROCEDURE terminate( t: Process );
  617. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; res: Kernel32.BOOL; shutdown: BOOLEAN;
  618. BEGIN
  619. IF t = NIL THEN RETURN END;
  620. (* see Objects.TerminateThis *)
  621. Machine.Acquire( Machine.Objects );
  622. IF TraceVerbose OR TraceOpenClose THEN
  623. Machine.Acquire (Machine.TraceOutput);
  624. Trace.String( "Terminating process " ); Trace.Int( t.id, 1 ); WriteType( t.obj ); Trace.Ln;
  625. Machine.Release (Machine.TraceOutput);
  626. END;
  627. IF (t.mode = Ready) OR (t.mode = Running) THEN Remove( ready, t );
  628. ELSIF t.mode = AwaitingLock THEN
  629. SYSTEM.GET(SYSTEM.VAL(ADDRESS, t.waitingOn) + Heaps.HeapBlockOffset, hdr);
  630. ASSERT(hdr IS Heaps.ProtRecBlock);
  631. Remove( hdr.awaitingLock, t ); Machine.Release( Machine.Objects );
  632. HALT( 97 )
  633. ELSIF t.mode = AwaitingCond THEN
  634. SYSTEM.GET(SYSTEM.VAL(ADDRESS, t.waitingOn) + Heaps.HeapBlockOffset, hdr);
  635. ASSERT(hdr IS Heaps.ProtRecBlock);
  636. Remove( hdr.awaitingCond, t ); Machine.Release( Machine.Objects );
  637. HALT( 98 )
  638. ELSE Machine.Release( Machine.Objects );
  639. HALT( 99 )
  640. END;
  641. t.mode := Terminated; (* a process can also be "terminated" if the queue containing it is garbage collected *)
  642. t.stackBottom := 0; t.state.SP := 0;
  643. t.restartPC := 0;
  644. IF t.event # 0 THEN res := Kernel32.CloseHandle( t.event ); t.event := 0 END;
  645. DEC( nProcs ); shutdown := (nProcs = 0);
  646. Machine.Release( Machine.Objects );
  647. IF shutdown THEN
  648. Trace.StringLn ( " Objects: shutdown" ); Modules.Shutdown( -1 );
  649. Kernel32.ExitProcess( 0 )
  650. END
  651. END terminate;
  652. PROCEDURE {WINAPI} Wrapper( lpParameter: ANY ): LONGINT;
  653. VAR t: Process; obj: ProtectedObject; res: Kernel32.BOOL; bp,sp: ADDRESS;
  654. excpfrm: Kernel32.ExcpFrm;
  655. BEGIN
  656. (* it may happen that the garbage collector runs right here and ignores this procedure.
  657. This is not a problem since lpParameter (being a reference to a process) is protected by the process lists *)
  658. Machine.Acquire(Machine.Objects);
  659. res := Kernel32.TlsSetValue(tlsIndex, SYSTEM.VAL(ADDRESS, lpParameter));
  660. t := lpParameter(Process); obj := t.obj;
  661. ASSERT(res # 0);
  662. SetPriority(t.priority);
  663. bp := SYSTEM.GetFramePointer();
  664. sp := SYSTEM.GetStackPointer();
  665. t.restartSP := sp;
  666. t.stackBottom := bp;
  667. IF t.restartPC = SYSTEM.VAL(ADDRESS, terminateProc) THEN DEC(t.restartSP, SIZEOF(ADDRESS))
  668. ELSE DEC(t.restartSP, 2*SIZEOF(ADDRESS))
  669. END;
  670. IF TraceVerbose THEN
  671. Machine.Acquire(Machine.TraceOutput);
  672. Trace.String("New process; restartPC= "); Trace.Address(t.restartPC);
  673. Trace.String("; stackBottom= ");
  674. Trace.Address(t.stackBottom);
  675. Trace.String("; id= ");
  676. Trace.Int(t.id,0); Trace.Ln;
  677. Machine.Release(Machine.TraceOutput);
  678. END;
  679. t.mode := Running;
  680. (* now gc is enabled for this process stack *)
  681. Machine.Release(Machine.Objects);
  682. (* 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) *)
  683. (*! should not be necessary any more as GC runs immediately and without scheduling decisions
  684. WHILE (gcActivity # NIL) & (gcActivity.process # NIL) & (gcActivity.process.mode = Running) DO END;
  685. *)
  686. t.body(obj);
  687. terminate(t);
  688. RemoveExcpFrm(excpfrm);
  689. RETURN 0
  690. END Wrapper;
  691. PROCEDURE FinalizeProcess(t: ANY);
  692. VAR p: Process; res: Kernel32.BOOL;
  693. BEGIN
  694. p := t(Process);
  695. IF TraceVerbose THEN
  696. Machine.Acquire (Machine.TraceOutput);
  697. Trace.String("Finalizing Process"); Trace.Int(p.id, 1);
  698. WriteType(p.obj); Trace.Ln;
  699. Machine.Release (Machine.TraceOutput);
  700. END;
  701. IF p.mode # Terminated THEN
  702. IF p.mode = AwaitingLock THEN DEC(awl);
  703. ELSIF p.mode = AwaitingCond THEN DEC(awc);
  704. END;
  705. (* no reference to the object any more *)
  706. Trace.String ("Closing unreferenced process"); (*Trace.Int(p.mode,20); Trace.Int( p.id, 20 ); *) Trace.Ln; (* Trace.Ln *)
  707. (* this usually happens, when an objects process waits on its own objtec and no reference exists any more. Then the object is discarded and
  708. consequently the process is unreferenced (except in the object). This cannot happen when there are still other references on the object.
  709. example:
  710. TYPE
  711. Object= OBJECT VAR active: BOOLEAN; BEGIN{ACTIVE} active := FALSE; AWAIT(active) END Object;
  712. VAR o: Object;
  713. BEGIN NEW(o);
  714. END;
  715. *)
  716. END;
  717. p.mode := Terminated; (* fof for GC problem *)
  718. IF p.handle # 0 THEN
  719. res := Kernel32.CloseHandle(p.handle); p.handle := 0
  720. END
  721. END FinalizeProcess;
  722. PROCEDURE TerminateProc;
  723. BEGIN
  724. terminate(CurrentProcess());
  725. Kernel32.ExitThread(0);
  726. Kernel32.Sleep(999999); (* wait until dependent threads terminated *)
  727. END TerminateProc;
  728. (* Allocate a new process associated with "obj". Must be outside lock region, because of potential GC. *)
  729. PROCEDURE NewProcess(body: Body; priority: LONGINT; flags: SET; obj: ProtectedObject; VAR new: Process);
  730. VAR t,r: Process; fn: Heaps.FinalizerNode;
  731. BEGIN
  732. NEW(t);
  733. t.gcContext.nextPos := 0;
  734. t.context := CurrentContext(); (* inherit context from parent process *)
  735. t.handle := 0;
  736. IF priority = 0 THEN (* no priority specified *)
  737. r := CurrentProcess();
  738. t.priority := r.priority (* inherit priority of creator *)
  739. ELSIF priority > 0 THEN (* positive priority specified *)
  740. t.priority := priority
  741. ELSE (* negative priority specified (only for Idle process) *)
  742. t.priority := MinPriority
  743. END;
  744. NEW(fn); (* implicit call Heaps.NewRec -> might invoke GC *)
  745. Machine.Acquire(Machine.Objects);
  746. t.next := NIL; t.prev := NIL; t.rootedNext := NIL;
  747. t.waitingOn := NIL; t.flags := flags; t.obj := obj; t.mode := Unknown;
  748. t.body := body; t.event := 0; fn.finalizer := FinalizeProcess;
  749. Heaps.AddFinalizer(t, fn);
  750. IF Restart IN flags THEN (* restart object body *)
  751. t.restartPC := SYSTEM.VAL(ADDRESS, body);
  752. ELSE (* terminate process *)
  753. t.restartPC := SYSTEM.VAL(ADDRESS, terminateProc);
  754. END;
  755. (*! Put the process into the process queue before the thread is created.
  756. this is highly important in case of a DLL, where Objects.AttachThread
  757. will be called by Kernel32.EntryPoint (DllMain)
  758. *)
  759. Put(ready, t);
  760. t.handle := Kernel32.CreateThread(0, defaultStackSize, Wrapper, t, {}, t.id);
  761. IF TraceVerbose OR TraceOpenClose THEN
  762. Machine.Acquire(Machine.TraceOutput);
  763. Trace.String("NewProcess: " ); Trace.Int(t.id, 1); WriteType(obj); Trace.Ln;
  764. Machine.Release(Machine.TraceOutput);
  765. END;
  766. ASSERT(t.handle # 0);
  767. new := t;
  768. END NewProcess;
  769. (* Create the process associated with an active object (kernel call). *)
  770. PROCEDURE CreateProcess*(body: Body; priority: LONGINT; flags: SET; obj: ProtectedObject);
  771. VAR t : Process; heapBlock {UNTRACED}: Heaps.HeapBlock;
  772. BEGIN
  773. ASSERT(priority >= 0, 1000); ASSERT(priority <=Realtime, 1001);
  774. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, heapBlock);
  775. ASSERT(heapBlock IS Heaps.ProtRecBlock); (* protected object *)
  776. IF Restart IN flags THEN INCL(flags, Resistant) END; (* SAFE => Restart & Resistant *)
  777. NewProcess(body, priority, flags, obj, t); INC(nProcs); (* acquires Machine.Objects lock *)
  778. t.mode := Ready;
  779. Machine.Release(Machine.Objects);
  780. END CreateProcess;
  781. (* The procedure Lock, Unlock and Await do not use header locks since it turned out that the header locks sometimes were finalized
  782. too early. *)
  783. PROCEDURE Lock*(obj: ProtectedObject; exclusive: BOOLEAN );
  784. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; r: Process; res: WORD;
  785. BEGIN (* {called from user level} *)
  786. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  787. IF StrongChecks THEN
  788. ASSERT(hdr IS Heaps.ProtRecBlock); (* protected object *)
  789. ASSERT(exclusive) (* shared not implemented yet *)
  790. END;
  791. r := CurrentProcess();
  792. IF StrongChecks THEN
  793. ASSERT(hdr # NIL, 1001);
  794. ASSERT(r # NIL, 1002);
  795. END;
  796. Machine.Acquire(Machine.Objects);
  797. IF hdr.count = 0 THEN (* not locked *)
  798. hdr.count := -1; hdr.lockedBy := r;
  799. Machine.Release(Machine.Objects)
  800. ELSE (* already locked *)
  801. IF hdr.lockedBy = r THEN
  802. Machine.Release(Machine.Objects);
  803. HALT(2203) (* nested locks not allowed *)
  804. END;
  805. ASSERT(r.waitingOn = NIL); (* sanity check *)
  806. Remove(ready, r);
  807. IF r.event = 0 THEN
  808. r.event := Kernel32.CreateEvent( NIL, Kernel32.False (* auto *), Kernel32.False, NIL ); (* auto reset event with initial state = reset *)
  809. ASSERT ( r.event # 0, 1239 );
  810. END;
  811. r.waitingOn := obj; r.mode := AwaitingLock;
  812. Put(hdr.awaitingLock, r); INC(awl);
  813. Machine.Release(Machine.Objects);
  814. res := Kernel32.WaitForSingleObject(r.event, Kernel32.Infinite); (* block execution *)
  815. ASSERT(res = Kernel32.WaitObject0);
  816. IF StrongChecks THEN
  817. ASSERT(hdr.lockedBy = r); (* at this moment only this process can own the lock and only this process can release it*)
  818. END;
  819. END
  820. END Lock;
  821. (* Find the first true condition from the queue and remove it. Assume the object is currently locked. *)
  822. PROCEDURE FindCondition( VAR q: ProcessQueue ): Process;
  823. VAR first, cand: Process;
  824. BEGIN
  825. Get( q, first );
  826. IF first.condition( first.condFP ) THEN RETURN first END;
  827. Put( q, first );
  828. WHILE q.head # first DO
  829. Get( q, cand );
  830. IF cand.condition( cand.condFP ) THEN RETURN cand END;
  831. Put( q, cand )
  832. END;
  833. RETURN NIL
  834. END FindCondition;
  835. (* The procedure Lock, Unlock and Await do not use header locks since it turned out that the header locks sometimes were finalized
  836. too early. *)
  837. PROCEDURE Unlock*( obj: ProtectedObject; dummy: BOOLEAN );
  838. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; t, c: Process; res: WORD;
  839. BEGIN
  840. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  841. IF StrongChecks THEN
  842. ASSERT(hdr IS Heaps.ProtRecBlock) (* protected object *)
  843. END;
  844. ASSERT(hdr.count = -1); (* exclusive locked *)
  845. Machine.Acquire(Machine.Objects);
  846. IF hdr.awaitingCond.head # NIL THEN (* evaluate the waiting conditions *)
  847. (* we are holding the lock, so the queue can not change (to do: except in TerminateThis) *)
  848. c := FindCondition(hdr.awaitingCond); (* interrupts should be on during this call *)
  849. ELSE
  850. c := NIL
  851. END;
  852. IF c = NIL THEN (* no true condition found, check the lock queue *)
  853. Get(hdr.awaitingLock, t);
  854. IF t # NIL THEN
  855. hdr.lockedBy := t;
  856. t.waitingOn := NIL;
  857. ELSE
  858. hdr.lockedBy := NIL; hdr.count := 0
  859. END
  860. ELSE (* true condition found, transfer the lock *)
  861. c.waitingOn := NIL; hdr.lockedBy := c;
  862. t := NIL
  863. END;
  864. IF c # NIL THEN
  865. Put(ready, c); c.mode := Running; DEC(awc);
  866. res := Kernel32.SetEvent(c.event);
  867. ASSERT (res # 0, 1001);
  868. ELSIF t # NIL THEN
  869. Put(ready, t); t.mode := Running; DEC(awl);
  870. res := Kernel32.SetEvent(t.event);
  871. ASSERT (res # 0, 1002);
  872. END;
  873. Machine.Release( Machine.Objects )
  874. END Unlock;
  875. (* The procedure Lock, Unlock and Await do not use header locks since it turned out that the header locks sometimes were finalized
  876. too early. *)
  877. PROCEDURE Await*( cond: Condition; slink: LONGINT; obj: ProtectedObject; flags: SET );
  878. VAR hdr {UNTRACED}: Heaps.ProtRecBlock; r, c, t: Process; res: WORD;
  879. BEGIN
  880. IF 1 IN flags THEN (* compiler did not generate IF *)
  881. IF cond(slink) THEN
  882. RETURN (* condition already true *)
  883. END
  884. END;
  885. SYSTEM.GET(SYSTEM.VAL(ADDRESS, obj) + Heaps.HeapBlockOffset, hdr);
  886. IF StrongChecks THEN
  887. ASSERT(hdr IS Heaps.ProtRecBlock) (* protected object *)
  888. END;
  889. r := CurrentProcess();
  890. Machine.Acquire(Machine.Objects);
  891. IF hdr.lockedBy = r THEN (* current process holds exclusive lock *)
  892. IF StrongChecks THEN ASSERT(hdr.count = -1) END; (* exclusive locked *)
  893. IF hdr.awaitingCond.head # NIL THEN (* evaluate the waiting conditions *)
  894. (* we are holding the lock, so the queue can not change (to do: except in TerminateThis) *)
  895. c := FindCondition(hdr.awaitingCond) (* interrupts should be on during this call *)
  896. ELSE
  897. c := NIL
  898. END;
  899. IF c = NIL THEN
  900. Get(hdr.awaitingLock, t);
  901. IF t = NIL THEN (* none waiting - remove lock *)
  902. hdr.count := 0; hdr.lockedBy := NIL;
  903. ELSE (* transfer lock to first waiting process *)
  904. IF StrongChecks THEN ASSERT(t.mode = AwaitingLock) END;
  905. t.waitingOn := NIL;
  906. hdr.lockedBy := t;
  907. END;
  908. ELSE
  909. c.waitingOn := NIL; hdr.lockedBy := c;
  910. t := NIL;
  911. END;
  912. ELSE (* no lock, or some other process may hold the lock, but that's the user's indaba (may be monotonic condition) *)
  913. Machine.Release(Machine.Objects);
  914. HALT( 2204 ) (* await must be exclusive region *)
  915. END;
  916. r.condition := cond; r.condFP := slink;
  917. r.waitingOn := obj; r.mode := AwaitingCond;
  918. Remove(ready, r);
  919. IF r.event = 0 THEN
  920. r.event := Kernel32.CreateEvent( NIL, Kernel32.False (* auto *), Kernel32.False, NIL ); (* auto-reset event with initial state = reset *)
  921. ASSERT ( r.event # 0, 1239 );
  922. END;
  923. IF c # NIL THEN
  924. DEC(awc); Put(ready, c); c.mode := Running;
  925. res := Kernel32.SetEvent(c.event); (* restart execution *)
  926. ASSERT(res # 0, 1002);
  927. END;
  928. IF t # NIL THEN
  929. DEC(awl); Put(ready, t); t.mode := Running;
  930. res := Kernel32.SetEvent( t.event ); (* restart execution *)
  931. ASSERT(res # 0, 1003);
  932. END;
  933. Put(hdr.awaitingCond, r); INC(awc);
  934. Machine.Release(Machine.Objects);
  935. res := Kernel32.WaitForSingleObject(r.event, Kernel32.Infinite); (* block execution *)
  936. ASSERT(res = Kernel32.WaitObject0);
  937. IF StrongChecks THEN
  938. ASSERT(cond(slink));
  939. ASSERT(hdr.lockedBy = r) (* lock held again *)
  940. END
  941. END Await;
  942. PROCEDURE Break*( t: Process );
  943. CONST MaxTry = 50;
  944. VAR mod: Modules.Module; try: LONGINT; retBOOL: Kernel32.BOOL; (* Dan 09.11.05 *)
  945. PROCEDURE SafeForBreak( mod: Modules.Module ): BOOLEAN;
  946. BEGIN
  947. Trace.String( "Safe for break?: " );
  948. IF mod # NIL THEN
  949. Trace.StringLn ( mod.name );
  950. IF (mod.name = "Trace") OR (mod.name = "Machine") OR
  951. (mod.name = "Heaps") OR (mod.name = "Modules") OR
  952. (mod.name = "Objects") OR (mod.name = "Kernel") THEN
  953. Trace.StringLn ( " - no" ); RETURN FALSE
  954. ELSE Trace.StringLn ( " - yes" ); RETURN TRUE
  955. END
  956. ELSE Trace.StringLn ( "unknown module" ); RETURN FALSE
  957. END
  958. END SafeForBreak;
  959. BEGIN
  960. IF CurrentProcess() # t THEN
  961. Machine.Acquire( Machine.Objects );
  962. LOOP
  963. retBOOL := Kernel32.SuspendThread( t.handle );
  964. t.state.ContextFlags := Kernel32.ContextControl;
  965. retBOOL := Kernel32.GetThreadContext( t.handle, t.state );
  966. mod := Modules.ThisModuleByAdr( t.state.PC ); Trace.String( "Objects Break at adr: " );
  967. Trace.Int( t.state.PC, 5 ); Trace.Ln;
  968. IF mod # NIL THEN
  969. Trace.String( "In module: " ); Trace.StringLn ( mod.name );
  970. END;
  971. IF ~SafeForBreak( mod ) (* we do not break Kernel modules *) THEN
  972. retBOOL := Kernel32.ResumeThread( t.handle ); INC( try );
  973. IF try > MaxTry THEN
  974. Trace.StringLn ( "Threads.Break: failed " );
  975. Machine.Release( Machine.Objects );
  976. RETURN
  977. END
  978. ELSE EXIT
  979. END;
  980. END;
  981. (* push cont.Eip *) break[0] := 68X;
  982. SYSTEM.MOVE( ADDRESSOF( t.state.PC ), ADDRESSOF( break[1] ), 4 );
  983. (* push ebp *) break[5] := 055X;
  984. (* mov ebp, esp *) break[6] := 08BX; break[7] := 0ECX;
  985. (* push 13 *) break[8] := 06AX; break[9] := 0DX;
  986. (* int 3 *) break[10] := 0CCX;
  987. (* mov esp, ebp *) break[11] := 08BX; break[12] := 0E5X;
  988. (* pop ebp *) break[13] := 05DX;
  989. (* ret *) break[14] := 0C3X; t.state.PC := ADDRESSOF( break[0] );
  990. retBOOL := Kernel32.SetThreadContext( t.handle, t.state );
  991. retBOOL := Kernel32.ResumeThread( t.handle ); (* INC( Kernel.GClevel ); *)
  992. Machine.Release( Machine.Objects );
  993. ELSE HALT( 99 )
  994. END;
  995. END Break;
  996. (* Attempt to terminate a specific process (mostly ignoring its locks). DEPRECATED *)
  997. PROCEDURE TerminateThis*( t: Process; halt: BOOLEAN );
  998. BEGIN
  999. terminate(t);
  1000. END TerminateThis;
  1001. PROCEDURE Terminate*;
  1002. BEGIN
  1003. TerminateProc();
  1004. END Terminate;
  1005. PROCEDURE Init; (* can not use NEW *)
  1006. VAR t: Process; fn: Heaps.FinalizerNode; proc: Kernel32.HANDLE;
  1007. res: Kernel32.BOOL;
  1008. BEGIN
  1009. Kernel32.AddVectoredExceptionHandler(1, ExcpFrmHandler);
  1010. Kernel32.InitializeCriticalSection(excplock);
  1011. numberOfProcessors := Machine.NumberOfProcessors();
  1012. #IF SHAREDLIB THEN
  1013. EnterA2; (*! ExitA2 for the DLL loading thread will be called after execution of all module bodies (see Modules.Main) *)
  1014. #ELSE
  1015. NEW(t);
  1016. NEW(fn);
  1017. Machine.Acquire(Machine.Objects);
  1018. t.gcContext.nextPos := 0;
  1019. nProcs := 1;
  1020. t.next := NIL; t.prev := NIL;
  1021. t.waitingOn := NIL;
  1022. t.flags := {};
  1023. t.obj := NIL;
  1024. t.mode := Unknown; t.body := NIL;
  1025. t.priority := Normal;
  1026. fn.finalizer := FinalizeProcess;
  1027. Heaps.AddFinalizer(t, fn);
  1028. t.handle := Kernel32.GetCurrentThread();
  1029. t.id := Kernel32.GetCurrentThreadId();
  1030. proc := Kernel32.GetCurrentProcess();
  1031. res := Kernel32.DuplicateHandle(proc, t.handle, proc, t.handle, {}, 0, {Kernel32.DuplicateSameAccess});
  1032. ASSERT(res # 0);
  1033. res := Kernel32.TlsSetValue(tlsIndex, SYSTEM.VAL(ADDRESS, t));
  1034. ASSERT(res # 0);
  1035. t.stackBottom := Machine.stackBottom;
  1036. t.mode := Running;
  1037. Put( ready, t );
  1038. ASSERT(t.handle # 0);
  1039. Machine.Release(Machine.Objects);
  1040. #END;
  1041. InitEventHandling; (* implicit call of NewProcess! *)
  1042. InitGCHandling; (* do. *)
  1043. Heaps.gcStatus := GCStatusFactory();
  1044. END Init;
  1045. (** Set (or reset) an event handler object's timeout value. *)
  1046. PROCEDURE SetTimeout*(t: Timer; h: EventHandler; ms: LONGINT );
  1047. VAR e: Timer; trigger: LONGINT;
  1048. BEGIN
  1049. ASSERT(Machine.Second= 1000); (* assume milliseconds for now *)
  1050. ASSERT((t # NIL) & (h # NIL));
  1051. ASSERT(ms >= 0);
  1052. Machine.Acquire(Machine.Objects);
  1053. trigger := Kernel32.GetTickCount() + ms; (* ignore overflow *)
  1054. IF t.next # NIL THEN (* cancel previous timeout *)
  1055. t.next.prev := t.prev; t.prev.next := t.next
  1056. END;
  1057. t.trigger := trigger; t.handler := h;
  1058. e := event.next; (* performance: linear search! *)
  1059. WHILE (e # event) & (e.trigger - trigger <= 0) DO e := e.next END;
  1060. t.prev := e.prev; e.prev := t; t.next := e; t.prev.next := t;
  1061. Machine.Release(Machine.Objects);
  1062. clock.Wakeup()
  1063. END SetTimeout;
  1064. (** Set (or reset) an event handler object's timeout value. Here ms is absolute *)
  1065. PROCEDURE SetTimeoutAt*(t: Timer; h: EventHandler; ms: LONGINT);
  1066. VAR e: Timer; trigger: LONGINT;
  1067. BEGIN
  1068. ASSERT(Machine.Second= 1000); (* assume milliseconds for now *)
  1069. ASSERT((t # NIL) & (h # NIL));
  1070. Machine.Acquire(Machine.Objects);
  1071. trigger := ms; (* ignore overflow *)
  1072. IF t.next # NIL THEN (* cancel previous timeout *)
  1073. t.next.prev := t.prev; t.prev.next := t.next
  1074. END;
  1075. t.trigger := trigger; t.handler := h;
  1076. e := event.next; (* performance: linear search! *)
  1077. WHILE (e # event) & (e.trigger - trigger <= 0) DO e := e.next END;
  1078. t.prev := e.prev; e.prev := t; t.next := e; t.prev.next := t;
  1079. Machine.Release(Machine.Objects);
  1080. clock.Wakeup()
  1081. END SetTimeoutAt;
  1082. (** Cancel an event handler object's timeout, if any. It is possible that the timer has expired, but not yet been scheduled to run. *)
  1083. PROCEDURE CancelTimeout*( t: Timer );
  1084. BEGIN
  1085. Machine.Acquire(Machine.Objects);
  1086. ASSERT (t # event );
  1087. IF t.next # NIL THEN
  1088. t.next.prev := t.prev;
  1089. IF t.prev#NIL THEN t.prev.next := t.next; END;
  1090. t.next := NIL;
  1091. t.prev := NIL
  1092. END;
  1093. Machine.Release(Machine.Objects);
  1094. END CancelTimeout;
  1095. PROCEDURE InitEventHandling;
  1096. BEGIN
  1097. NEW(event); event.next := event; event.prev := event; (* event: head of timer event queue, only a sentinel *)
  1098. NEW(clock);
  1099. END InitEventHandling;
  1100. PROCEDURE InitGCHandling;
  1101. BEGIN
  1102. NEW(finalizerCaller);
  1103. END InitGCHandling;
  1104. PROCEDURE GCStatusFactory(): Heaps.GCStatus;
  1105. VAR gcStatusExt : GCStatusExt;
  1106. BEGIN
  1107. ASSERT(Heaps.gcStatus = NIL);
  1108. NEW(gcStatusExt);
  1109. RETURN gcStatusExt
  1110. END GCStatusFactory;
  1111. PROCEDURE InstallExceptionHandler*( e: ExceptionHandler );
  1112. BEGIN
  1113. exceptionhandler := e;
  1114. END InstallExceptionHandler;
  1115. PROCEDURE UpdateProcessState*( p: Process );
  1116. VAR res: Kernel32.BOOL;
  1117. BEGIN
  1118. res := Kernel32.GetThreadContext( p.handle, p.state );
  1119. ASSERT (p.handle # 0);
  1120. END UpdateProcessState;
  1121. (*ALEX 2005.12.12 added for WMPerfMon needs*)
  1122. PROCEDURE NumReady*( ): LONGINT;
  1123. VAR n: LONGINT; p: Heaps.ProcessLink;
  1124. BEGIN
  1125. n := 0;
  1126. Machine.Acquire( Machine.Objects );
  1127. p := ready.head;
  1128. WHILE p # NIL DO INC( n ); p := p.next END;
  1129. Machine.Release( Machine.Objects );
  1130. RETURN n
  1131. END NumReady;
  1132. (** Return number of CPU cycles consumed by the specified process. If all is TRUE,
  1133. return the number of cycles since the process has been created. If FALSE, return the number of cycles
  1134. consumed since the last time asked. *)
  1135. PROCEDURE GetCpuCycles*(process : Process; VAR cpuCycles : CpuCyclesArray; all : BOOLEAN);
  1136. VAR res : Kernel32.BOOL; temp : HUGEINT;
  1137. BEGIN
  1138. ASSERT(process # NIL);
  1139. IF (Kernel32.QueryThreadCycleTime # NIL) THEN
  1140. res := Kernel32.QueryThreadCycleTime(process.handle, cpuCycles[0]);
  1141. ELSE
  1142. cpuCycles[0] := Machine.GetTimer(); res := Kernel32.True;
  1143. END;
  1144. IF ~all & (res = Kernel32.True) THEN
  1145. temp := process.lastThreadTimes;
  1146. process.lastThreadTimes := cpuCycles[0];
  1147. cpuCycles[0] := cpuCycles[0] - temp;
  1148. END;
  1149. END GetCpuCycles;
  1150. PROCEDURE CurrentProcessTime*(): HUGEINT;
  1151. VAR res: WORD; result: HUGEINT;
  1152. BEGIN
  1153. IF (Kernel32.QueryThreadCycleTime # NIL) THEN
  1154. res := Kernel32.QueryThreadCycleTime(CurrentProcess().handle, result);
  1155. ELSE (* fallback *)
  1156. result := Machine.GetTimer();
  1157. END;
  1158. RETURN result;
  1159. END CurrentProcessTime;
  1160. PROCEDURE TimerFrequency*(): HUGEINT;
  1161. BEGIN
  1162. RETURN 1000000000;
  1163. END TimerFrequency;
  1164. VAR GetProcedureName*: PROCEDURE (pc: ADDRESS; VAR n: ARRAY OF CHAR; VAR spc: ADDRESS);
  1165. (* Leave A2 is called when a process leaves A2 by a call to the windows API *)
  1166. PROCEDURE LeaveA2*;
  1167. VAR cur: Process; ebp,n: ADDRESS;
  1168. BEGIN
  1169. #IF AMD64 THEN
  1170. CODE
  1171. PUSH RCX
  1172. PUSH RDX
  1173. PUSH R8
  1174. PUSH R9
  1175. END;
  1176. #END
  1177. IF clock = NIL THEN
  1178. RETURN
  1179. END;
  1180. cur := CurrentProcess();
  1181. IF cur # NIL THEN
  1182. ebp := SYSTEM.GetFramePointer();
  1183. SYSTEM.GET(ebp, n);
  1184. IF ODD(n) THEN SYSTEM.GET(ebp + SIZEOF(ADDRESS), ebp) ELSE ebp := n END;
  1185. cur.gcContext.last[cur.gcContext.nextPos] := ebp;
  1186. INC(cur.gcContext.nextPos);
  1187. ASSERT(cur.gcContext.nextPos < 255);
  1188. END;
  1189. #IF AMD64 THEN
  1190. CODE
  1191. POP R9
  1192. POP R8
  1193. POP RDX
  1194. POP RCX
  1195. END;
  1196. #END
  1197. END LeaveA2;
  1198. (* reenter is called when a process returns from a call to the windows API *)
  1199. PROCEDURE ReenterA2*;
  1200. VAR cur: Process;
  1201. BEGIN
  1202. IF clock = NIL THEN RETURN END;
  1203. cur := CurrentProcess();
  1204. IF cur # NIL THEN
  1205. IF (cur.gcContext.nextPos > 0) THEN
  1206. DEC(cur.gcContext.nextPos);
  1207. END;
  1208. cur.gcContext.last[cur.gcContext.nextPos] := NIL; (* returned *)
  1209. (*cur.gcContext.first[cur.gcContext.nextPos] := NIL; (* returned *)*)
  1210. END;
  1211. END ReenterA2;
  1212. #IF SHAREDLIB THEN
  1213. PROCEDURE AcquireLock(VAR lock: BOOLEAN);
  1214. BEGIN
  1215. REPEAT UNTIL CAS(lock, FALSE, TRUE) = FALSE;
  1216. END AcquireLock;
  1217. PROCEDURE ReleaseLock(VAR lock: BOOLEAN);
  1218. BEGIN
  1219. IGNORE CAS(lock, TRUE, FALSE);
  1220. END ReleaseLock;
  1221. VAR
  1222. protect: Process;
  1223. protectLock: BOOLEAN;
  1224. PROCEDURE RegisterExternalProcess;
  1225. VAR
  1226. t: Process;
  1227. proc: Kernel32.HANDLE;
  1228. res: Kernel32.BOOL;
  1229. low, high: SIZE;
  1230. BEGIN
  1231. (*! global variable "protect" is used for avoiding problems when GC is invoked
  1232. by calling NEW while the current external thread is not yet registered.
  1233. *)
  1234. AcquireLock(protectLock);
  1235. NEW(protect); t := protect;
  1236. NEW(t.obj); (*! required for ActiveObject() to return non-NIL *)
  1237. t.gcContext.nextPos := 0; (*! the registered process is considered as entered into A2 *)
  1238. t.next := NIL; t.prev := NIL;
  1239. t.waitingOn := NIL;
  1240. t.flags := {External}; (*! mark the process as external (non A2) *)
  1241. t.mode := Unknown; t.body := NIL;
  1242. t.handle := Kernel32.GetCurrentThread();
  1243. t.priority := Kernel32.GetThreadPriority(t.handle);
  1244. ASSERT(t.priority # Kernel32.ThreadPriorityErrorReturn);
  1245. CASE t.priority OF
  1246. |Kernel32.ThreadPriorityIdle: t.priority := MinPriority;
  1247. |Kernel32.ThreadPriorityBelowNormal: t.priority := Low;
  1248. |Kernel32.ThreadPriorityAboveNormal,Kernel32.ThreadPriorityHighest: t.priority := High;
  1249. |Kernel32.ThreadPriorityTimeCritical: t.priority := Realtime;
  1250. ELSE
  1251. ASSERT(t.priority = Kernel32.ThreadPriorityNormal);
  1252. t.priority := Normal;
  1253. END;
  1254. t.id := Kernel32.GetCurrentThreadId();
  1255. proc := Kernel32.GetCurrentProcess();
  1256. res := Kernel32.DuplicateHandle(proc, t.handle, proc, t.handle, {}, 0, {Kernel32.DuplicateSameAccess});
  1257. ASSERT(res # 0);
  1258. Kernel32.GetCurrentThreadStackLimits(low,high);
  1259. t.stackBottom := high;
  1260. t.mode := Running;
  1261. res := Kernel32.TlsSetValue(tlsIndex, SYSTEM.VAL(ADDRESS, t));
  1262. ASSERT(res # 0);
  1263. Machine.Acquire(Machine.Objects);
  1264. Put(ready, t);
  1265. INC(nProcs);
  1266. Machine.Release(Machine.Objects);
  1267. ReleaseLock(protectLock);
  1268. Machine.Acquire(Machine.TraceOutput);
  1269. Trace.String("registered an external thread: id=");
  1270. Trace.Int(t.id,0);
  1271. Trace.String(", handle=");
  1272. Trace.Int(t.handle,0);
  1273. Trace.String(", stackBottom=");
  1274. Trace.Hex(t.stackBottom,-8);
  1275. Trace.Ln;
  1276. Machine.Release(Machine.TraceOutput);
  1277. END RegisterExternalProcess;
  1278. (* enter A2 should be called when a process enters A2 from windows or from A2 via a call to a WINAPI A2 function *)
  1279. PROCEDURE EnterA2*;
  1280. VAR cur: Process; ebp, n: ADDRESS;
  1281. BEGIN
  1282. cur := CurrentProcess();
  1283. IF cur = NIL THEN (* create a process descriptor *)
  1284. RegisterExternalProcess;
  1285. cur := CurrentProcess();
  1286. IF TraceVerbose THEN
  1287. Machine.Acquire(Machine.TraceOutput);
  1288. Trace.String("First Enter: "); Trace.Int(cur.id,0); Trace.Ln;
  1289. Machine.Release(Machine.TraceOutput);
  1290. END;
  1291. ELSE
  1292. ebp := SYSTEM.GetFramePointer();
  1293. SYSTEM.GET(ebp, n);
  1294. IF ODD(n) THEN SYSTEM.GET(ebp + SIZEOF(ADDRESS), ebp) ELSE ebp := n END;
  1295. IF cur.gcContext.nextPos = -1 THEN (* re-entry *)
  1296. cur.gcContext.nextPos := 0;
  1297. cur.stackBottom := ebp;
  1298. IF TraceVerbose THEN
  1299. Machine.Acquire(Machine.TraceOutput);
  1300. Trace.String("Reenter: "); Trace.Int(cur.id,0); Trace.Ln;
  1301. Machine.Release(Machine.TraceOutput);
  1302. END;
  1303. ELSE
  1304. INC(cur.gcContext.nextPos);
  1305. cur.gcContext.last[cur.gcContext.nextPos] := NIL;
  1306. END;
  1307. END;
  1308. (*
  1309. cur.gcContext.first[cur.gcContext.nextPos] := ebp; (* here our responsibility starts -- currently this field is not strictly required to be set valid *)
  1310. cur.gcContext.last[cur.gcContext.nextPos] := NIL; (* we do not know where it ends yet *)
  1311. *)
  1312. END EnterA2;
  1313. (* exit A2 should be called when a process exits a WINAPI procedure *)
  1314. PROCEDURE ExitA2*();
  1315. VAR cur: Process;
  1316. BEGIN
  1317. cur := CurrentProcess();
  1318. ASSERT(cur # NIL);
  1319. IF cur.gcContext.nextPos > 0 THEN
  1320. DEC(cur.gcContext.nextPos);
  1321. cur.gcContext.last[cur.gcContext.nextPos] := NIL;
  1322. ELSE
  1323. IF TraceVerbose THEN
  1324. Machine.Acquire(Machine.TraceOutput);
  1325. Trace.String("Exiting: "); Trace.Int(cur.id,0); Trace.Ln;
  1326. Machine.Release(Machine.TraceOutput);
  1327. END;
  1328. cur.gcContext.nextPos := -1;
  1329. END;
  1330. END ExitA2;
  1331. PROCEDURE AttachThread*();
  1332. BEGIN
  1333. END AttachThread;
  1334. (* Cleanup resources of an external process. Must be called while Objects lock is taken *)
  1335. PROCEDURE CleanupExternalProcess(t: Process);
  1336. BEGIN
  1337. ASSERT(External IN t.flags);
  1338. IF InQueue(ready,t) THEN
  1339. Remove(ready,t); DEC(nProcs);
  1340. END;
  1341. IF t.event # 0 THEN IGNORE Kernel32.CloseHandle(t.event); END;
  1342. END CleanupExternalProcess;
  1343. (* Called when a thread is detaching from the DLL *)
  1344. PROCEDURE DetachThread*();
  1345. VAR
  1346. t: Process;
  1347. res: Kernel32.BOOL;
  1348. BEGIN
  1349. t := CurrentProcess();
  1350. IF (t = NIL) OR ~(External IN t.flags) THEN RETURN; END;
  1351. Machine.Acquire (Machine.TraceOutput);
  1352. Trace.String("detaching a thread: id="); Trace.Int(t.id,0); Trace.Ln;
  1353. Machine.Release (Machine.TraceOutput);
  1354. Machine.Acquire(Machine.Objects);
  1355. CleanupExternalProcess(t);
  1356. res := Kernel32.TlsSetValue(tlsIndex, NIL);
  1357. ASSERT(res # 0);
  1358. Machine.Release(Machine.Objects);
  1359. Machine.Acquire (Machine.TraceOutput);
  1360. Trace.String("detached a thread: id="); Trace.Int(t.id,0); Trace.Ln;
  1361. Machine.Release (Machine.TraceOutput);
  1362. END DetachThread;
  1363. PROCEDURE CleanupProcesses;
  1364. VAR
  1365. t: Process;
  1366. res: Kernel32.BOOL;
  1367. BEGIN
  1368. Machine.Acquire(Machine.Objects);
  1369. Get(ready, t); DEC(nProcs);
  1370. WHILE t # NIL DO
  1371. IF t.mode # Terminated THEN
  1372. IF External IN t.flags THEN
  1373. Machine.Acquire (Machine.TraceOutput);
  1374. Trace.String("cleaning up an external process: id="); Trace.Int(t.id,0); Trace.String(", mode="); Trace.Int(t.mode,0); Trace.Ln;
  1375. Machine.Release (Machine.TraceOutput);
  1376. CleanupExternalProcess(t);
  1377. ELSE
  1378. Machine.Acquire (Machine.TraceOutput);
  1379. Trace.String("killing a process: id="); Trace.Int(t.id,0); Trace.String(", mode="); Trace.Int(t.mode,0); Trace.Ln;
  1380. Machine.Release (Machine.TraceOutput);
  1381. res := Kernel32.TerminateThread(t.handle,-1);
  1382. IF res = 0 THEN
  1383. Machine.Acquire (Machine.TraceOutput);
  1384. Trace.String("failed to kill a process: id="); Trace.Int(t.id,0); Trace.String(", error="); Trace.Int(Kernel32.GetLastError(),0); Trace.Ln;
  1385. Machine.Release (Machine.TraceOutput);
  1386. END;
  1387. END;
  1388. END;
  1389. Get(ready, t); DEC(nProcs);
  1390. END;
  1391. Trace.String("nProcs="); Trace.Int(nProcs,0); Trace.Ln;
  1392. Machine.Release(Machine.Objects);
  1393. END CleanupProcesses;
  1394. (* Called when the DLL loading process is detaching from the DLL *)
  1395. PROCEDURE DetachProcess*();
  1396. CONST
  1397. TerminationTimeout = 1000;
  1398. VAR
  1399. p: Heaps.ProcessLink;
  1400. t: Process;
  1401. res: Kernel32.BOOL;
  1402. tick: LONGINT;
  1403. numNonTerminated, numExternals: SIZE;
  1404. BEGIN
  1405. EnterA2;
  1406. Machine.Acquire(Machine.TraceOutput);
  1407. Trace.String("detaching the process: id="); Trace.Int(Kernel32.GetCurrentThreadId(),0); Trace.Ln;
  1408. Machine.Release(Machine.TraceOutput);
  1409. Modules.Shutdown(-1);
  1410. finalizerCaller.Exit;
  1411. clock.Exit;
  1412. Machine.Acquire(Machine.TraceOutput);
  1413. Trace.StringLn("wait until all A2 processes terminate");
  1414. Machine.Release(Machine.TraceOutput);
  1415. tick := Kernel32.GetTickCount();
  1416. REPEAT
  1417. numNonTerminated := 0;
  1418. numExternals := 0;
  1419. Machine.Acquire(Machine.Objects);
  1420. p := ready.head;
  1421. WHILE p # NIL DO
  1422. t := p(Process);
  1423. IF External IN t.flags THEN
  1424. INC(numExternals);
  1425. ELSIF t.mode # Terminated THEN
  1426. INC(numNonTerminated);
  1427. END;
  1428. p := p.next;
  1429. END;
  1430. Machine.Release(Machine.Objects);
  1431. UNTIL (numNonTerminated = 0) OR (Kernel32.GetTickCount() - tick >= TerminationTimeout);
  1432. IF numNonTerminated # 0 THEN
  1433. Machine.Acquire(Machine.TraceOutput);
  1434. Trace.String("there are "); Trace.Int(numNonTerminated,0); Trace.StringLn(" A2 processes to terminate forcedly");
  1435. Machine.Release(Machine.TraceOutput);
  1436. CleanupProcesses;
  1437. ELSE
  1438. Machine.Acquire(Machine.TraceOutput);
  1439. Trace.StringLn("all A2 processes terminated");
  1440. Machine.Release(Machine.TraceOutput);
  1441. IF numExternals # 0 THEN
  1442. CleanupProcesses;
  1443. END;
  1444. END;
  1445. res := Kernel32.TlsFree(tlsIndex);
  1446. IF res = 0 THEN
  1447. Machine.Acquire (Machine.TraceOutput);
  1448. Trace.String("failed free TLS: error="); Trace.Int(Kernel32.GetLastError(),0); Trace.Ln;
  1449. Machine.Release (Machine.TraceOutput);
  1450. END;
  1451. (*!TODO: free resources allocated in Machine (e.g. critical section objects) *)
  1452. END DetachProcess;
  1453. #END;
  1454. VAR
  1455. TraceProcessHook*: PROCEDURE (prcoess: Process; pc, bp: ADDRESS; stacklow, stackhigh: ADDRESS);
  1456. BEGIN
  1457. TraceProcessHook := NIL;
  1458. exceptionhandler := NIL;
  1459. terminateProc := TerminateProc;
  1460. ready.head := NIL; ready.tail := NIL;
  1461. tlsIndex := Kernel32.TlsAlloc();
  1462. ASSERT ( tlsIndex # Kernel32.TLSOutOfIndexes );
  1463. Kernel32.SendToDebugger("Modules.root", ADDRESSOF(Modules.root));
  1464. Init;
  1465. END Objects.
  1466. Linker.Link --fileFormat=PE32CUI --fileName=oberonn.exe --extension=GofW --displacement=401000H
  1467. Builtins Trace Kernel32 Heaps Modules Objects Kernel KernelLog Streams Commands Files WinFS Clock Dates Reals Strings Diagnostics BitSets
  1468. StringPool ObjectFile GenericLinker Reflection Loader Shell StdIOShell Traps System ~