system.pp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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 FPC_IS_SYSTEM}
  16. {$define StdErrToConsole}
  17. {$define useLongNamespaceByDefault}
  18. {$define autoHeapRelease}
  19. {$define DISABLE_NO_THREAD_MANAGER}
  20. {$ifdef SYSTEMDEBUG}
  21. {$define SYSTEMEXCEPTIONDEBUG}
  22. {$endif SYSTEMDEBUG}
  23. {$ifdef cpui386}
  24. {$define Set_i386_Exception_handler}
  25. {$endif cpui386}
  26. { include system-independent routine headers }
  27. {$I systemh.inc}
  28. {Platform specific information}
  29. const
  30. LineEnding = #13#10;
  31. LFNSupport : boolean = false;
  32. DirectorySeparator = '/';
  33. DriveSeparator = ':';
  34. ExtensionSeparator = '.';
  35. PathSeparator = ';';
  36. AllowDirectorySeparators : set of char = ['\','/'];
  37. AllowDriveSeparators : set of char = [':'];
  38. { FileNameCaseSensitive and FileNameCasePreserving are defined separately below!!! }
  39. maxExitCode = 255;
  40. MaxPathLen = 256;
  41. AllFilesMask = '*';
  42. SharedSuffix = 'nlm';
  43. CONST
  44. { Default filehandles }
  45. UnusedHandle : THandle = -1;
  46. StdInputHandle : THandle = 0;
  47. StdOutputHandle : THandle = 0;
  48. StdErrorHandle : THandle = 0;
  49. FileNameCaseSensitive : boolean = false;
  50. FileNameCasePreserving: boolean = true; (* Not really correct on older Netware versions without the LFN support switched on... *)
  51. CtrlZMarksEOF: boolean = false; (* #26 not considered as end of file *)
  52. sLineBreak = LineEnding;
  53. DefaultTextLineBreakStyle : TTextLineBreakStyle = tlbsCRLF;
  54. TYPE
  55. TNWCheckFunction = procedure (var code : longint);
  56. VAR
  57. ArgC : INTEGER;
  58. ArgV : ppchar;
  59. NetwareCheckFunction : TNWCheckFunction;
  60. NetwareMainThreadGroupID: longint;
  61. NetwareUnloadProc : pointer = nil; {like exitProc but for nlm unload only}
  62. CONST
  63. envp : ppchar = nil; {dummy to make heaptrc happy}
  64. procedure ConsolePrintf (FormatStr : PCHAR; Param : LONGINT); CDecl; external 'clib' name 'printf';
  65. procedure ConsolePrintf (FormatStr : PCHAR; Param : pchar); CDecl; external 'clib' name 'printf';
  66. procedure ConsolePrintf (FormatStr : PCHAR; P1,P2 : LONGINT); CDecl; external 'clib' name 'printf';
  67. procedure ConsolePrintf (FormatStr : PCHAR; P1,P2,P3 : LONGINT); CDecl; external 'clib' name 'printf';
  68. procedure ConsolePrintf (FormatStr : PCHAR); CDecl; external 'clib' name 'printf';
  69. // this gives internal compiler error 200404181
  70. // procedure ConsolePrintf (FormatStr : PCHAR; Param : array of const); CDecl; EXTERNAL 'clib' name 'ConsolePrintf';
  71. procedure __EnterDebugger; cdecl; external 'clib' name 'EnterDebugger';
  72. type
  73. TSysCloseAllRemainingSemaphores = procedure;
  74. TSysReleaseThreadVars = procedure;
  75. TSysSetThreadDataAreaPtr = function (newPtr:pointer):pointer;
  76. procedure NWSysSetThreadFunctions (crs:TSysCloseAllRemainingSemaphores;
  77. rtv:TSysReleaseThreadVars;
  78. stdata:TSysSetThreadDataAreaPtr);
  79. function NWGetCodeStart : pointer; // needed for lineinfo
  80. implementation
  81. { Indicate that stack checking is taken care by OS}
  82. {$DEFINE NO_GENERIC_STACK_CHECK}
  83. { include system independent routines }
  84. {$I system.inc}
  85. //procedure __EnterDebugger; cdecl; external 'clib' name 'EnterDebugger';
  86. procedure PASCALMAIN;external name 'PASCALMAIN';
  87. procedure fpc_do_exit;external name 'FPC_DO_EXIT';
  88. {*****************************************************************************
  89. Startup
  90. *****************************************************************************}
  91. PROCEDURE nlm_main (_ArgC : LONGINT; _ArgV : ppchar); CDECL; [public,alias: '_nlm_main'];
  92. BEGIN
  93. // Initialize of BSS now done in nwpre
  94. ArgC := _ArgC;
  95. ArgV := _ArgV;
  96. fpc_threadvar_relocate_proc := nil;
  97. PASCALMAIN;
  98. END;
  99. var dottext : ptruint; external name '__text_start__';
  100. function NWGetCodeStart : pointer; // needed for lineinfo
  101. begin
  102. NWGetCodeStart := @dottext;
  103. end;
  104. {*****************************************************************************
  105. System Dependent Exit code
  106. *****************************************************************************}
  107. var SigTermHandlerActive : boolean;
  108. Procedure system_exit;
  109. begin
  110. if TerminatingThreadID <> 0 then
  111. if TerminatingThreadID <> ThreadId then
  112. if TerminatingThreadID <> _GetThreadID then
  113. begin
  114. {$ifdef DEBUG_MT}
  115. ConsolePrintf ('Terminating Thread %x because halt was called while Thread %x terminates nlm'#13#10,_GetThreadId,TerminatingThreadId);
  116. {$endif}
  117. ExitThread (EXIT_THREAD,0);
  118. // only for the case ExitThread fails
  119. while true do
  120. _ThreadSwitchWithDelay;
  121. end;
  122. if assigned (CloseAllRemainingSemaphores) then CloseAllRemainingSemaphores;
  123. if assigned (ReleaseThreadVars) then ReleaseThreadVars;
  124. {$ifdef autoHeapRelease}
  125. FreeSbrkMem; { free memory allocated by heapmanager }
  126. {$endif}
  127. if not SigTermHandlerActive then
  128. begin
  129. if ExitCode <> 0 Then { otherwise we dont see runtime-errors }
  130. _SetAutoScreenDestructionMode (false);
  131. _exit (ExitCode);
  132. end;
  133. end;
  134. {*****************************************************************************
  135. Stack check code
  136. *****************************************************************************}
  137. const StackErr : boolean = false;
  138. procedure fpc_stackcheck(stack_size:SizeUInt);[public,alias:'FPC_STACKCHECK']; compilerproc;
  139. {
  140. called when trying to get local stack if the compiler directive $S
  141. is set this function must preserve all registers
  142. With a 2048 byte safe area used to write to StdIo without crossing
  143. the stack boundary
  144. }
  145. begin
  146. if StackErr then exit; // avoid recursive calls
  147. asm
  148. pusha
  149. end;
  150. stackerr := ( _stackavail < stack_size + 2048);
  151. asm
  152. popa
  153. end;
  154. if not StackErr then exit;
  155. StackErr := true;
  156. HandleError (202);
  157. end;
  158. {*****************************************************************************
  159. ParamStr/Randomize
  160. *****************************************************************************}
  161. { number of args }
  162. function paramcount : longint;
  163. begin
  164. paramcount := argc - 1;
  165. end;
  166. { argument number l }
  167. function paramstr(l : longint) : string;
  168. begin
  169. if (l>=0) and (l+1<=argc) then
  170. begin
  171. paramstr:=strpas(argv[l]);
  172. if l = 0 then // fix nlm path
  173. begin
  174. DoDirSeparators(paramstr);
  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. internal_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. initunicodestringmanager;
  390. SysInitStdIO;
  391. {Delphi Compatible}
  392. IsConsole := TRUE;
  393. ExitCode := 0;
  394. InitSystemThreads;
  395. InitSystemDynLibs;
  396. End.