system.pp 16 KB

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