system.pp 14 KB

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