system.pp 13 KB

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