Windows.Objects.Mod 52 KB

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