system.pp 16 KB

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