system.pp 17 KB

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