system.pp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. SharedSuffix = 'nlm';
  42. CONST
  43. { Default filehandles }
  44. UnusedHandle : THandle = -1;
  45. StdInputHandle : THandle = 0;
  46. StdOutputHandle : THandle = 0;
  47. StdErrorHandle : THandle = 0;
  48. FileNameCaseSensitive : boolean = false;
  49. FileNameCasePreserving: boolean = true; (* Not really correct on older Netware versions without the LFN support switched on... *)
  50. CtrlZMarksEOF: boolean = false; (* #26 not considered as end of file *)
  51. sLineBreak = LineEnding;
  52. DefaultTextLineBreakStyle : TTextLineBreakStyle = tlbsCRLF;
  53. TYPE
  54. TNWCheckFunction = procedure (var code : longint);
  55. VAR
  56. ArgC : INTEGER;
  57. ArgV : ppchar;
  58. NetwareCheckFunction : TNWCheckFunction;
  59. NetwareMainThreadGroupID: longint;
  60. NetwareUnloadProc : pointer = nil; {like exitProc but for nlm unload only}
  61. CONST
  62. envp : ppchar = nil; {dummy to make heaptrc happy}
  63. procedure ConsolePrintf (FormatStr : PCHAR; Param : LONGINT); CDecl; external 'clib' name 'printf';
  64. procedure ConsolePrintf (FormatStr : PCHAR; Param : pchar); CDecl; external 'clib' name 'printf';
  65. procedure ConsolePrintf (FormatStr : PCHAR; P1,P2 : LONGINT); CDecl; external 'clib' name 'printf';
  66. procedure ConsolePrintf (FormatStr : PCHAR; P1,P2,P3 : LONGINT); CDecl; external 'clib' name 'printf';
  67. procedure ConsolePrintf (FormatStr : PCHAR); CDecl; external 'clib' name 'printf';
  68. // this gives internal compiler error 200404181
  69. // procedure ConsolePrintf (FormatStr : PCHAR; Param : array of const); CDecl; EXTERNAL 'clib' name 'ConsolePrintf';
  70. procedure __EnterDebugger; cdecl; external 'clib' name 'EnterDebugger';
  71. type
  72. TSysCloseAllRemainingSemaphores = procedure;
  73. TSysReleaseThreadVars = procedure;
  74. TSysSetThreadDataAreaPtr = function (newPtr:pointer):pointer;
  75. procedure NWSysSetThreadFunctions (crs:TSysCloseAllRemainingSemaphores;
  76. rtv:TSysReleaseThreadVars;
  77. stdata:TSysSetThreadDataAreaPtr);
  78. function NWGetCodeStart : pointer; // needed for lineinfo
  79. implementation
  80. { Indicate that stack checking is taken care by OS}
  81. {$DEFINE NO_GENERIC_STACK_CHECK}
  82. { include system independent routines }
  83. {$I system.inc}
  84. //procedure __EnterDebugger; cdecl; external 'clib' name 'EnterDebugger';
  85. procedure PASCALMAIN;external name 'PASCALMAIN';
  86. procedure fpc_do_exit;external name 'FPC_DO_EXIT';
  87. {*****************************************************************************
  88. Startup
  89. *****************************************************************************}
  90. PROCEDURE nlm_main (_ArgC : LONGINT; _ArgV : ppchar); CDECL; [public,alias: '_nlm_main'];
  91. BEGIN
  92. // Initialize of BSS now done in nwpre
  93. ArgC := _ArgC;
  94. ArgV := _ArgV;
  95. fpc_threadvar_relocate_proc := nil;
  96. PASCALMAIN;
  97. END;
  98. var dottext : ptruint; external name '__text_start__';
  99. function NWGetCodeStart : pointer; // needed for lineinfo
  100. begin
  101. NWGetCodeStart := @dottext;
  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 fpc_stackcheck(stack_size:SizeUInt);[public,alias:'FPC_STACKCHECK']; compilerproc;
  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. DoDirSeparators(paramstr);
  174. end;
  175. end else
  176. paramstr:='';
  177. end;
  178. { set randseed to a new pseudo random value }
  179. procedure randomize;
  180. begin
  181. randseed := _time (NIL);
  182. end;
  183. {*****************************************************************************
  184. Thread Handling
  185. *****************************************************************************}
  186. { if return-value is <> 0, netware shows the message
  187. Unload Anyway ?
  188. To Disable unload at all, SetNLMDontUnloadFlag can be used on
  189. Netware >= 4.0 }
  190. function CheckFunction : longint; CDECL; [public,alias: 'FPC_NW_CHECKFUNCTION'];
  191. var oldTG:longint;
  192. oldPtr: pointer;
  193. begin
  194. if assigned (NetwareCheckFunction) then
  195. begin
  196. { this function is called without clib context, to allow clib
  197. calls, we set the thread group id before calling the
  198. user-function }
  199. oldTG := _SetThreadGroupID (NetwareMainThreadGroupID);
  200. { to allow use of threadvars, we simply set the threadvar-memory
  201. from the main thread }
  202. if assigned (SetThreadDataAreaPtr) then
  203. oldPtr := SetThreadDataAreaPtr (NIL); { nil means main threadvars }
  204. result := 0;
  205. NetwareCheckFunction (result);
  206. if assigned (SetThreadDataAreaPtr) then
  207. SetThreadDataAreaPtr (oldPtr);
  208. _SetThreadGroupID (oldTG);
  209. end else
  210. result := 0;
  211. end;
  212. {$ifdef StdErrToConsole}
  213. var ConsoleBuff : array [0..512] of char;
  214. Function ConsoleWrite(Var F: TextRec): Integer;
  215. var
  216. i : longint;
  217. Begin
  218. if F.BufPos>0 then
  219. begin
  220. if F.BufPos>sizeof(ConsoleBuff)-1 then
  221. i:=sizeof(ConsoleBuff)-1
  222. else
  223. i:=F.BufPos;
  224. Move(F.BufPtr^,ConsoleBuff,i);
  225. ConsoleBuff[i] := #0;
  226. ConsolePrintf(@ConsoleBuff[0]);
  227. end;
  228. F.BufPos:=0;
  229. ConsoleWrite := 0;
  230. End;
  231. Function ConsoleClose(Var F: TextRec): Integer;
  232. begin
  233. ConsoleClose:=0;
  234. end;
  235. Function ConsoleOpen(Var F: TextRec): Integer;
  236. Begin
  237. TextRec(F).InOutFunc:=@ConsoleWrite;
  238. TextRec(F).FlushFunc:=@ConsoleWrite;
  239. TextRec(F).CloseFunc:=@ConsoleClose;
  240. ConsoleOpen:=0;
  241. End;
  242. procedure AssignStdErrConsole(Var T: Text);
  243. begin
  244. Assign(T,'');
  245. TextRec(T).OpenFunc:=@ConsoleOpen;
  246. Rewrite(T);
  247. end;
  248. {$endif}
  249. { this will be called if the nlm is unloaded. It will NOT be
  250. called if the program exits i.e. with halt.
  251. Halt (or _exit) can not be called from this callback procedure }
  252. procedure TermSigHandler (Sig:longint); CDecl;
  253. var oldTG : longint;
  254. oldPtr: pointer;
  255. err : longint;
  256. current_exit : procedure;
  257. ThreadName : array [0..20] of char;
  258. HadExitProc : boolean;
  259. Count : longint;
  260. begin
  261. oldTG := _SetThreadGroupID (NetwareMainThreadGroupID); { this is only needed for nw 3.11 }
  262. { _GetThreadDataAreaPtr will not be valid because the signal
  263. handler is called by netware with a differnt thread. To avoid
  264. problems in the exit routines, we set the data of the main thread
  265. here }
  266. if assigned (SetThreadDataAreaPtr) then
  267. oldPtr := SetThreadDataAreaPtr (NIL); { nil means main thread }
  268. {this signal handler is called within the console command
  269. thread, the main thread is still running. Via NetwareUnloadProc
  270. running threads may terminate itself}
  271. TerminatingThreadID := _GetThreadID;
  272. {$ifdef DEBUG_MT}
  273. ConsolePrintf (#13'TermSigHandler Called, MainThread:%x, OurThread: %x'#13#10,ThreadId,TerminatingThreadId);
  274. if NetwareUnloadProc <> nil then
  275. ConsolePrintf (#13'Calling NetwareUnloadProcs'#13#10);
  276. {$endif}
  277. HadExitProc := false;
  278. {we need to finalize winock to release threads
  279. waiting on a blocking socket call. If that thread
  280. calls halt, we have to avoid that unit finalization
  281. is called by that thread because we are doing it
  282. here
  283. like the old exitProc, mainly to allow winsock to release threads
  284. blocking in a winsock calls }
  285. while NetwareUnloadProc<>nil Do
  286. Begin
  287. InOutRes:=0;
  288. current_exit:=tProcedure(NetwareUnloadProc);
  289. NetwareUnloadProc:=nil;
  290. current_exit();
  291. _ThreadSwitchWithDelay;
  292. hadExitProc := true;
  293. End;
  294. err := 0;
  295. if hadExitProc then
  296. begin {give the main thread a little bit of time to terminate}
  297. count := 0;
  298. repeat
  299. err := _GetThreadName(ThreadID,ThreadName);
  300. if err = 0 then _Delay (200);
  301. inc(count);
  302. until (err <> 0) or (count > 100); {about 20 seconds}
  303. {$ifdef DEBUG_MT}
  304. if err = 0 then
  305. ConsolePrintf (#13,'Main Thread not terminated'#13#10)
  306. else
  307. ConsolePrintf (#13'Main Thread has ended'#13#10);
  308. {$endif}
  309. end;
  310. if err = 0 then
  311. {$ifdef DEBUG_MT}
  312. begin
  313. err := _SuspendThread(ThreadId);
  314. ConsolePrintf (#13'SuspendThread(%x) returned %d'#13#10,ThreadId,err);
  315. end;
  316. {$else}
  317. _SuspendThread(ThreadId);
  318. {$endif}
  319. _ThreadSwitchWithDelay;
  320. {$ifdef DEBUG_MT}
  321. ConsolePrintf (#13'Calling do_exit'#13#10);
  322. {$endif}
  323. SigTermHandlerActive := true; { to avoid that system_exit calls _exit }
  324. internal_do_exit; { calls finalize units }
  325. if assigned (SetThreadDataAreaPtr) then
  326. SetThreadDataAreaPtr (oldPtr);
  327. _SetThreadGroupID (oldTG);
  328. {$ifdef DEBUG_MT}
  329. ConsolePrintf (#13'TermSigHandler: all done'#13#10);
  330. {$endif}
  331. end;
  332. procedure SysInitStdIO;
  333. begin
  334. { Setup stdin, stdout and stderr }
  335. StdInputHandle := _fileno (LONGINT (_GetStdIn^)); // GetStd** returns **FILE
  336. StdOutputHandle:= _fileno (LONGINT (_GetStdOut^));
  337. StdErrorHandle := _fileno (LONGINT (_GetStdErr^));
  338. OpenStdIO(Input,fmInput,StdInputHandle);
  339. OpenStdIO(Output,fmOutput,StdOutputHandle);
  340. OpenStdIO(StdOut,fmOutput,StdOutputHandle);
  341. {$ifdef StdErrToConsole}
  342. AssignStdErrConsole(StdErr);
  343. AssignStdErrConsole(ErrOutput);
  344. {$else}
  345. OpenStdIO(StdErr,fmOutput,StdErrorHandle);
  346. OpenStdIO(ErrOutput,fmOutput,StdErrorHandle);
  347. {$endif}
  348. end;
  349. function GetProcessID: SizeUInt;
  350. begin
  351. GetProcessID := SizeUInt (GetNlmHandle);
  352. end;
  353. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt;
  354. begin
  355. result := stklen;
  356. end;
  357. {*****************************************************************************
  358. SystemUnit Initialization
  359. *****************************************************************************}
  360. Begin
  361. StackLength := CheckInitialStkLen(initialstklen);
  362. StackBottom := SPtr - StackLength;
  363. SigTermHandlerActive := false;
  364. NetwareCheckFunction := nil;
  365. NetwareMainThreadGroupID := _GetThreadGroupID;
  366. _Signal (_SIGTERM, @TermSigHandler);
  367. {$ifdef useLongNamespaceByDefault}
  368. if _getenv ('FPC_DISABLE_LONG_NAMESPACE') = nil then
  369. begin
  370. if _SetCurrentNameSpace (NW_NS_LONG) <> 255 then
  371. begin
  372. if _SetTargetNamespace (NW_NS_LONG) <> 255 then
  373. LFNSupport := true
  374. else
  375. _SetCurrentNameSpace (NW_NS_DOS);
  376. end;
  377. end;
  378. {$endif useLongNamespaceByDefault}
  379. { Setup heap }
  380. InitHeap;
  381. SysInitExceptions;
  382. { Reset IO Error }
  383. InOutRes:=0;
  384. ThreadID := _GetThreadID;
  385. {$ifdef DEBUG_MT}
  386. ConsolePrintf (#13'Start system, ThreadID: %x'#13#10,ThreadID);
  387. {$endif}
  388. initunicodestringmanager;
  389. SysInitStdIO;
  390. {Delphi Compatible}
  391. IsConsole := TRUE;
  392. ExitCode := 0;
  393. InitSystemThreads;
  394. InitSystemDynLibs;
  395. End.