Windows.Objects.Mod 55 KB

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