system.pp 17 KB

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