system.pp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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. { used by wstrings.inc because wstrings.inc is included before sysos.inc
  101. this is put here (FK) }
  102. function SysAllocStringLen(psz:pointer;len:dword):pointer;stdcall;
  103. external 'oleaut32.dll' name 'SysAllocStringLen';
  104. procedure SysFreeString(bstr:pointer);stdcall;
  105. external 'oleaut32.dll' name 'SysFreeString';
  106. function SysReAllocStringLen(var bstr:pointer;psz: pointer;
  107. len:dword): Integer; stdcall;external 'oleaut32.dll' name 'SysReAllocStringLen';
  108. { include system independent routines }
  109. {$I system.inc}
  110. {*****************************************************************************
  111. System Dependent Exit code
  112. *****************************************************************************}
  113. procedure install_exception_handlers;forward;
  114. procedure remove_exception_handlers;forward;
  115. procedure PascalMain;stdcall;external name 'PASCALMAIN';
  116. procedure fpc_do_exit;stdcall;external name 'FPC_DO_EXIT';
  117. Procedure ExitDLL(Exitcode : longint); forward;
  118. Procedure system_exit;
  119. begin
  120. { don't call ExitProcess inside
  121. the DLL exit code !!
  122. This crashes Win95 at least PM }
  123. if IsLibrary then
  124. ExitDLL(ExitCode);
  125. if not IsConsole then
  126. begin
  127. Close(stderr);
  128. Close(stdout);
  129. Close(erroutput);
  130. Close(Input);
  131. Close(Output);
  132. { what about Input and Output ?? PM }
  133. { now handled, FPK }
  134. end;
  135. remove_exception_handlers;
  136. { call exitprocess, with cleanup as required }
  137. ExitProcess(exitcode);
  138. end;
  139. var
  140. { old compilers emitted a reference to _fltused if a module contains
  141. floating type code so the linker could leave away floating point
  142. libraries or not. VC does this as well so we need to define this
  143. symbol as well (FK)
  144. }
  145. _fltused : int64;cvar;public;
  146. { value of the stack segment
  147. to check if the call stack can be written on exceptions }
  148. _SS : Cardinal;
  149. procedure Exe_entry;[public,alias:'_FPC_EXE_Entry'];
  150. var
  151. ST : pointer;
  152. begin
  153. IsLibrary:=false;
  154. { install the handlers for exe only ?
  155. or should we install them for DLL also ? (PM) }
  156. install_exception_handlers;
  157. ExitCode:=0;
  158. asm
  159. movq %rsp,%rax
  160. movq %rax,st
  161. end;
  162. StackTop:=st;
  163. asm
  164. xorq %rax,%rax
  165. movw %ss,%ax
  166. movl %eax,_SS(%rip)
  167. movq %rbp,%rsi
  168. xorq %rbp,%rbp
  169. call PASCALMAIN
  170. movq %rsi,%rbp
  171. end ['RSI','RBP']; { <-- specifying RSI allows compiler to save/restore it properly }
  172. { if we pass here there was no error ! }
  173. system_exit;
  174. end;
  175. function GetConsoleMode(hConsoleHandle: THandle; var lpMode: DWORD): Boolean; stdcall; external 'kernel32' name 'GetConsoleMode';
  176. function Dll_entry{$ifdef FPC_HAS_INDIRECT_MAIN_INFORMATION}(const info : TEntryInformation){$endif FPC_HAS_INDIRECT_MAIN_INFORMATION} : longbool;forward;
  177. procedure _FPC_DLLMainCRTStartup(_hinstance : qword;_dllreason,_dllparam:longint);stdcall;public name '_DLLMainCRTStartup';
  178. begin
  179. IsConsole:=true;
  180. sysinstance:=_hinstance;
  181. dllreason:=_dllreason;
  182. dllparam:=_dllparam;
  183. DLL_Entry;
  184. end;
  185. procedure _FPC_DLLWinMainCRTStartup(_hinstance : qword;_dllreason,_dllparam:longint);stdcall;public name '_DLLWinMainCRTStartup';
  186. begin
  187. IsConsole:=false;
  188. sysinstance:=_hinstance;
  189. dllreason:=_dllreason;
  190. dllparam:=_dllparam;
  191. DLL_Entry;
  192. end;
  193. function GetCurrentProcess : dword;
  194. stdcall;external 'kernel32' name 'GetCurrentProcess';
  195. function ReadProcessMemory(process : dword;address : pointer;dest : pointer;size : dword;bytesread : pdword) : longbool;
  196. stdcall;external 'kernel32' name 'ReadProcessMemory';
  197. function is_prefetch(p : pointer) : boolean;
  198. var
  199. a : array[0..15] of byte;
  200. doagain : boolean;
  201. instrlo,instrhi,opcode : byte;
  202. i : longint;
  203. begin
  204. result:=false;
  205. { read memory savely without causing another exeception }
  206. if not(ReadProcessMemory(GetCurrentProcess,p,@a,sizeof(a),nil)) then
  207. exit;
  208. i:=0;
  209. doagain:=true;
  210. while doagain and (i<15) do
  211. begin
  212. opcode:=a[i];
  213. instrlo:=opcode and $f;
  214. instrhi:=opcode and $f0;
  215. case instrhi of
  216. { prefix? }
  217. $20,$30:
  218. doagain:=(instrlo and 7)=6;
  219. $60:
  220. doagain:=(instrlo and $c)=4;
  221. $f0:
  222. doagain:=instrlo in [0,2,3];
  223. $0:
  224. begin
  225. result:=(instrlo=$f) and (a[i+1] in [$d,$18]);
  226. exit;
  227. end;
  228. else
  229. doagain:=false;
  230. end;
  231. inc(i);
  232. end;
  233. end;
  234. {******************************************************************************}
  235. { include code common with win64 }
  236. {$I syswin.inc}
  237. {******************************************************************************}
  238. //
  239. // Hardware exception handling
  240. //
  241. type
  242. M128A = record
  243. Low : QWord;
  244. High : Int64;
  245. end;
  246. PContext = ^TContext;
  247. TContext = record
  248. P1Home : QWord;
  249. P2Home : QWord;
  250. P3Home : QWord;
  251. P4Home : QWord;
  252. P5Home : QWord;
  253. P6Home : QWord;
  254. ContextFlags : DWord;
  255. MxCsr : DWord;
  256. SegCs : word;
  257. SegDs : word;
  258. SegEs : word;
  259. SegFs : word;
  260. SegGs : word;
  261. SegSs : word;
  262. EFlags : DWord;
  263. Dr0 : QWord;
  264. Dr1 : QWord;
  265. Dr2 : QWord;
  266. Dr3 : QWord;
  267. Dr6 : QWord;
  268. Dr7 : QWord;
  269. Rax : QWord;
  270. Rcx : QWord;
  271. Rdx : QWord;
  272. Rbx : QWord;
  273. Rsp : QWord;
  274. Rbp : QWord;
  275. Rsi : QWord;
  276. Rdi : QWord;
  277. R8 : QWord;
  278. R9 : QWord;
  279. R10 : QWord;
  280. R11 : QWord;
  281. R12 : QWord;
  282. R13 : QWord;
  283. R14 : QWord;
  284. R15 : QWord;
  285. Rip : QWord;
  286. Header : array[0..1] of M128A;
  287. Legacy : array[0..7] of M128A;
  288. Xmm0 : M128A;
  289. Xmm1 : M128A;
  290. Xmm2 : M128A;
  291. Xmm3 : M128A;
  292. Xmm4 : M128A;
  293. Xmm5 : M128A;
  294. Xmm6 : M128A;
  295. Xmm7 : M128A;
  296. Xmm8 : M128A;
  297. Xmm9 : M128A;
  298. Xmm10 : M128A;
  299. Xmm11 : M128A;
  300. Xmm12 : M128A;
  301. Xmm13 : M128A;
  302. Xmm14 : M128A;
  303. Xmm15 : M128A;
  304. VectorRegister : array[0..25] of M128A;
  305. VectorControl : QWord;
  306. DebugControl : QWord;
  307. LastBranchToRip : QWord;
  308. LastBranchFromRip : QWord;
  309. LastExceptionToRip : QWord;
  310. LastExceptionFromRip : QWord;
  311. end;
  312. type
  313. PExceptionRecord = ^TExceptionRecord;
  314. TExceptionRecord = record
  315. ExceptionCode : DWord;
  316. ExceptionFlags : DWord;
  317. ExceptionRecord : PExceptionRecord;
  318. ExceptionAddress : Pointer;
  319. NumberParameters : DWord;
  320. ExceptionInformation : array[0..EXCEPTION_MAXIMUM_PARAMETERS-1] of Pointer;
  321. end;
  322. PExceptionPointers = ^TExceptionPointers;
  323. TExceptionPointers = packed record
  324. ExceptionRecord : PExceptionRecord;
  325. ContextRecord : PContext;
  326. end;
  327. TVectoredExceptionHandler = function (excep : PExceptionPointers) : Longint;
  328. function AddVectoredExceptionHandler(FirstHandler : DWORD;VectoredHandler : TVectoredExceptionHandler) : longint;
  329. external 'kernel32' name 'AddVectoredExceptionHandler';
  330. const
  331. MaxExceptionLevel = 16;
  332. exceptLevel : Byte = 0;
  333. var
  334. exceptRip : array[0..MaxExceptionLevel-1] of Int64;
  335. exceptError : array[0..MaxExceptionLevel-1] of Byte;
  336. resetFPU : array[0..MaxExceptionLevel-1] of Boolean;
  337. {$ifdef SYSTEMEXCEPTIONDEBUG}
  338. procedure DebugHandleErrorAddrFrame(error : longint; addr, frame : pointer);
  339. begin
  340. if IsConsole then
  341. begin
  342. write(stderr,'HandleErrorAddrFrame(error=',error);
  343. write(stderr,',addr=',hexstr(int64(addr),16));
  344. writeln(stderr,',frame=',hexstr(int64(frame),16),')');
  345. end;
  346. HandleErrorAddrFrame(error,addr,frame);
  347. end;
  348. {$endif SYSTEMEXCEPTIONDEBUG}
  349. procedure JumpToHandleErrorFrame;
  350. var
  351. rip, rbp : int64;
  352. error : longint;
  353. begin
  354. // save ebp
  355. asm
  356. movq (%rbp),%rax
  357. movq %rax,rbp
  358. end;
  359. if exceptLevel>0 then
  360. dec(exceptLevel);
  361. rip:=exceptRip[exceptLevel];
  362. error:=exceptError[exceptLevel];
  363. {$ifdef SYSTEMEXCEPTIONDEBUG}
  364. if IsConsole then
  365. writeln(stderr,'In JumpToHandleErrorFrame error=',error);
  366. {$endif SYSTEMEXCEPTIONDEBUG}
  367. if resetFPU[exceptLevel] then
  368. SysResetFPU;
  369. { build a fake stack }
  370. asm
  371. movq rbp,%r8
  372. movq rip,%rdx
  373. movl error,%ecx
  374. pushq rip
  375. movq rbp,%rbp // Change frame pointer
  376. {$ifdef SYSTEMEXCEPTIONDEBUG}
  377. jmpl DebugHandleErrorAddrFrame
  378. {$else not SYSTEMEXCEPTIONDEBUG}
  379. jmpl HandleErrorAddrFrame
  380. {$endif SYSTEMEXCEPTIONDEBUG}
  381. end;
  382. end;
  383. function syswin64_x86_64_exception_handler(excep : PExceptionPointers) : Longint;public;
  384. var
  385. res: longint;
  386. err: byte;
  387. must_reset_fpu: boolean;
  388. begin
  389. res:=EXCEPTION_CONTINUE_SEARCH;
  390. {$ifdef SYSTEMEXCEPTIONDEBUG}
  391. if IsConsole then
  392. Writeln(stderr,'syswin64_x86_64_exception_handler called');
  393. {$endif SYSTEMEXCEPTIONDEBUG}
  394. if excep^.ContextRecord^.SegSs=_SS then
  395. begin
  396. err := 0;
  397. must_reset_fpu := true;
  398. {$ifdef SYSTEMEXCEPTIONDEBUG}
  399. if IsConsole then Writeln(stderr,'Exception ',
  400. hexstr(excep^.ExceptionRecord^.ExceptionCode,8));
  401. {$endif SYSTEMEXCEPTIONDEBUG}
  402. case cardinal(excep^.ExceptionRecord^.ExceptionCode) of
  403. STATUS_INTEGER_DIVIDE_BY_ZERO,
  404. STATUS_FLOAT_DIVIDE_BY_ZERO :
  405. err := 200;
  406. STATUS_ARRAY_BOUNDS_EXCEEDED :
  407. begin
  408. err := 201;
  409. must_reset_fpu := false;
  410. end;
  411. STATUS_STACK_OVERFLOW :
  412. begin
  413. err := 202;
  414. must_reset_fpu := false;
  415. end;
  416. STATUS_FLOAT_OVERFLOW :
  417. err := 205;
  418. STATUS_FLOAT_DENORMAL_OPERAND,
  419. STATUS_FLOAT_UNDERFLOW :
  420. err := 206;
  421. { excep^.ContextRecord^.FloatSave.StatusWord := excep^.ContextRecord^.FloatSave.StatusWord and $ffffff00;}
  422. STATUS_FLOAT_INEXACT_RESULT,
  423. STATUS_FLOAT_INVALID_OPERATION,
  424. STATUS_FLOAT_STACK_CHECK :
  425. err := 207;
  426. STATUS_INTEGER_OVERFLOW :
  427. begin
  428. err := 215;
  429. must_reset_fpu := false;
  430. end;
  431. STATUS_ILLEGAL_INSTRUCTION:
  432. err := 216;
  433. STATUS_ACCESS_VIOLATION:
  434. { Athlon prefetch bug? }
  435. if is_prefetch(pointer(excep^.ContextRecord^.rip)) then
  436. begin
  437. { if yes, then retry }
  438. excep^.ExceptionRecord^.ExceptionCode := 0;
  439. res:=EXCEPTION_CONTINUE_EXECUTION;
  440. end
  441. else
  442. err := 216;
  443. STATUS_CONTROL_C_EXIT:
  444. err := 217;
  445. STATUS_PRIVILEGED_INSTRUCTION:
  446. begin
  447. err := 218;
  448. must_reset_fpu := false;
  449. end;
  450. else
  451. begin
  452. if ((excep^.ExceptionRecord^.ExceptionCode and SEVERITY_ERROR) = SEVERITY_ERROR) then
  453. err := 217
  454. else
  455. { pass through exceptions which aren't an error. The problem is that vectored handlers
  456. always are called before structured ones so we see also internal exceptions of libraries.
  457. I wonder if there is a better solution (FK)
  458. }
  459. res:=EXCEPTION_CONTINUE_SEARCH;
  460. end;
  461. end;
  462. if (err <> 0) and (exceptLevel < MaxExceptionLevel) then
  463. begin
  464. exceptRip[exceptLevel] := excep^.ContextRecord^.Rip;
  465. exceptError[exceptLevel] := err;
  466. resetFPU[exceptLevel] := must_reset_fpu;
  467. inc(exceptLevel);
  468. excep^.ContextRecord^.Rip := Int64(@JumpToHandleErrorFrame);
  469. excep^.ExceptionRecord^.ExceptionCode := 0;
  470. res := EXCEPTION_CONTINUE_EXECUTION;
  471. {$ifdef SYSTEMEXCEPTIONDEBUG}
  472. if IsConsole then begin
  473. writeln(stderr,'Exception Continue Exception set at ',
  474. hexstr(exceptRip[exceptLevel-1],16));
  475. writeln(stderr,'Rip changed to ',
  476. hexstr(int64(@JumpToHandleErrorFrame),16), ' error=', err);
  477. end;
  478. {$endif SYSTEMEXCEPTIONDEBUG}
  479. end;
  480. end;
  481. syswin64_x86_64_exception_handler := res;
  482. end;
  483. procedure install_exception_handlers;
  484. begin
  485. AddVectoredExceptionHandler(1,@syswin64_x86_64_exception_handler);
  486. end;
  487. procedure remove_exception_handlers;
  488. begin
  489. end;
  490. procedure fpc_cpucodeinit;
  491. begin
  492. end;
  493. procedure LinkIn(p1,p2,p3: Pointer); inline;
  494. begin
  495. end;
  496. procedure _FPC_mainCRTStartup;stdcall;public name '_mainCRTStartup';
  497. begin
  498. IsConsole:=true;
  499. GetConsoleMode(GetStdHandle((Std_Input_Handle)),StartupConsoleMode);
  500. {$ifdef FPC_USE_TLS_DIRECTORY}
  501. LinkIn(@_tls_used,@FreePascal_TLS_callback,@FreePascal_end_of_TLS_callback);
  502. {$endif FPC_USE_TLS_DIRECTORY}
  503. Exe_entry;
  504. end;
  505. procedure _FPC_WinMainCRTStartup;stdcall;public name '_WinMainCRTStartup';
  506. begin
  507. IsConsole:=false;
  508. {$ifdef FPC_USE_TLS_DIRECTORY}
  509. LinkIn(@_tls_used,@FreePascal_TLS_callback,@FreePascal_end_of_TLS_callback);
  510. {$endif FPC_USE_TLS_DIRECTORY}
  511. Exe_entry;
  512. end;
  513. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt;assembler;
  514. asm
  515. movq %gs:(8),%rax
  516. subq %gs:(16),%rax
  517. end;
  518. begin
  519. { pass dummy value }
  520. StackLength := CheckInitialStkLen($1000000);
  521. StackBottom := StackTop - StackLength;
  522. { get some helpful informations }
  523. GetStartupInfo(@startupinfo);
  524. { some misc Win32 stuff }
  525. if not IsLibrary then
  526. SysInstance:=getmodulehandle(nil);
  527. MainInstance:=SysInstance;
  528. cmdshow:=startupinfo.wshowwindow;
  529. { Setup heap }
  530. InitHeap;
  531. SysInitExceptions;
  532. { setup fastmove stuff }
  533. fpc_cpucodeinit;
  534. initwidestringmanager;
  535. initunicodestringmanager;
  536. InitWin32Widestrings;
  537. SysInitStdIO;
  538. { Arguments }
  539. setup_arguments;
  540. { Reset IO Error }
  541. InOutRes:=0;
  542. ProcessID := GetCurrentProcessID;
  543. { threading }
  544. InitSystemThreads;
  545. { Reset internal error variable }
  546. errno:=0;
  547. initvariantmanager;
  548. DispCallByIDProc:=@DoDispCallByIDError;
  549. end.