system.pp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 1999-2006 by Florian Klaempfl and Pavel Ozerski
  4. member of the Free Pascal development team.
  5. FPC Pascal system unit for the Win64 API.
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. **********************************************************************}
  12. unit System;
  13. interface
  14. { $define SYSTEMEXCEPTIONDEBUG}
  15. {$ifdef SYSTEMDEBUG}
  16. {$define SYSTEMEXCEPTIONDEBUG}
  17. {$endif SYSTEMDEBUG}
  18. {$define DISABLE_NO_THREAD_MANAGER}
  19. {$define HAS_WIDESTRINGMANAGER}
  20. { include system-independent routine headers }
  21. {$I systemh.inc}
  22. const
  23. LineEnding = #13#10;
  24. LFNSupport = true;
  25. DirectorySeparator = '\';
  26. DriveSeparator = ':';
  27. ExtensionSeparator = '.';
  28. PathSeparator = ';';
  29. AllowDirectorySeparators : set of char = ['\','/'];
  30. AllowDriveSeparators : set of char = [':'];
  31. { FileNameCaseSensitive is defined separately below!!! }
  32. maxExitCode = 65535;
  33. MaxPathLen = 260;
  34. AllFilesMask = '*';
  35. type
  36. PEXCEPTION_FRAME = ^TEXCEPTION_FRAME;
  37. TEXCEPTION_FRAME = record
  38. next : PEXCEPTION_FRAME;
  39. handler : pointer;
  40. end;
  41. const
  42. { Default filehandles }
  43. UnusedHandle : THandle = THandle(-1);
  44. StdInputHandle : THandle = 0;
  45. StdOutputHandle : THandle = 0;
  46. StdErrorHandle : THandle = 0;
  47. System_exception_frame : PEXCEPTION_FRAME =nil;
  48. FileNameCaseSensitive : boolean = true;
  49. CtrlZMarksEOF: boolean = true; (* #26 is considered as end of file *)
  50. sLineBreak = LineEnding;
  51. DefaultTextLineBreakStyle : TTextLineBreakStyle = tlbsCRLF;
  52. type
  53. TStartupInfo = record
  54. cb : longint;
  55. lpReserved : Pointer;
  56. lpDesktop : Pointer;
  57. lpTitle : Pointer;
  58. dwX : longint;
  59. dwY : longint;
  60. dwXSize : longint;
  61. dwYSize : longint;
  62. dwXCountChars : longint;
  63. dwYCountChars : longint;
  64. dwFillAttribute : longint;
  65. dwFlags : longint;
  66. wShowWindow : Word;
  67. cbReserved2 : Word;
  68. lpReserved2 : Pointer;
  69. hStdInput : THandle;
  70. hStdOutput : THandle;
  71. hStdError : THandle;
  72. end;
  73. var
  74. { C compatible arguments }
  75. argc : longint;
  76. argv : ppchar;
  77. { Win32 Info }
  78. startupinfo : tstartupinfo;
  79. StartupConsoleMode : dword;
  80. MainInstance : qword;
  81. cmdshow : longint;
  82. DLLreason,DLLparam:longint;
  83. const
  84. hprevinst: qword=0;
  85. type
  86. TDLL_Entry_Hook = procedure (dllparam : longint);
  87. const
  88. Dll_Process_Detach_Hook : TDLL_Entry_Hook = nil;
  89. Dll_Thread_Attach_Hook : TDLL_Entry_Hook = nil;
  90. Dll_Thread_Detach_Hook : TDLL_Entry_Hook = nil;
  91. Const
  92. { it can be discussed whether fmShareDenyNone means read and write or read, write and delete, see
  93. also http://bugs.freepascal.org/view.php?id=8898, this allows users to configure the used
  94. value
  95. }
  96. fmShareDenyNoneFlags : DWord = 3;
  97. implementation
  98. var
  99. SysInstance : qword;public;
  100. { include system independent routines }
  101. {$I system.inc}
  102. {*****************************************************************************
  103. System Dependent Exit code
  104. *****************************************************************************}
  105. procedure install_exception_handlers;forward;
  106. procedure remove_exception_handlers;forward;
  107. procedure PascalMain;stdcall;external name 'PASCALMAIN';
  108. procedure fpc_do_exit;stdcall;external name 'FPC_DO_EXIT';
  109. Procedure ExitDLL(Exitcode : longint); forward;
  110. Procedure system_exit;
  111. begin
  112. { don't call ExitProcess inside
  113. the DLL exit code !!
  114. This crashes Win95 at least PM }
  115. if IsLibrary then
  116. ExitDLL(ExitCode);
  117. if not IsConsole then
  118. begin
  119. Close(stderr);
  120. Close(stdout);
  121. Close(erroutput);
  122. Close(Input);
  123. Close(Output);
  124. { what about Input and Output ?? PM }
  125. { now handled, FPK }
  126. end;
  127. remove_exception_handlers;
  128. { call exitprocess, with cleanup as required }
  129. ExitProcess(exitcode);
  130. end;
  131. var
  132. { old compilers emitted a reference to _fltused if a module contains
  133. floating type code so the linker could leave away floating point
  134. libraries or not. VC does this as well so we need to define this
  135. symbol as well (FK)
  136. }
  137. _fltused : int64;cvar;public;
  138. { value of the stack segment
  139. to check if the call stack can be written on exceptions }
  140. _SS : Cardinal;
  141. procedure Exe_entry;[public,alias:'_FPC_EXE_Entry'];
  142. var
  143. ST : pointer;
  144. begin
  145. IsLibrary:=false;
  146. { install the handlers for exe only ?
  147. or should we install them for DLL also ? (PM) }
  148. install_exception_handlers;
  149. ExitCode:=0;
  150. asm
  151. movq %rsp,%rax
  152. movq %rax,st
  153. end;
  154. StackTop:=st;
  155. asm
  156. xorq %rax,%rax
  157. movw %ss,%ax
  158. movl %eax,_SS(%rip)
  159. movq %rbp,%rsi
  160. xorq %rbp,%rbp
  161. call PASCALMAIN
  162. movq %rsi,%rbp
  163. end ['RSI','RBP']; { <-- specifying RSI allows compiler to save/restore it properly }
  164. { if we pass here there was no error ! }
  165. system_exit;
  166. end;
  167. function Dll_entry{$ifdef FPC_HAS_INDIRECT_MAIN_INFORMATION}(const info : TEntryInformation){$endif FPC_HAS_INDIRECT_MAIN_INFORMATION} : longbool;forward;
  168. procedure _FPC_DLLMainCRTStartup(_hinstance : qword;_dllreason,_dllparam:longint);stdcall;public name '_DLLMainCRTStartup';
  169. begin
  170. IsConsole:=true;
  171. sysinstance:=_hinstance;
  172. dllreason:=_dllreason;
  173. dllparam:=_dllparam;
  174. DLL_Entry;
  175. end;
  176. procedure _FPC_DLLWinMainCRTStartup(_hinstance : qword;_dllreason,_dllparam:longint);stdcall;public name '_DLLWinMainCRTStartup';
  177. begin
  178. IsConsole:=false;
  179. sysinstance:=_hinstance;
  180. dllreason:=_dllreason;
  181. dllparam:=_dllparam;
  182. DLL_Entry;
  183. end;
  184. function is_prefetch(p : pointer) : boolean;
  185. var
  186. a : array[0..15] of byte;
  187. doagain : boolean;
  188. instrlo,instrhi,opcode : byte;
  189. i : longint;
  190. begin
  191. result:=false;
  192. { read memory savely without causing another exeception }
  193. if not(ReadProcessMemory(GetCurrentProcess,p,@a,sizeof(a),nil)) then
  194. exit;
  195. i:=0;
  196. doagain:=true;
  197. while doagain and (i<15) do
  198. begin
  199. opcode:=a[i];
  200. instrlo:=opcode and $f;
  201. instrhi:=opcode and $f0;
  202. case instrhi of
  203. { prefix? }
  204. $20,$30:
  205. doagain:=(instrlo and 7)=6;
  206. $60:
  207. doagain:=(instrlo and $c)=4;
  208. $f0:
  209. doagain:=instrlo in [0,2,3];
  210. $0:
  211. begin
  212. result:=(instrlo=$f) and (a[i+1] in [$d,$18]);
  213. exit;
  214. end;
  215. else
  216. doagain:=false;
  217. end;
  218. inc(i);
  219. end;
  220. end;
  221. {******************************************************************************}
  222. { include code common with win64 }
  223. {$I syswin.inc}
  224. {******************************************************************************}
  225. //
  226. // Hardware exception handling
  227. //
  228. {$I seh64.inc}
  229. type
  230. TVectoredExceptionHandler = function (excep : PExceptionPointers) : Longint;
  231. function AddVectoredExceptionHandler(FirstHandler : DWORD;VectoredHandler : TVectoredExceptionHandler) : longint;
  232. external 'kernel32' name 'AddVectoredExceptionHandler';
  233. const
  234. MaxExceptionLevel = 16;
  235. exceptLevel : Byte = 0;
  236. var
  237. exceptRip : array[0..MaxExceptionLevel-1] of Int64;
  238. exceptError : array[0..MaxExceptionLevel-1] of Byte;
  239. resetFPU : array[0..MaxExceptionLevel-1] of Boolean;
  240. {$ifdef SYSTEMEXCEPTIONDEBUG}
  241. procedure DebugHandleErrorAddrFrame(error : longint; addr, frame : pointer);
  242. begin
  243. if IsConsole then
  244. begin
  245. write(stderr,'HandleErrorAddrFrame(error=',error);
  246. write(stderr,',addr=',hexstr(int64(addr),16));
  247. writeln(stderr,',frame=',hexstr(int64(frame),16),')');
  248. end;
  249. HandleErrorAddrFrame(error,addr,frame);
  250. end;
  251. {$endif SYSTEMEXCEPTIONDEBUG}
  252. procedure JumpToHandleErrorFrame;
  253. var
  254. rip, rbp : int64;
  255. error : longint;
  256. begin
  257. // save ebp
  258. asm
  259. movq (%rbp),%rax
  260. movq %rax,rbp
  261. end;
  262. if exceptLevel>0 then
  263. dec(exceptLevel);
  264. rip:=exceptRip[exceptLevel];
  265. error:=exceptError[exceptLevel];
  266. {$ifdef SYSTEMEXCEPTIONDEBUG}
  267. if IsConsole then
  268. writeln(stderr,'In JumpToHandleErrorFrame error=',error);
  269. {$endif SYSTEMEXCEPTIONDEBUG}
  270. if resetFPU[exceptLevel] then
  271. SysResetFPU;
  272. { build a fake stack }
  273. asm
  274. movq rbp,%r8
  275. movq rip,%rdx
  276. movl error,%ecx
  277. pushq rip
  278. movq rbp,%rbp // Change frame pointer
  279. {$ifdef SYSTEMEXCEPTIONDEBUG}
  280. jmpl DebugHandleErrorAddrFrame
  281. {$else not SYSTEMEXCEPTIONDEBUG}
  282. jmpl HandleErrorAddrFrame
  283. {$endif SYSTEMEXCEPTIONDEBUG}
  284. end;
  285. end;
  286. function syswin64_x86_64_exception_handler(excep : PExceptionPointers) : Longint;public;
  287. var
  288. res: longint;
  289. err: byte;
  290. must_reset_fpu: boolean;
  291. begin
  292. res:=EXCEPTION_CONTINUE_SEARCH;
  293. {$ifdef SYSTEMEXCEPTIONDEBUG}
  294. if IsConsole then
  295. Writeln(stderr,'syswin64_x86_64_exception_handler called');
  296. {$endif SYSTEMEXCEPTIONDEBUG}
  297. if excep^.ContextRecord^.SegSs=_SS then
  298. begin
  299. err := 0;
  300. must_reset_fpu := true;
  301. {$ifdef SYSTEMEXCEPTIONDEBUG}
  302. if IsConsole then Writeln(stderr,'Exception ',
  303. hexstr(excep^.ExceptionRecord^.ExceptionCode,8));
  304. {$endif SYSTEMEXCEPTIONDEBUG}
  305. case cardinal(excep^.ExceptionRecord^.ExceptionCode) of
  306. STATUS_INTEGER_DIVIDE_BY_ZERO,
  307. STATUS_FLOAT_DIVIDE_BY_ZERO :
  308. err := 200;
  309. STATUS_ARRAY_BOUNDS_EXCEEDED :
  310. begin
  311. err := 201;
  312. must_reset_fpu := false;
  313. end;
  314. STATUS_STACK_OVERFLOW :
  315. begin
  316. err := 202;
  317. must_reset_fpu := false;
  318. end;
  319. STATUS_FLOAT_OVERFLOW :
  320. err := 205;
  321. STATUS_FLOAT_DENORMAL_OPERAND,
  322. STATUS_FLOAT_UNDERFLOW :
  323. err := 206;
  324. { excep^.ContextRecord^.FloatSave.StatusWord := excep^.ContextRecord^.FloatSave.StatusWord and $ffffff00;}
  325. STATUS_FLOAT_INEXACT_RESULT,
  326. STATUS_FLOAT_INVALID_OPERATION,
  327. STATUS_FLOAT_STACK_CHECK :
  328. err := 207;
  329. STATUS_INTEGER_OVERFLOW :
  330. begin
  331. err := 215;
  332. must_reset_fpu := false;
  333. end;
  334. STATUS_ILLEGAL_INSTRUCTION:
  335. err := 216;
  336. STATUS_ACCESS_VIOLATION:
  337. { Athlon prefetch bug? }
  338. if is_prefetch(pointer(excep^.ContextRecord^.rip)) then
  339. begin
  340. { if yes, then retry }
  341. excep^.ExceptionRecord^.ExceptionCode := 0;
  342. res:=EXCEPTION_CONTINUE_EXECUTION;
  343. end
  344. else
  345. err := 216;
  346. STATUS_CONTROL_C_EXIT:
  347. err := 217;
  348. STATUS_PRIVILEGED_INSTRUCTION:
  349. begin
  350. err := 218;
  351. must_reset_fpu := false;
  352. end;
  353. else
  354. begin
  355. if ((excep^.ExceptionRecord^.ExceptionCode and SEVERITY_ERROR) = SEVERITY_ERROR) then
  356. err := 217
  357. else
  358. { pass through exceptions which aren't an error. The problem is that vectored handlers
  359. always are called before structured ones so we see also internal exceptions of libraries.
  360. I wonder if there is a better solution (FK)
  361. }
  362. res:=EXCEPTION_CONTINUE_SEARCH;
  363. end;
  364. end;
  365. if (err <> 0) and (exceptLevel < MaxExceptionLevel) then
  366. begin
  367. exceptRip[exceptLevel] := excep^.ContextRecord^.Rip;
  368. exceptError[exceptLevel] := err;
  369. resetFPU[exceptLevel] := must_reset_fpu;
  370. inc(exceptLevel);
  371. excep^.ContextRecord^.Rip := Int64(@JumpToHandleErrorFrame);
  372. excep^.ExceptionRecord^.ExceptionCode := 0;
  373. res := EXCEPTION_CONTINUE_EXECUTION;
  374. {$ifdef SYSTEMEXCEPTIONDEBUG}
  375. if IsConsole then begin
  376. writeln(stderr,'Exception Continue Exception set at ',
  377. hexstr(exceptRip[exceptLevel-1],16));
  378. writeln(stderr,'Rip changed to ',
  379. hexstr(int64(@JumpToHandleErrorFrame),16), ' error=', err);
  380. end;
  381. {$endif SYSTEMEXCEPTIONDEBUG}
  382. end;
  383. end;
  384. syswin64_x86_64_exception_handler := res;
  385. end;
  386. procedure install_exception_handlers;
  387. begin
  388. AddVectoredExceptionHandler(1,@syswin64_x86_64_exception_handler);
  389. end;
  390. procedure remove_exception_handlers;
  391. begin
  392. end;
  393. procedure fpc_cpucodeinit;
  394. begin
  395. end;
  396. procedure LinkIn(p1,p2,p3: Pointer); inline;
  397. begin
  398. end;
  399. procedure _FPC_mainCRTStartup;stdcall;public name '_mainCRTStartup';
  400. begin
  401. IsConsole:=true;
  402. GetConsoleMode(GetStdHandle((Std_Input_Handle)),@StartupConsoleMode);
  403. {$ifdef FPC_USE_TLS_DIRECTORY}
  404. LinkIn(@_tls_used,@FreePascal_TLS_callback,@FreePascal_end_of_TLS_callback);
  405. {$endif FPC_USE_TLS_DIRECTORY}
  406. Exe_entry;
  407. end;
  408. procedure _FPC_WinMainCRTStartup;stdcall;public name '_WinMainCRTStartup';
  409. begin
  410. IsConsole:=false;
  411. {$ifdef FPC_USE_TLS_DIRECTORY}
  412. LinkIn(@_tls_used,@FreePascal_TLS_callback,@FreePascal_end_of_TLS_callback);
  413. {$endif FPC_USE_TLS_DIRECTORY}
  414. Exe_entry;
  415. end;
  416. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt;assembler;
  417. asm
  418. movq %gs:(8),%rax
  419. subq %gs:(16),%rax
  420. end;
  421. begin
  422. { pass dummy value }
  423. StackLength := CheckInitialStkLen($1000000);
  424. StackBottom := StackTop - StackLength;
  425. { get some helpful informations }
  426. GetStartupInfo(@startupinfo);
  427. { some misc Win32 stuff }
  428. if not IsLibrary then
  429. SysInstance:=getmodulehandle(nil);
  430. MainInstance:=SysInstance;
  431. cmdshow:=startupinfo.wshowwindow;
  432. { Setup heap and threading, these may be already initialized from TLS callback }
  433. if not Assigned(CurrentTM.BeginThread) then
  434. begin
  435. InitHeap;
  436. InitSystemThreads;
  437. end;
  438. SysInitExceptions;
  439. { setup fastmove stuff }
  440. fpc_cpucodeinit;
  441. initwidestringmanager;
  442. initunicodestringmanager;
  443. InitWin32Widestrings;
  444. SysInitStdIO;
  445. { Arguments }
  446. setup_arguments;
  447. { Reset IO Error }
  448. InOutRes:=0;
  449. ProcessID := GetCurrentProcessID;
  450. { Reset internal error variable }
  451. errno:=0;
  452. initvariantmanager;
  453. DispCallByIDProc:=@DoDispCallByIDError;
  454. end.