system.pp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. {
  2. $Id$
  3. This file is part of the Free Pascal run time library.
  4. Copyright (c) 1999-2000 by the Free Pascal development team.
  5. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. **********************************************************************}
  11. { no stack check in system }
  12. {$S-}
  13. unit system;
  14. interface
  15. {$define StdErrToConsole}
  16. {$define useLongNamespaceByDefault}
  17. {$define autoHeapRelease}
  18. {$ifdef SYSTEMDEBUG}
  19. {$define SYSTEMEXCEPTIONDEBUG}
  20. {$endif SYSTEMDEBUG}
  21. {$ifdef cpui386}
  22. {$define Set_i386_Exception_handler}
  23. {$endif cpui386}
  24. { include system-independent routine headers }
  25. {$I systemh.inc}
  26. {Platform specific information}
  27. const
  28. LineEnding = #13#10;
  29. LFNSupport : boolean = false;
  30. DirectorySeparator = '/';
  31. DriveSeparator = ':';
  32. PathSeparator = ';';
  33. { FileNameCaseSensitive is defined separately below!!! }
  34. maxExitCode = 255;
  35. CONST
  36. { Default filehandles }
  37. UnusedHandle : THandle = -1;
  38. StdInputHandle : THandle = 0;
  39. StdOutputHandle : THandle = 0;
  40. StdErrorHandle : THandle = 0;
  41. FileNameCaseSensitive : boolean = false;
  42. sLineBreak = LineEnding;
  43. DefaultTextLineBreakStyle : TTextLineBreakStyle = tlbsCRLF;
  44. TYPE
  45. TNWCheckFunction = procedure (var code : longint);
  46. VAR
  47. ArgC : INTEGER;
  48. ArgV : ppchar;
  49. NetwareCheckFunction : TNWCheckFunction;
  50. NetwareMainThreadGroupID: longint;
  51. NetwareCodeStartAddress : dword;
  52. NetwareUnloadProc : pointer = nil; {like exitProc but for nlm unload only}
  53. CONST
  54. envp : ppchar = nil; {dummy to make heaptrc happy}
  55. procedure ConsolePrintf (FormatStr : PCHAR; Param : LONGINT); CDecl; external 'clib' name 'printf';
  56. procedure ConsolePrintf (FormatStr : PCHAR; Param : pchar); CDecl; external 'clib' name 'printf';
  57. procedure ConsolePrintf (FormatStr : PCHAR; P1,P2 : LONGINT); CDecl; external 'clib' name 'printf';
  58. procedure ConsolePrintf (FormatStr : PCHAR; P1,P2,P3 : LONGINT); CDecl; external 'clib' name 'printf';
  59. procedure ConsolePrintf (FormatStr : PCHAR); CDecl; external 'clib' name 'printf';
  60. // this gives internal compiler error 200404181
  61. // procedure ConsolePrintf (FormatStr : PCHAR; Param : array of const); CDecl; EXTERNAL 'clib' name 'ConsolePrintf';
  62. procedure __EnterDebugger; cdecl; external 'clib' name 'EnterDebugger';
  63. type
  64. TSysCloseAllRemainingSemaphores = procedure;
  65. TSysReleaseThreadVars = procedure;
  66. TSysSetThreadDataAreaPtr = function (newPtr:pointer):pointer;
  67. procedure NWSysSetThreadFunctions (crs:TSysCloseAllRemainingSemaphores;
  68. rtv:TSysReleaseThreadVars;
  69. stdata:TSysSetThreadDataAreaPtr);
  70. function NWGetCodeStart : pointer; // needed for lineinfo
  71. implementation
  72. { Indicate that stack checking is taken care by OS}
  73. {$DEFINE NO_GENERIC_STACK_CHECK}
  74. { include system independent routines }
  75. {$I system.inc}
  76. //procedure __EnterDebugger; cdecl; external 'clib' name 'EnterDebugger';
  77. procedure PASCALMAIN;external name 'PASCALMAIN';
  78. procedure fpc_do_exit;external name 'FPC_DO_EXIT';
  79. {*****************************************************************************
  80. Startup
  81. *****************************************************************************}
  82. function __GetBssStart : pointer; external name '__getBssStart';
  83. function __getUninitializedDataSize : longint; external name '__getUninitializedDataSize';
  84. //function __getDataStart : longint; external name '__getDataStart';
  85. function __GetTextStart : longint; external name '__getTextStart';
  86. PROCEDURE nlm_main (_ArgC : LONGINT; _ArgV : ppchar); CDECL; [public,alias: '_nlm_main'];
  87. BEGIN
  88. // Initialize BSS
  89. if __getUninitializedDataSize > 0 then
  90. fillchar (__getBssStart^,__getUninitializedDataSize,0);
  91. NetwareCodeStartAddress := __GetTextStart;
  92. ArgC := _ArgC;
  93. ArgV := _ArgV;
  94. fpc_threadvar_relocate_proc := nil;
  95. PASCALMAIN;
  96. END;
  97. function NWGetCodeStart : pointer; // needed for lineinfo
  98. begin
  99. NWGetCodeStart := pointer(NetwareCodeStartAddress);
  100. end;
  101. {*****************************************************************************
  102. System Dependent Exit code
  103. *****************************************************************************}
  104. var SigTermHandlerActive : boolean;
  105. Procedure system_exit;
  106. begin
  107. if TerminatingThreadID <> 0 then
  108. if TerminatingThreadID <> ThreadId then
  109. if TerminatingThreadID <> _GetThreadID then
  110. begin
  111. {$ifdef DEBUG_MT}
  112. ConsolePrintf ('Terminating Thread %x because halt was called while Thread %x terminates nlm'#13#10,_GetThreadId,TerminatingThreadId);
  113. {$endif}
  114. ExitThread (EXIT_THREAD,0);
  115. // only for the case ExitThread fails
  116. while true do
  117. _ThreadSwitchWithDelay;
  118. end;
  119. if assigned (CloseAllRemainingSemaphores) then CloseAllRemainingSemaphores;
  120. if assigned (ReleaseThreadVars) then ReleaseThreadVars;
  121. {$ifdef autoHeapRelease}
  122. FreeSbrkMem; { free memory allocated by heapmanager }
  123. {$endif}
  124. if not SigTermHandlerActive then
  125. begin
  126. if ExitCode <> 0 Then { otherwise we dont see runtime-errors }
  127. _SetAutoScreenDestructionMode (false);
  128. _exit (ExitCode);
  129. end;
  130. end;
  131. {*****************************************************************************
  132. Stack check code
  133. *****************************************************************************}
  134. const StackErr : boolean = false;
  135. procedure int_stackcheck(stack_size:Cardinal);[public,alias:'FPC_STACKCHECK'];
  136. {
  137. called when trying to get local stack if the compiler directive $S
  138. is set this function must preserve all registers
  139. With a 2048 byte safe area used to write to StdIo without crossing
  140. the stack boundary
  141. }
  142. begin
  143. if StackErr then exit; // avoid recursive calls
  144. asm
  145. pusha
  146. end;
  147. stackerr := ( _stackavail < stack_size + 2048);
  148. asm
  149. popa
  150. end;
  151. if not StackErr then exit;
  152. StackErr := true;
  153. HandleError (202);
  154. end;
  155. {*****************************************************************************
  156. ParamStr/Randomize
  157. *****************************************************************************}
  158. { number of args }
  159. function paramcount : longint;
  160. begin
  161. paramcount := argc - 1;
  162. end;
  163. { argument number l }
  164. function paramstr(l : longint) : string;
  165. begin
  166. if (l>=0) and (l+1<=argc) then
  167. begin
  168. paramstr:=strpas(argv[l]);
  169. if l = 0 then // fix nlm path
  170. begin
  171. for l := 1 to length (paramstr) do
  172. if paramstr[l] = '\' then paramstr[l] := '/';
  173. end;
  174. end else
  175. paramstr:='';
  176. end;
  177. { set randseed to a new pseudo random value }
  178. procedure randomize;
  179. begin
  180. randseed := _time (NIL);
  181. end;
  182. {*****************************************************************************
  183. Thread Handling
  184. *****************************************************************************}
  185. procedure InitFPU;assembler;
  186. asm
  187. fninit
  188. fldcw fpucw
  189. end;
  190. { if return-value is <> 0, netware shows the message
  191. Unload Anyway ?
  192. To Disable unload at all, SetNLMDontUnloadFlag can be used on
  193. Netware >= 4.0 }
  194. function CheckFunction : longint; CDECL; [public,alias: 'FPC_NW_CHECKFUNCTION'];
  195. var oldTG:longint;
  196. oldPtr: pointer;
  197. begin
  198. if assigned (NetwareCheckFunction) then
  199. begin
  200. { this function is called without clib context, to allow clib
  201. calls, we set the thread group id before calling the
  202. user-function }
  203. oldTG := _SetThreadGroupID (NetwareMainThreadGroupID);
  204. { to allow use of threadvars, we simply set the threadvar-memory
  205. from the main thread }
  206. if assigned (SetThreadDataAreaPtr) then
  207. oldPtr := SetThreadDataAreaPtr (NIL); { nil means main threadvars }
  208. result := 0;
  209. NetwareCheckFunction (result);
  210. if assigned (SetThreadDataAreaPtr) then
  211. SetThreadDataAreaPtr (oldPtr);
  212. _SetThreadGroupID (oldTG);
  213. end else
  214. result := 0;
  215. end;
  216. {$ifdef StdErrToConsole}
  217. var ConsoleBuff : array [0..512] of char;
  218. Function ConsoleWrite(Var F: TextRec): Integer;
  219. var
  220. i : longint;
  221. Begin
  222. if F.BufPos>0 then
  223. begin
  224. if F.BufPos>sizeof(ConsoleBuff)-1 then
  225. i:=sizeof(ConsoleBuff)-1
  226. else
  227. i:=F.BufPos;
  228. Move(F.BufPtr^,ConsoleBuff,i);
  229. ConsoleBuff[i] := #0;
  230. ConsolePrintf(@ConsoleBuff[0]);
  231. end;
  232. F.BufPos:=0;
  233. ConsoleWrite := 0;
  234. End;
  235. Function ConsoleClose(Var F: TextRec): Integer;
  236. begin
  237. ConsoleClose:=0;
  238. end;
  239. Function ConsoleOpen(Var F: TextRec): Integer;
  240. Begin
  241. TextRec(F).InOutFunc:=@ConsoleWrite;
  242. TextRec(F).FlushFunc:=@ConsoleWrite;
  243. TextRec(F).CloseFunc:=@ConsoleClose;
  244. ConsoleOpen:=0;
  245. End;
  246. procedure AssignStdErrConsole(Var T: Text);
  247. begin
  248. Assign(T,'');
  249. TextRec(T).OpenFunc:=@ConsoleOpen;
  250. Rewrite(T);
  251. end;
  252. {$endif}
  253. { this will be called if the nlm is unloaded. It will NOT be
  254. called if the program exits i.e. with halt.
  255. Halt (or _exit) can not be called from this callback procedure }
  256. procedure TermSigHandler (Sig:longint); CDecl;
  257. var oldTG : longint;
  258. oldPtr: pointer;
  259. err : longint;
  260. current_exit : procedure;
  261. ThreadName : array [0..20] of char;
  262. HadExitProc : boolean;
  263. Count : longint;
  264. begin
  265. oldTG := _SetThreadGroupID (NetwareMainThreadGroupID); { this is only needed for nw 3.11 }
  266. { _GetThreadDataAreaPtr will not be valid because the signal
  267. handler is called by netware with a differnt thread. To avoid
  268. problems in the exit routines, we set the data of the main thread
  269. here }
  270. if assigned (SetThreadDataAreaPtr) then
  271. oldPtr := SetThreadDataAreaPtr (NIL); { nil means main thread }
  272. {this signal handler is called within the console command
  273. thread, the main thread is still running. Via NetwareUnloadProc
  274. running threads may terminate itself}
  275. TerminatingThreadID := _GetThreadID;
  276. {$ifdef DEBUG_MT}
  277. ConsolePrintf (#13'TermSigHandler Called, MainThread:%x, OurThread: %x'#13#10,ThreadId,TerminatingThreadId);
  278. if NetwareUnloadProc <> nil then
  279. ConsolePrintf (#13'Calling NetwareUnloadProcs'#13#10);
  280. {$endif}
  281. HadExitProc := false;
  282. {we need to finalize winock to release threads
  283. waiting on a blocking socket call. If that thread
  284. calls halt, we have to avoid that unit finalization
  285. is called by that thread because we are doing it
  286. here
  287. like the old exitProc, mainly to allow winsock to release threads
  288. blocking in a winsock calls }
  289. while NetwareUnloadProc<>nil Do
  290. Begin
  291. InOutRes:=0;
  292. current_exit:=tProcedure(NetwareUnloadProc);
  293. NetwareUnloadProc:=nil;
  294. current_exit();
  295. _ThreadSwitchWithDelay;
  296. hadExitProc := true;
  297. End;
  298. err := 0;
  299. if hadExitProc then
  300. begin {give the main thread a little bit of time to terminate}
  301. count := 0;
  302. repeat
  303. err := _GetThreadName(ThreadID,ThreadName);
  304. if err = 0 then _Delay (200);
  305. inc(count);
  306. until (err <> 0) or (count > 100); {about 20 seconds}
  307. {$ifdef DEBUG_MT}
  308. if err = 0 then
  309. ConsolePrintf (#13,'Main Thread not terminated'#13#10)
  310. else
  311. ConsolePrintf (#13'Main Thread has ended'#13#10);
  312. {$endif}
  313. end;
  314. if err = 0 then
  315. {$ifdef DEBUG_MT}
  316. begin
  317. err := _SuspendThread(ThreadId);
  318. ConsolePrintf (#13'SuspendThread(%x) returned %d'#13#10,ThreadId,err);
  319. end;
  320. {$else}
  321. _SuspendThread(ThreadId);
  322. {$endif}
  323. _ThreadSwitchWithDelay;
  324. {$ifdef DEBUG_MT}
  325. ConsolePrintf (#13'Calling do_exit'#13#10);
  326. {$endif}
  327. SigTermHandlerActive := true; { to avoid that system_exit calls _exit }
  328. do_exit; { calls finalize units }
  329. if assigned (SetThreadDataAreaPtr) then
  330. SetThreadDataAreaPtr (oldPtr);
  331. _SetThreadGroupID (oldTG);
  332. {$ifdef DEBUG_MT}
  333. ConsolePrintf (#13'TermSigHandler: all done'#13#10);
  334. {$endif}
  335. end;
  336. procedure SysInitStdIO;
  337. begin
  338. { Setup stdin, stdout and stderr }
  339. StdInputHandle := _fileno (LONGINT (_GetStdIn^)); // GetStd** returns **FILE
  340. StdOutputHandle:= _fileno (LONGINT (_GetStdOut^));
  341. StdErrorHandle := _fileno (LONGINT (_GetStdErr^));
  342. OpenStdIO(Input,fmInput,StdInputHandle);
  343. OpenStdIO(Output,fmOutput,StdOutputHandle);
  344. OpenStdIO(StdOut,fmOutput,StdOutputHandle);
  345. {$ifdef StdErrToConsole}
  346. AssignStdErrConsole(StdErr);
  347. AssignStdErrConsole(ErrOutput);
  348. {$else}
  349. OpenStdIO(StdErr,fmOutput,StdErrorHandle);
  350. OpenStdIO(ErrOutput,fmOutput,StdErrorHandle);
  351. {$endif}
  352. end;
  353. function GetProcessID: SizeUInt;
  354. begin
  355. GetProcessID := SizeUInt (GetNlmHandle);
  356. end;
  357. {*****************************************************************************
  358. SystemUnit Initialization
  359. *****************************************************************************}
  360. Begin
  361. StackBottom := SPtr - StackLength;
  362. SigTermHandlerActive := false;
  363. NetwareCheckFunction := nil;
  364. NetwareMainThreadGroupID := _GetThreadGroupID;
  365. _Signal (_SIGTERM, @TermSigHandler);
  366. {$ifdef useLongNamespaceByDefault}
  367. if _getenv ('FPC_DISABLE_LONG_NAMESPACE') = nil then
  368. begin
  369. if _SetCurrentNameSpace (NW_NS_LONG) <> 255 then
  370. begin
  371. if _SetTargetNamespace (NW_NS_LONG) <> 255 then
  372. LFNSupport := true
  373. else
  374. _SetCurrentNameSpace (NW_NS_DOS);
  375. end;
  376. end;
  377. {$endif useLongNamespaceByDefault}
  378. { Setup heap }
  379. InitHeap;
  380. SysInitExceptions;
  381. { Reset IO Error }
  382. InOutRes:=0;
  383. ThreadID := _GetThreadID;
  384. {$ifdef DEBUG_MT}
  385. ConsolePrintf (#13'Start system, ThreadID: %x'#13#10,ThreadID);
  386. {$endif}
  387. SysInitStdIO;
  388. {Delphi Compatible}
  389. IsLibrary := FALSE;
  390. IsConsole := TRUE;
  391. ExitCode := 0;
  392. InitSystemThreads;
  393. {$ifdef HASVARIANT}
  394. initvariantmanager;
  395. {$endif HASVARIANT}
  396. {$ifdef HASWIDESTRING}
  397. initwidestringmanager;
  398. {$endif HASWIDESTRING}
  399. End.
  400. {
  401. $Log$
  402. Revision 1.36 2005-02-14 17:13:30 peter
  403. * truncate log
  404. Revision 1.35 2005/02/06 16:57:18 peter
  405. * threads for go32v2,os,emx,netware
  406. Revision 1.34 2005/02/01 20:22:49 florian
  407. * improved widestring infrastructure manager
  408. }