system.pp 14 KB

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