system.pp 14 KB

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