system.pp 17 KB

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