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