system.pp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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. var
  58. { C compatible arguments }
  59. argc : longint;
  60. argv : ppchar;
  61. { Win32 Info }
  62. startupinfo : tstartupinfo deprecated; // Delphi does not have one in interface
  63. StartupConsoleMode : dword;
  64. MainInstance : qword;
  65. cmdshow : longint;
  66. DLLreason : dword;
  67. DLLparam : PtrInt;
  68. const
  69. hprevinst: qword=0;
  70. type
  71. TDLL_Entry_Hook = procedure (dllparam : PtrInt);
  72. const
  73. Dll_Process_Detach_Hook : TDLL_Entry_Hook = nil;
  74. Dll_Thread_Attach_Hook : TDLL_Entry_Hook = nil;
  75. Dll_Thread_Detach_Hook : TDLL_Entry_Hook = nil;
  76. Const
  77. { it can be discussed whether fmShareDenyNone means read and write or read, write and delete, see
  78. also http://bugs.freepascal.org/view.php?id=8898, this allows users to configure the used
  79. value
  80. }
  81. fmShareDenyNoneFlags : DWord = 3;
  82. implementation
  83. {$asmmode att}
  84. var
  85. SysInstance : qword;public;
  86. {$ifdef FPC_USE_WIN64_SEH}
  87. function main_wrapper(arg: Pointer; proc: Pointer): ptrint; assembler; nostackframe;
  88. asm
  89. subq $40, %rsp
  90. .seh_stackalloc 40
  91. .seh_endprologue
  92. call %rdx { "arg" is passed in %rcx }
  93. nop { this nop is critical for exception handling }
  94. addq $40, %rsp
  95. .seh_handler __FPC_default_handler,@except,@unwind
  96. end;
  97. {$endif FPC_USE_WIN64_SEH}
  98. {$define FPC_SYSTEM_HAS_STACKTOP}
  99. function StackTop: pointer; assembler;nostackframe;
  100. asm
  101. movq %gs:(8),%rax
  102. end;
  103. { include system independent routines }
  104. {$I system.inc}
  105. {*****************************************************************************
  106. System Dependent Exit code
  107. *****************************************************************************}
  108. {$ifndef FPC_USE_WIN64_SEH}
  109. procedure install_exception_handlers;forward;
  110. {$endif FPC_USE_WIN64_SEH}
  111. procedure PascalMain;stdcall;external name 'PASCALMAIN';
  112. { include code common with win32 }
  113. {$I syswin.inc}
  114. { TLS directory code }
  115. {$I systlsdir.inc}
  116. Procedure system_exit;
  117. begin
  118. { see comments in win32/system.pp about this logic }
  119. if IsLibrary then
  120. begin
  121. if DllInitState in [DLL_PROCESS_ATTACH,DLL_PROCESS_DETACH] then
  122. LongJmp(DLLBuf,1)
  123. else
  124. MainThreadIDWin32:=0;
  125. end;
  126. if not IsConsole then
  127. begin
  128. Close(stderr);
  129. Close(stdout);
  130. Close(erroutput);
  131. Close(Input);
  132. Close(Output);
  133. { what about Input and Output ?? PM }
  134. { now handled, FPK }
  135. end;
  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. begin
  151. IsLibrary:=false;
  152. { install the handlers for exe only ?
  153. or should we install them for DLL also ? (PM) }
  154. {$ifndef FPC_USE_WIN64_SEH}
  155. install_exception_handlers;
  156. {$endif FPC_USE_WIN64_SEH}
  157. ExitCode:=0;
  158. asm
  159. xorq %rax,%rax
  160. movw %ss,%ax
  161. movl %eax,_SS(%rip)
  162. movq %rbp,%rsi
  163. xorq %rbp,%rbp
  164. {$ifdef FPC_USE_WIN64_SEH}
  165. xor %rcx,%rcx
  166. lea PASCALMAIN(%rip),%rdx
  167. call main_wrapper
  168. {$else FPC_USE_WIN64_SEH}
  169. call PASCALMAIN
  170. {$endif FPC_USE_WIN64_SEH}
  171. movq %rsi,%rbp
  172. end ['RSI','RBP']; { <-- specifying RSI allows compiler to save/restore it properly }
  173. { if we pass here there was no error ! }
  174. system_exit;
  175. end;
  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 is_prefetch(p : pointer) : boolean;
  193. var
  194. a : array[0..15] of byte;
  195. doagain : boolean;
  196. instrlo,instrhi,opcode : byte;
  197. i : longint;
  198. begin
  199. result:=false;
  200. { read memory savely without causing another exeception }
  201. if not(ReadProcessMemory(GetCurrentProcess,p,@a,sizeof(a),nil)) then
  202. exit;
  203. i:=0;
  204. doagain:=true;
  205. while doagain and (i<15) do
  206. begin
  207. opcode:=a[i];
  208. instrlo:=opcode and $f;
  209. instrhi:=opcode and $f0;
  210. case instrhi of
  211. { prefix? }
  212. $20,$30:
  213. doagain:=(instrlo and 7)=6;
  214. $60:
  215. doagain:=(instrlo and $c)=4;
  216. $f0:
  217. doagain:=instrlo in [0,2,3];
  218. $0:
  219. begin
  220. result:=(instrlo=$f) and (a[i+1] in [$d,$18]);
  221. exit;
  222. end;
  223. else
  224. doagain:=false;
  225. end;
  226. inc(i);
  227. end;
  228. end;
  229. //
  230. // Hardware exception handling
  231. //
  232. {$I seh64.inc}
  233. type
  234. TVectoredExceptionHandler = function (excep : PExceptionPointers) : Longint;
  235. function AddVectoredExceptionHandler(FirstHandler : DWORD;VectoredHandler : TVectoredExceptionHandler) : longint;
  236. external 'kernel32' name 'AddVectoredExceptionHandler';
  237. {$ifndef FPC_USE_WIN64_SEH}
  238. const
  239. MaxExceptionLevel = 16;
  240. exceptLevel : Byte = 0;
  241. var
  242. exceptRip : array[0..MaxExceptionLevel-1] of Int64;
  243. exceptError : array[0..MaxExceptionLevel-1] of Byte;
  244. resetFPU : array[0..MaxExceptionLevel-1] of Boolean;
  245. {$ifdef SYSTEMEXCEPTIONDEBUG}
  246. procedure DebugHandleErrorAddrFrame(error : longint; addr, frame : pointer);
  247. begin
  248. if IsConsole then
  249. begin
  250. write(stderr,'HandleErrorAddrFrame(error=',error);
  251. write(stderr,',addr=',hexstr(int64(addr),16));
  252. writeln(stderr,',frame=',hexstr(int64(frame),16),')');
  253. end;
  254. HandleErrorAddrFrame(error,addr,frame);
  255. end;
  256. {$endif SYSTEMEXCEPTIONDEBUG}
  257. procedure JumpToHandleErrorFrame;
  258. var
  259. rip, rbp : int64;
  260. error : longint;
  261. begin
  262. // save ebp
  263. asm
  264. movq (%rbp),%rax
  265. movq %rax,rbp
  266. end;
  267. if exceptLevel>0 then
  268. dec(exceptLevel);
  269. rip:=exceptRip[exceptLevel];
  270. error:=exceptError[exceptLevel];
  271. {$ifdef SYSTEMEXCEPTIONDEBUG}
  272. if IsConsole then
  273. writeln(stderr,'In JumpToHandleErrorFrame error=',error);
  274. {$endif SYSTEMEXCEPTIONDEBUG}
  275. if resetFPU[exceptLevel] then
  276. SysResetFPU;
  277. { build a fake stack }
  278. asm
  279. movq rbp,%r8
  280. movq rip,%rdx
  281. movl error,%ecx
  282. pushq rip
  283. movq rbp,%rbp // Change frame pointer
  284. {$ifdef SYSTEMEXCEPTIONDEBUG}
  285. jmpl DebugHandleErrorAddrFrame
  286. {$else not SYSTEMEXCEPTIONDEBUG}
  287. jmpl HandleErrorAddrFrame
  288. {$endif SYSTEMEXCEPTIONDEBUG}
  289. end;
  290. end;
  291. function syswin64_x86_64_exception_handler(excep : PExceptionPointers) : Longint;public;
  292. var
  293. res: longint;
  294. err: byte;
  295. must_reset_fpu: boolean;
  296. begin
  297. res:=EXCEPTION_CONTINUE_SEARCH;
  298. {$ifdef SYSTEMEXCEPTIONDEBUG}
  299. if IsConsole then
  300. Writeln(stderr,'syswin64_x86_64_exception_handler called');
  301. {$endif SYSTEMEXCEPTIONDEBUG}
  302. if excep^.ContextRecord^.SegSs=_SS then
  303. begin
  304. err := 0;
  305. must_reset_fpu := true;
  306. {$ifdef SYSTEMEXCEPTIONDEBUG}
  307. if IsConsole then Writeln(stderr,'Exception ',
  308. hexstr(excep^.ExceptionRecord^.ExceptionCode,8));
  309. {$endif SYSTEMEXCEPTIONDEBUG}
  310. case cardinal(excep^.ExceptionRecord^.ExceptionCode) of
  311. STATUS_INTEGER_DIVIDE_BY_ZERO,
  312. STATUS_FLOAT_DIVIDE_BY_ZERO :
  313. err := 200;
  314. STATUS_ARRAY_BOUNDS_EXCEEDED :
  315. begin
  316. err := 201;
  317. must_reset_fpu := false;
  318. end;
  319. STATUS_STACK_OVERFLOW :
  320. begin
  321. err := 202;
  322. must_reset_fpu := false;
  323. end;
  324. STATUS_FLOAT_OVERFLOW :
  325. err := 205;
  326. STATUS_FLOAT_DENORMAL_OPERAND,
  327. STATUS_FLOAT_UNDERFLOW :
  328. err := 206;
  329. { excep^.ContextRecord^.FloatSave.StatusWord := excep^.ContextRecord^.FloatSave.StatusWord and $ffffff00;}
  330. STATUS_FLOAT_INEXACT_RESULT,
  331. STATUS_FLOAT_INVALID_OPERATION,
  332. STATUS_FLOAT_STACK_CHECK :
  333. err := 207;
  334. STATUS_INTEGER_OVERFLOW :
  335. begin
  336. err := 215;
  337. must_reset_fpu := false;
  338. end;
  339. STATUS_ILLEGAL_INSTRUCTION:
  340. err := 216;
  341. STATUS_ACCESS_VIOLATION:
  342. { Athlon prefetch bug? }
  343. if is_prefetch(pointer(excep^.ContextRecord^.rip)) then
  344. begin
  345. { if yes, then retry }
  346. excep^.ExceptionRecord^.ExceptionCode := 0;
  347. res:=EXCEPTION_CONTINUE_EXECUTION;
  348. end
  349. else
  350. err := 216;
  351. STATUS_CONTROL_C_EXIT:
  352. err := 217;
  353. STATUS_PRIVILEGED_INSTRUCTION:
  354. begin
  355. err := 218;
  356. must_reset_fpu := false;
  357. end;
  358. else
  359. begin
  360. if ((excep^.ExceptionRecord^.ExceptionCode and SEVERITY_ERROR) = SEVERITY_ERROR) then
  361. err := 217
  362. else
  363. { pass through exceptions which aren't an error. The problem is that vectored handlers
  364. always are called before structured ones so we see also internal exceptions of libraries.
  365. I wonder if there is a better solution (FK)
  366. }
  367. res:=EXCEPTION_CONTINUE_SEARCH;
  368. end;
  369. end;
  370. if (err <> 0) and (exceptLevel < MaxExceptionLevel) then
  371. begin
  372. exceptRip[exceptLevel] := excep^.ContextRecord^.Rip;
  373. exceptError[exceptLevel] := err;
  374. resetFPU[exceptLevel] := must_reset_fpu;
  375. inc(exceptLevel);
  376. excep^.ContextRecord^.Rip := Int64(@JumpToHandleErrorFrame);
  377. excep^.ExceptionRecord^.ExceptionCode := 0;
  378. res := EXCEPTION_CONTINUE_EXECUTION;
  379. {$ifdef SYSTEMEXCEPTIONDEBUG}
  380. if IsConsole then begin
  381. writeln(stderr,'Exception Continue Exception set at ',
  382. hexstr(exceptRip[exceptLevel-1],16));
  383. writeln(stderr,'Rip changed to ',
  384. hexstr(int64(@JumpToHandleErrorFrame),16), ' error=', err);
  385. end;
  386. {$endif SYSTEMEXCEPTIONDEBUG}
  387. end;
  388. end;
  389. syswin64_x86_64_exception_handler := res;
  390. end;
  391. procedure install_exception_handlers;
  392. begin
  393. AddVectoredExceptionHandler(1,@syswin64_x86_64_exception_handler);
  394. end;
  395. {$endif ndef FPC_USE_WIN64_SEH}
  396. procedure LinkIn(p1,p2,p3: Pointer); inline;
  397. begin
  398. end;
  399. procedure _FPC_mainCRTStartup;stdcall;public name '_mainCRTStartup';
  400. begin
  401. IsConsole:=true;
  402. GetConsoleMode(GetStdHandle((Std_Input_Handle)),@StartupConsoleMode);
  403. {$ifdef FPC_USE_TLS_DIRECTORY}
  404. LinkIn(@_tls_used,@FreePascal_TLS_callback,@FreePascal_end_of_TLS_callback);
  405. {$endif FPC_USE_TLS_DIRECTORY}
  406. Exe_entry;
  407. end;
  408. procedure _FPC_WinMainCRTStartup;stdcall;public name '_WinMainCRTStartup';
  409. begin
  410. IsConsole:=false;
  411. {$ifdef FPC_USE_TLS_DIRECTORY}
  412. LinkIn(@_tls_used,@FreePascal_TLS_callback,@FreePascal_end_of_TLS_callback);
  413. {$endif FPC_USE_TLS_DIRECTORY}
  414. Exe_entry;
  415. end;
  416. {$ifdef FPC_SECTION_THREADVARS}
  417. function fpc_tls_add(addr: pointer): pointer; assembler; nostackframe;
  418. [public,alias: 'FPC_TLS_ADD']; compilerproc;
  419. asm
  420. sub $56,%rsp { 32 spill area + 16 local vars + 8 misalignment }
  421. .seh_stackalloc 56
  422. .seh_endprologue
  423. lea tls_data_start(%rip),%rax
  424. sub %rax,%rcx
  425. cmpb $0,IsLibrary(%rip)
  426. mov _tls_index(%rip),%eax
  427. jnz .L1
  428. mov %gs:(88),%rdx
  429. add (%rdx,%rax,8),%rcx
  430. mov %rcx,%rax
  431. jmp .L3
  432. .L1:
  433. mov %rcx,32(%rsp)
  434. call GetLastError
  435. mov %rax,40(%rsp) { save LastError }
  436. mov _tls_index(%rip),%ecx
  437. call TlsGetValue
  438. test %rax,%rax
  439. jnz .L2
  440. { This can happen when a thread existed before DLL was loaded,
  441. or if DisableThreadLibraryCalls was called. }
  442. call SysAllocateThreadVars
  443. mov $0x1000000,%rcx
  444. call InitThread
  445. mov _tls_index(%rip),%ecx
  446. call TlsGetValue
  447. .L2:
  448. add %rax,32(%rsp)
  449. mov 40(%rsp),%rcx
  450. call SetLastError
  451. mov 32(%rsp),%rax
  452. .L3:
  453. add $56,%rsp
  454. end;
  455. {$endif FPC_SECTION_THREADVARS}
  456. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt;
  457. type
  458. tdosheader = packed record
  459. e_magic : word;
  460. e_cblp : word;
  461. e_cp : word;
  462. e_crlc : word;
  463. e_cparhdr : word;
  464. e_minalloc : word;
  465. e_maxalloc : word;
  466. e_ss : word;
  467. e_sp : word;
  468. e_csum : word;
  469. e_ip : word;
  470. e_cs : word;
  471. e_lfarlc : word;
  472. e_ovno : word;
  473. e_res : array[0..3] of word;
  474. e_oemid : word;
  475. e_oeminfo : word;
  476. e_res2 : array[0..9] of word;
  477. e_lfanew : longint;
  478. end;
  479. tpeheader = packed record
  480. PEMagic : longint;
  481. Machine : word;
  482. NumberOfSections : word;
  483. TimeDateStamp : longint;
  484. PointerToSymbolTable : longint;
  485. NumberOfSymbols : longint;
  486. SizeOfOptionalHeader : word;
  487. Characteristics : word;
  488. Magic : word;
  489. MajorLinkerVersion : byte;
  490. MinorLinkerVersion : byte;
  491. SizeOfCode : longint;
  492. SizeOfInitializedData : longint;
  493. SizeOfUninitializedData : longint;
  494. AddressOfEntryPoint : longint;
  495. BaseOfCode : longint;
  496. {$ifdef win32}
  497. BaseOfData : longint;
  498. {$endif win32}
  499. ImageBase : PtrInt;
  500. SectionAlignment : longint;
  501. FileAlignment : longint;
  502. MajorOperatingSystemVersion : word;
  503. MinorOperatingSystemVersion : word;
  504. MajorImageVersion : word;
  505. MinorImageVersion : word;
  506. MajorSubsystemVersion : word;
  507. MinorSubsystemVersion : word;
  508. Reserved1 : longint;
  509. SizeOfImage : longint;
  510. SizeOfHeaders : longint;
  511. CheckSum : longint;
  512. Subsystem : word;
  513. DllCharacteristics : word;
  514. SizeOfStackReserve : PtrInt;
  515. SizeOfStackCommit : PtrInt;
  516. SizeOfHeapReserve : PtrInt;
  517. SizeOfHeapCommit : PtrInt;
  518. LoaderFlags : longint;
  519. NumberOfRvaAndSizes : longint;
  520. DataDirectory : array[1..$80] of byte;
  521. end;
  522. begin
  523. result:=tpeheader((pointer(getmodulehandle(nil))+(tdosheader(pointer(getmodulehandle(nil))^).e_lfanew))^).SizeOfStackReserve;
  524. end;
  525. begin
  526. { pass dummy value }
  527. StackLength := CheckInitialStkLen($1000000);
  528. StackBottom := StackTop - StackLength;
  529. { get some helpful informations }
  530. GetStartupInfo(@startupinfo);
  531. { some misc Win32 stuff }
  532. if not IsLibrary then
  533. SysInstance:=getmodulehandle(nil);
  534. MainInstance:=SysInstance;
  535. cmdshow:=startupinfo.wshowwindow;
  536. { Setup heap and threading, these may be already initialized from TLS callback }
  537. if not Assigned(CurrentTM.BeginThread) then
  538. begin
  539. InitHeap;
  540. InitSystemThreads;
  541. end;
  542. SysInitExceptions;
  543. initunicodestringmanager;
  544. InitWin32Widestrings;
  545. SysInitStdIO;
  546. { Arguments }
  547. setup_arguments;
  548. { Reset IO Error }
  549. InOutRes:=0;
  550. ProcessID := GetCurrentProcessID;
  551. DispCallByIDProc:=@DoDispCallByIDError;
  552. end.