system.pp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. { include system independent routines }
  102. {$I system.inc}
  103. {*****************************************************************************
  104. System Dependent Exit code
  105. *****************************************************************************}
  106. procedure install_exception_handlers;forward;
  107. procedure remove_exception_handlers;forward;
  108. procedure PascalMain;stdcall;external name 'PASCALMAIN';
  109. procedure fpc_do_exit;stdcall;external name 'FPC_DO_EXIT';
  110. Procedure ExitDLL(Exitcode : longint); forward;
  111. Procedure system_exit;
  112. begin
  113. { don't call ExitProcess inside
  114. the DLL exit code !!
  115. This crashes Win95 at least PM }
  116. if IsLibrary then
  117. ExitDLL(ExitCode);
  118. if not IsConsole then
  119. begin
  120. Close(stderr);
  121. Close(stdout);
  122. Close(erroutput);
  123. Close(Input);
  124. Close(Output);
  125. { what about Input and Output ?? PM }
  126. { now handled, FPK }
  127. end;
  128. remove_exception_handlers;
  129. { call exitprocess, with cleanup as required }
  130. ExitProcess(exitcode);
  131. end;
  132. var
  133. { old compilers emitted a reference to _fltused if a module contains
  134. floating type code so the linker could leave away floating point
  135. libraries or not. VC does this as well so we need to define this
  136. symbol as well (FK)
  137. }
  138. _fltused : int64;cvar;public;
  139. { value of the stack segment
  140. to check if the call stack can be written on exceptions }
  141. _SS : Cardinal;
  142. procedure Exe_entry;[public,alias:'_FPC_EXE_Entry'];
  143. var
  144. ST : pointer;
  145. begin
  146. IsLibrary:=false;
  147. { install the handlers for exe only ?
  148. or should we install them for DLL also ? (PM) }
  149. install_exception_handlers;
  150. ExitCode:=0;
  151. asm
  152. movq %rsp,%rax
  153. movq %rax,st
  154. end;
  155. StackTop:=st;
  156. asm
  157. xorq %rax,%rax
  158. movw %ss,%ax
  159. movl %eax,_SS(%rip)
  160. movq %rbp,%rsi
  161. xorq %rbp,%rbp
  162. call PASCALMAIN
  163. movq %rsi,%rbp
  164. end ['RSI','RBP']; { <-- specifying RSI allows compiler to save/restore it properly }
  165. { if we pass here there was no error ! }
  166. system_exit;
  167. end;
  168. function Dll_entry{$ifdef FPC_HAS_INDIRECT_MAIN_INFORMATION}(const info : TEntryInformation){$endif FPC_HAS_INDIRECT_MAIN_INFORMATION} : longbool;forward;
  169. procedure _FPC_DLLMainCRTStartup(_hinstance : qword;_dllreason : dword;_dllparam:Pointer);stdcall;public name '_DLLMainCRTStartup';
  170. begin
  171. IsConsole:=true;
  172. sysinstance:=_hinstance;
  173. dllreason:=_dllreason;
  174. dllparam:=PtrInt(_dllparam);
  175. DLL_Entry;
  176. end;
  177. procedure _FPC_DLLWinMainCRTStartup(_hinstance : qword;_dllreason : dword;_dllparam:Pointer);stdcall;public name '_DLLWinMainCRTStartup';
  178. begin
  179. IsConsole:=false;
  180. sysinstance:=_hinstance;
  181. dllreason:=_dllreason;
  182. dllparam:=PtrInt(_dllparam);
  183. DLL_Entry;
  184. end;
  185. function is_prefetch(p : pointer) : boolean;
  186. var
  187. a : array[0..15] of byte;
  188. doagain : boolean;
  189. instrlo,instrhi,opcode : byte;
  190. i : longint;
  191. begin
  192. result:=false;
  193. { read memory savely without causing another exeception }
  194. if not(ReadProcessMemory(GetCurrentProcess,p,@a,sizeof(a),nil)) then
  195. exit;
  196. i:=0;
  197. doagain:=true;
  198. while doagain and (i<15) do
  199. begin
  200. opcode:=a[i];
  201. instrlo:=opcode and $f;
  202. instrhi:=opcode and $f0;
  203. case instrhi of
  204. { prefix? }
  205. $20,$30:
  206. doagain:=(instrlo and 7)=6;
  207. $60:
  208. doagain:=(instrlo and $c)=4;
  209. $f0:
  210. doagain:=instrlo in [0,2,3];
  211. $0:
  212. begin
  213. result:=(instrlo=$f) and (a[i+1] in [$d,$18]);
  214. exit;
  215. end;
  216. else
  217. doagain:=false;
  218. end;
  219. inc(i);
  220. end;
  221. end;
  222. {******************************************************************************}
  223. { include code common with win64 }
  224. {$I syswin.inc}
  225. {******************************************************************************}
  226. //
  227. // Hardware exception handling
  228. //
  229. {$I seh64.inc}
  230. type
  231. TVectoredExceptionHandler = function (excep : PExceptionPointers) : Longint;
  232. function AddVectoredExceptionHandler(FirstHandler : DWORD;VectoredHandler : TVectoredExceptionHandler) : longint;
  233. external 'kernel32' name 'AddVectoredExceptionHandler';
  234. const
  235. MaxExceptionLevel = 16;
  236. exceptLevel : Byte = 0;
  237. var
  238. exceptRip : array[0..MaxExceptionLevel-1] of Int64;
  239. exceptError : array[0..MaxExceptionLevel-1] of Byte;
  240. resetFPU : array[0..MaxExceptionLevel-1] of Boolean;
  241. {$ifdef SYSTEMEXCEPTIONDEBUG}
  242. procedure DebugHandleErrorAddrFrame(error : longint; addr, frame : pointer);
  243. begin
  244. if IsConsole then
  245. begin
  246. write(stderr,'HandleErrorAddrFrame(error=',error);
  247. write(stderr,',addr=',hexstr(int64(addr),16));
  248. writeln(stderr,',frame=',hexstr(int64(frame),16),')');
  249. end;
  250. HandleErrorAddrFrame(error,addr,frame);
  251. end;
  252. {$endif SYSTEMEXCEPTIONDEBUG}
  253. procedure JumpToHandleErrorFrame;
  254. var
  255. rip, rbp : int64;
  256. error : longint;
  257. begin
  258. // save ebp
  259. asm
  260. movq (%rbp),%rax
  261. movq %rax,rbp
  262. end;
  263. if exceptLevel>0 then
  264. dec(exceptLevel);
  265. rip:=exceptRip[exceptLevel];
  266. error:=exceptError[exceptLevel];
  267. {$ifdef SYSTEMEXCEPTIONDEBUG}
  268. if IsConsole then
  269. writeln(stderr,'In JumpToHandleErrorFrame error=',error);
  270. {$endif SYSTEMEXCEPTIONDEBUG}
  271. if resetFPU[exceptLevel] then
  272. SysResetFPU;
  273. { build a fake stack }
  274. asm
  275. movq rbp,%r8
  276. movq rip,%rdx
  277. movl error,%ecx
  278. pushq rip
  279. movq rbp,%rbp // Change frame pointer
  280. {$ifdef SYSTEMEXCEPTIONDEBUG}
  281. jmpl DebugHandleErrorAddrFrame
  282. {$else not SYSTEMEXCEPTIONDEBUG}
  283. jmpl HandleErrorAddrFrame
  284. {$endif SYSTEMEXCEPTIONDEBUG}
  285. end;
  286. end;
  287. function syswin64_x86_64_exception_handler(excep : PExceptionPointers) : Longint;public;
  288. var
  289. res: longint;
  290. err: byte;
  291. must_reset_fpu: boolean;
  292. begin
  293. res:=EXCEPTION_CONTINUE_SEARCH;
  294. {$ifdef SYSTEMEXCEPTIONDEBUG}
  295. if IsConsole then
  296. Writeln(stderr,'syswin64_x86_64_exception_handler called');
  297. {$endif SYSTEMEXCEPTIONDEBUG}
  298. if excep^.ContextRecord^.SegSs=_SS then
  299. begin
  300. err := 0;
  301. must_reset_fpu := true;
  302. {$ifdef SYSTEMEXCEPTIONDEBUG}
  303. if IsConsole then Writeln(stderr,'Exception ',
  304. hexstr(excep^.ExceptionRecord^.ExceptionCode,8));
  305. {$endif SYSTEMEXCEPTIONDEBUG}
  306. case cardinal(excep^.ExceptionRecord^.ExceptionCode) of
  307. STATUS_INTEGER_DIVIDE_BY_ZERO,
  308. STATUS_FLOAT_DIVIDE_BY_ZERO :
  309. err := 200;
  310. STATUS_ARRAY_BOUNDS_EXCEEDED :
  311. begin
  312. err := 201;
  313. must_reset_fpu := false;
  314. end;
  315. STATUS_STACK_OVERFLOW :
  316. begin
  317. err := 202;
  318. must_reset_fpu := false;
  319. end;
  320. STATUS_FLOAT_OVERFLOW :
  321. err := 205;
  322. STATUS_FLOAT_DENORMAL_OPERAND,
  323. STATUS_FLOAT_UNDERFLOW :
  324. err := 206;
  325. { excep^.ContextRecord^.FloatSave.StatusWord := excep^.ContextRecord^.FloatSave.StatusWord and $ffffff00;}
  326. STATUS_FLOAT_INEXACT_RESULT,
  327. STATUS_FLOAT_INVALID_OPERATION,
  328. STATUS_FLOAT_STACK_CHECK :
  329. err := 207;
  330. STATUS_INTEGER_OVERFLOW :
  331. begin
  332. err := 215;
  333. must_reset_fpu := false;
  334. end;
  335. STATUS_ILLEGAL_INSTRUCTION:
  336. err := 216;
  337. STATUS_ACCESS_VIOLATION:
  338. { Athlon prefetch bug? }
  339. if is_prefetch(pointer(excep^.ContextRecord^.rip)) then
  340. begin
  341. { if yes, then retry }
  342. excep^.ExceptionRecord^.ExceptionCode := 0;
  343. res:=EXCEPTION_CONTINUE_EXECUTION;
  344. end
  345. else
  346. err := 216;
  347. STATUS_CONTROL_C_EXIT:
  348. err := 217;
  349. STATUS_PRIVILEGED_INSTRUCTION:
  350. begin
  351. err := 218;
  352. must_reset_fpu := false;
  353. end;
  354. else
  355. begin
  356. if ((excep^.ExceptionRecord^.ExceptionCode and SEVERITY_ERROR) = SEVERITY_ERROR) then
  357. err := 217
  358. else
  359. { pass through exceptions which aren't an error. The problem is that vectored handlers
  360. always are called before structured ones so we see also internal exceptions of libraries.
  361. I wonder if there is a better solution (FK)
  362. }
  363. res:=EXCEPTION_CONTINUE_SEARCH;
  364. end;
  365. end;
  366. if (err <> 0) and (exceptLevel < MaxExceptionLevel) then
  367. begin
  368. exceptRip[exceptLevel] := excep^.ContextRecord^.Rip;
  369. exceptError[exceptLevel] := err;
  370. resetFPU[exceptLevel] := must_reset_fpu;
  371. inc(exceptLevel);
  372. excep^.ContextRecord^.Rip := Int64(@JumpToHandleErrorFrame);
  373. excep^.ExceptionRecord^.ExceptionCode := 0;
  374. res := EXCEPTION_CONTINUE_EXECUTION;
  375. {$ifdef SYSTEMEXCEPTIONDEBUG}
  376. if IsConsole then begin
  377. writeln(stderr,'Exception Continue Exception set at ',
  378. hexstr(exceptRip[exceptLevel-1],16));
  379. writeln(stderr,'Rip changed to ',
  380. hexstr(int64(@JumpToHandleErrorFrame),16), ' error=', err);
  381. end;
  382. {$endif SYSTEMEXCEPTIONDEBUG}
  383. end;
  384. end;
  385. syswin64_x86_64_exception_handler := res;
  386. end;
  387. procedure install_exception_handlers;
  388. begin
  389. AddVectoredExceptionHandler(1,@syswin64_x86_64_exception_handler);
  390. end;
  391. procedure remove_exception_handlers;
  392. begin
  393. end;
  394. procedure fpc_cpucodeinit;
  395. begin
  396. end;
  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. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt;assembler;
  418. asm
  419. movq %gs:(8),%rax
  420. subq %gs:(16),%rax
  421. end;
  422. begin
  423. { pass dummy value }
  424. StackLength := CheckInitialStkLen($1000000);
  425. StackBottom := StackTop - StackLength;
  426. { get some helpful informations }
  427. GetStartupInfo(@startupinfo);
  428. { some misc Win32 stuff }
  429. if not IsLibrary then
  430. SysInstance:=getmodulehandle(nil);
  431. MainInstance:=SysInstance;
  432. cmdshow:=startupinfo.wshowwindow;
  433. { Setup heap and threading, these may be already initialized from TLS callback }
  434. if not Assigned(CurrentTM.BeginThread) then
  435. begin
  436. InitHeap;
  437. InitSystemThreads;
  438. end;
  439. SysInitExceptions;
  440. { setup fastmove stuff }
  441. fpc_cpucodeinit;
  442. initwidestringmanager;
  443. initunicodestringmanager;
  444. InitWin32Widestrings;
  445. SysInitStdIO;
  446. { Arguments }
  447. setup_arguments;
  448. { Reset IO Error }
  449. InOutRes:=0;
  450. ProcessID := GetCurrentProcessID;
  451. { Reset internal error variable }
  452. errno:=0;
  453. initvariantmanager;
  454. DispCallByIDProc:=@DoDispCallByIDError;
  455. end.