system.pp 14 KB

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