system.pp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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. begin
  166. IsLibrary:=false;
  167. { install the handlers for exe only ?
  168. or should we install them for DLL also ? (PM) }
  169. {$ifndef FPC_USE_WIN64_SEH}
  170. install_exception_handlers;
  171. {$endif FPC_USE_WIN64_SEH}
  172. ExitCode:=0;
  173. asm
  174. xorq %rax,%rax
  175. movw %ss,%ax
  176. movl %eax,_SS(%rip)
  177. movq %rbp,%rsi
  178. xorq %rbp,%rbp
  179. {$ifdef FPC_USE_WIN64_SEH}
  180. lea PASCALMAIN(%rip),%rcx
  181. call main_wrapper
  182. {$else FPC_USE_WIN64_SEH}
  183. call PASCALMAIN
  184. {$endif FPC_USE_WIN64_SEH}
  185. movq %rsi,%rbp
  186. end ['RSI','RBP']; { <-- specifying RSI allows compiler to save/restore it properly }
  187. { if we pass here there was no error ! }
  188. system_exit;
  189. end;
  190. procedure _FPC_DLLMainCRTStartup(_hinstance : qword;_dllreason : dword;_dllparam:Pointer);stdcall;public name '_DLLMainCRTStartup';
  191. begin
  192. IsConsole:=true;
  193. sysinstance:=_hinstance;
  194. dllreason:=_dllreason;
  195. dllparam:=PtrInt(_dllparam);
  196. DLL_Entry;
  197. end;
  198. procedure _FPC_DLLWinMainCRTStartup(_hinstance : qword;_dllreason : dword;_dllparam:Pointer);stdcall;public name '_DLLWinMainCRTStartup';
  199. begin
  200. IsConsole:=false;
  201. sysinstance:=_hinstance;
  202. dllreason:=_dllreason;
  203. dllparam:=PtrInt(_dllparam);
  204. DLL_Entry;
  205. end;
  206. function is_prefetch(p : pointer) : boolean;
  207. var
  208. a : array[0..15] of byte;
  209. doagain : boolean;
  210. instrlo,instrhi,opcode : byte;
  211. i : longint;
  212. begin
  213. result:=false;
  214. { read memory savely without causing another exeception }
  215. if not(ReadProcessMemory(GetCurrentProcess,p,@a,sizeof(a),nil)) then
  216. exit;
  217. i:=0;
  218. doagain:=true;
  219. while doagain and (i<15) do
  220. begin
  221. opcode:=a[i];
  222. instrlo:=opcode and $f;
  223. instrhi:=opcode and $f0;
  224. case instrhi of
  225. { prefix? }
  226. $20,$30:
  227. doagain:=(instrlo and 7)=6;
  228. $60:
  229. doagain:=(instrlo and $c)=4;
  230. $f0:
  231. doagain:=instrlo in [0,2,3];
  232. $0:
  233. begin
  234. result:=(instrlo=$f) and (a[i+1] in [$d,$18]);
  235. exit;
  236. end;
  237. else
  238. doagain:=false;
  239. end;
  240. inc(i);
  241. end;
  242. end;
  243. //
  244. // Hardware exception handling
  245. //
  246. {$I seh64.inc}
  247. type
  248. TVectoredExceptionHandler = function (excep : PExceptionPointers) : Longint;
  249. function AddVectoredExceptionHandler(FirstHandler : DWORD;VectoredHandler : TVectoredExceptionHandler) : longint;
  250. external 'kernel32' name 'AddVectoredExceptionHandler';
  251. {$ifndef FPC_USE_WIN64_SEH}
  252. const
  253. MaxExceptionLevel = 16;
  254. exceptLevel : Byte = 0;
  255. var
  256. exceptRip : array[0..MaxExceptionLevel-1] of Int64;
  257. exceptError : array[0..MaxExceptionLevel-1] of Byte;
  258. resetFPU : array[0..MaxExceptionLevel-1] of Boolean;
  259. {$ifdef SYSTEMEXCEPTIONDEBUG}
  260. procedure DebugHandleErrorAddrFrame(error : longint; addr, frame : pointer);
  261. begin
  262. if IsConsole then
  263. begin
  264. write(stderr,'HandleErrorAddrFrame(error=',error);
  265. write(stderr,',addr=',hexstr(int64(addr),16));
  266. writeln(stderr,',frame=',hexstr(int64(frame),16),')');
  267. end;
  268. HandleErrorAddrFrame(error,addr,frame);
  269. end;
  270. {$endif SYSTEMEXCEPTIONDEBUG}
  271. procedure JumpToHandleErrorFrame;
  272. var
  273. rip, rbp : int64;
  274. error : longint;
  275. begin
  276. // save ebp
  277. asm
  278. movq (%rbp),%rax
  279. movq %rax,rbp
  280. end;
  281. if exceptLevel>0 then
  282. dec(exceptLevel);
  283. rip:=exceptRip[exceptLevel];
  284. error:=exceptError[exceptLevel];
  285. {$ifdef SYSTEMEXCEPTIONDEBUG}
  286. if IsConsole then
  287. writeln(stderr,'In JumpToHandleErrorFrame error=',error);
  288. {$endif SYSTEMEXCEPTIONDEBUG}
  289. if resetFPU[exceptLevel] then
  290. SysResetFPU;
  291. { build a fake stack }
  292. asm
  293. movq rbp,%r8
  294. movq rip,%rdx
  295. movl error,%ecx
  296. pushq rip
  297. movq rbp,%rbp // Change frame pointer
  298. {$ifdef SYSTEMEXCEPTIONDEBUG}
  299. jmpl DebugHandleErrorAddrFrame
  300. {$else not SYSTEMEXCEPTIONDEBUG}
  301. jmpl HandleErrorAddrFrame
  302. {$endif SYSTEMEXCEPTIONDEBUG}
  303. end;
  304. end;
  305. function syswin64_x86_64_exception_handler(excep : PExceptionPointers) : Longint;public;
  306. var
  307. res: longint;
  308. err: byte;
  309. must_reset_fpu: boolean;
  310. begin
  311. res:=EXCEPTION_CONTINUE_SEARCH;
  312. {$ifdef SYSTEMEXCEPTIONDEBUG}
  313. if IsConsole then
  314. Writeln(stderr,'syswin64_x86_64_exception_handler called');
  315. {$endif SYSTEMEXCEPTIONDEBUG}
  316. if excep^.ContextRecord^.SegSs=_SS then
  317. begin
  318. err := 0;
  319. must_reset_fpu := true;
  320. {$ifdef SYSTEMEXCEPTIONDEBUG}
  321. if IsConsole then Writeln(stderr,'Exception ',
  322. hexstr(excep^.ExceptionRecord^.ExceptionCode,8));
  323. {$endif SYSTEMEXCEPTIONDEBUG}
  324. case cardinal(excep^.ExceptionRecord^.ExceptionCode) of
  325. STATUS_INTEGER_DIVIDE_BY_ZERO,
  326. STATUS_FLOAT_DIVIDE_BY_ZERO :
  327. err := 200;
  328. STATUS_ARRAY_BOUNDS_EXCEEDED :
  329. begin
  330. err := 201;
  331. must_reset_fpu := false;
  332. end;
  333. STATUS_STACK_OVERFLOW :
  334. begin
  335. err := 202;
  336. must_reset_fpu := false;
  337. end;
  338. STATUS_FLOAT_OVERFLOW :
  339. err := 205;
  340. STATUS_FLOAT_DENORMAL_OPERAND,
  341. STATUS_FLOAT_UNDERFLOW :
  342. err := 206;
  343. { excep^.ContextRecord^.FloatSave.StatusWord := excep^.ContextRecord^.FloatSave.StatusWord and $ffffff00;}
  344. STATUS_FLOAT_INEXACT_RESULT,
  345. STATUS_FLOAT_INVALID_OPERATION,
  346. STATUS_FLOAT_STACK_CHECK :
  347. err := 207;
  348. STATUS_INTEGER_OVERFLOW :
  349. begin
  350. err := 215;
  351. must_reset_fpu := false;
  352. end;
  353. STATUS_ILLEGAL_INSTRUCTION:
  354. err := 216;
  355. STATUS_ACCESS_VIOLATION:
  356. { Athlon prefetch bug? }
  357. if is_prefetch(pointer(excep^.ContextRecord^.rip)) then
  358. begin
  359. { if yes, then retry }
  360. excep^.ExceptionRecord^.ExceptionCode := 0;
  361. res:=EXCEPTION_CONTINUE_EXECUTION;
  362. end
  363. else
  364. err := 216;
  365. STATUS_CONTROL_C_EXIT:
  366. err := 217;
  367. STATUS_PRIVILEGED_INSTRUCTION:
  368. begin
  369. err := 218;
  370. must_reset_fpu := false;
  371. end;
  372. else
  373. begin
  374. if ((excep^.ExceptionRecord^.ExceptionCode and SEVERITY_ERROR) = SEVERITY_ERROR) then
  375. err := 217
  376. else
  377. { pass through exceptions which aren't an error. The problem is that vectored handlers
  378. always are called before structured ones so we see also internal exceptions of libraries.
  379. I wonder if there is a better solution (FK)
  380. }
  381. res:=EXCEPTION_CONTINUE_SEARCH;
  382. end;
  383. end;
  384. if (err <> 0) and (exceptLevel < MaxExceptionLevel) then
  385. begin
  386. exceptRip[exceptLevel] := excep^.ContextRecord^.Rip;
  387. exceptError[exceptLevel] := err;
  388. resetFPU[exceptLevel] := must_reset_fpu;
  389. inc(exceptLevel);
  390. excep^.ContextRecord^.Rip := Int64(@JumpToHandleErrorFrame);
  391. excep^.ExceptionRecord^.ExceptionCode := 0;
  392. res := EXCEPTION_CONTINUE_EXECUTION;
  393. {$ifdef SYSTEMEXCEPTIONDEBUG}
  394. if IsConsole then begin
  395. writeln(stderr,'Exception Continue Exception set at ',
  396. hexstr(exceptRip[exceptLevel-1],16));
  397. writeln(stderr,'Rip changed to ',
  398. hexstr(int64(@JumpToHandleErrorFrame),16), ' error=', err);
  399. end;
  400. {$endif SYSTEMEXCEPTIONDEBUG}
  401. end;
  402. end;
  403. syswin64_x86_64_exception_handler := res;
  404. end;
  405. procedure install_exception_handlers;
  406. begin
  407. AddVectoredExceptionHandler(1,@syswin64_x86_64_exception_handler);
  408. end;
  409. {$endif ndef FPC_USE_WIN64_SEH}
  410. procedure LinkIn(p1,p2,p3: Pointer); inline;
  411. begin
  412. end;
  413. procedure _FPC_mainCRTStartup;stdcall;public name '_mainCRTStartup';
  414. begin
  415. IsConsole:=true;
  416. GetConsoleMode(GetStdHandle((Std_Input_Handle)),@StartupConsoleMode);
  417. {$ifdef FPC_USE_TLS_DIRECTORY}
  418. LinkIn(@_tls_used,@FreePascal_TLS_callback,@FreePascal_end_of_TLS_callback);
  419. {$endif FPC_USE_TLS_DIRECTORY}
  420. Exe_entry;
  421. end;
  422. procedure _FPC_WinMainCRTStartup;stdcall;public name '_WinMainCRTStartup';
  423. begin
  424. IsConsole:=false;
  425. {$ifdef FPC_USE_TLS_DIRECTORY}
  426. LinkIn(@_tls_used,@FreePascal_TLS_callback,@FreePascal_end_of_TLS_callback);
  427. {$endif FPC_USE_TLS_DIRECTORY}
  428. Exe_entry;
  429. end;
  430. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt;
  431. type
  432. tdosheader = packed record
  433. e_magic : word;
  434. e_cblp : word;
  435. e_cp : word;
  436. e_crlc : word;
  437. e_cparhdr : word;
  438. e_minalloc : word;
  439. e_maxalloc : word;
  440. e_ss : word;
  441. e_sp : word;
  442. e_csum : word;
  443. e_ip : word;
  444. e_cs : word;
  445. e_lfarlc : word;
  446. e_ovno : word;
  447. e_res : array[0..3] of word;
  448. e_oemid : word;
  449. e_oeminfo : word;
  450. e_res2 : array[0..9] of word;
  451. e_lfanew : longint;
  452. end;
  453. tpeheader = packed record
  454. PEMagic : longint;
  455. Machine : word;
  456. NumberOfSections : word;
  457. TimeDateStamp : longint;
  458. PointerToSymbolTable : longint;
  459. NumberOfSymbols : longint;
  460. SizeOfOptionalHeader : word;
  461. Characteristics : word;
  462. Magic : word;
  463. MajorLinkerVersion : byte;
  464. MinorLinkerVersion : byte;
  465. SizeOfCode : longint;
  466. SizeOfInitializedData : longint;
  467. SizeOfUninitializedData : longint;
  468. AddressOfEntryPoint : longint;
  469. BaseOfCode : longint;
  470. {$ifdef win32}
  471. BaseOfData : longint;
  472. {$endif win32}
  473. ImageBase : PtrInt;
  474. SectionAlignment : longint;
  475. FileAlignment : longint;
  476. MajorOperatingSystemVersion : word;
  477. MinorOperatingSystemVersion : word;
  478. MajorImageVersion : word;
  479. MinorImageVersion : word;
  480. MajorSubsystemVersion : word;
  481. MinorSubsystemVersion : word;
  482. Reserved1 : longint;
  483. SizeOfImage : longint;
  484. SizeOfHeaders : longint;
  485. CheckSum : longint;
  486. Subsystem : word;
  487. DllCharacteristics : word;
  488. SizeOfStackReserve : PtrInt;
  489. SizeOfStackCommit : PtrInt;
  490. SizeOfHeapReserve : PtrInt;
  491. SizeOfHeapCommit : PtrInt;
  492. LoaderFlags : longint;
  493. NumberOfRvaAndSizes : longint;
  494. DataDirectory : array[1..$80] of byte;
  495. end;
  496. begin
  497. result:=tpeheader((pointer(getmodulehandle(nil))+(tdosheader(pointer(getmodulehandle(nil))^).e_lfanew))^).SizeOfStackReserve;
  498. end;
  499. var
  500. st : Pointer;
  501. begin
  502. asm
  503. movq %gs:(8),%rax
  504. movq %rax,st
  505. end;
  506. StackTop:=st;
  507. { pass dummy value }
  508. StackLength := CheckInitialStkLen($1000000);
  509. StackBottom := StackTop - StackLength;
  510. { get some helpful informations }
  511. GetStartupInfo(@startupinfo);
  512. { some misc Win32 stuff }
  513. if not IsLibrary then
  514. SysInstance:=getmodulehandle(nil);
  515. MainInstance:=SysInstance;
  516. cmdshow:=startupinfo.wshowwindow;
  517. { Setup heap and threading, these may be already initialized from TLS callback }
  518. if not Assigned(CurrentTM.BeginThread) then
  519. begin
  520. InitHeap;
  521. InitSystemThreads;
  522. end;
  523. SysInitExceptions;
  524. initwidestringmanager;
  525. initunicodestringmanager;
  526. InitWin32Widestrings;
  527. SysInitStdIO;
  528. { Arguments }
  529. setup_arguments;
  530. { Reset IO Error }
  531. InOutRes:=0;
  532. ProcessID := GetCurrentProcessID;
  533. { Reset internal error variable }
  534. errno:=0;
  535. initvariantmanager;
  536. DispCallByIDProc:=@DoDispCallByIDError;
  537. end.