system.pp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 FPC_IS_SYSTEM}
  15. { $define SYSTEMEXCEPTIONDEBUG}
  16. {$ifdef SYSTEMDEBUG}
  17. {$define SYSTEMEXCEPTIONDEBUG}
  18. {$endif SYSTEMDEBUG}
  19. {$define DISABLE_NO_THREAD_MANAGER}
  20. {$define HAS_WIDESTRINGMANAGER}
  21. {$define DISABLE_NO_DYNLIBS_MANAGER}
  22. {$define FPC_SYSTEM_HAS_SYSDLH}
  23. {$define FPC_HAS_SETCTRLBREAKHANDLER}
  24. {$if defined(FPC_USE_WIN64_SEH) or defined(CPUAARCH64)}
  25. {$define SYSTEM_USE_WIN_SEH}
  26. {$endif}
  27. {$ifdef SYSTEM_USE_WIN_SEH}
  28. {$define FPC_SYSTEM_HAS_RAISEEXCEPTION}
  29. {$define FPC_SYSTEM_HAS_RERAISE}
  30. {$define FPC_SYSTEM_HAS_CAPTUREBACKTRACE}
  31. {$endif SYSTEM_USE_WIN_SEH}
  32. { include system-independent routine headers }
  33. {$I systemh.inc}
  34. { include common windows headers }
  35. {$I syswinh.inc}
  36. var
  37. MainInstance : qword;
  38. implementation
  39. var
  40. {$ifdef VER3_0}
  41. SysInstance : qword;
  42. FPCSysInstance: PQWord = @SysInstance; public name '_FPC_SysInstance';
  43. {$else VER3_0}
  44. FPCSysInstance : PQWord;public name '_FPC_SysInstance';
  45. {$endif VER3_0}
  46. {$define FPC_SYSTEM_HAS_OSSETUPENTRYINFORMATION}
  47. procedure OsSetupEntryInformation(constref info: TEntryInformation); forward;
  48. procedure SetupEntryInformation(constref info: TEntryInformation);forward;
  49. {$define FPC_SYSTEM_HAS_STACKTOP}
  50. function main_wrapper(arg: Pointer; proc: Pointer): ptrint; forward;
  51. { include system independent routines }
  52. {$I system.inc}
  53. {$I cpuwin.inc}
  54. {*****************************************************************************
  55. System Dependent Exit code
  56. *****************************************************************************}
  57. {$ifndef SYSTEM_USE_WIN_SEH}
  58. procedure install_exception_handlers;forward;
  59. {$endif SYSTEM_USE_WIN_SEH}
  60. {$ifdef VER3_0}
  61. procedure PascalMain;external name 'PASCALMAIN';
  62. {$endif VER3_0}
  63. { include code common with win32 }
  64. {$I syswin.inc}
  65. {$ifdef VER3_0}
  66. { TLS directory code }
  67. {$I systlsdir.inc}
  68. {$endif VER3_0}
  69. procedure OsSetupEntryInformation(constref info: TEntryInformation);
  70. begin
  71. TlsKey := info.OS.TlsKeyAddr;
  72. FPCSysInstance := info.OS.SysInstance;
  73. WStrInitTablesTable := info.OS.WideInitTables;
  74. end;
  75. Procedure system_exit;
  76. begin
  77. { see comments in win32/system.pp about this logic }
  78. if IsLibrary then
  79. begin
  80. if DllInitState in [DLL_PROCESS_ATTACH,DLL_PROCESS_DETACH] then
  81. LongJmp(DLLBuf,1)
  82. else
  83. MainThreadIDWin32:=0;
  84. end;
  85. if not IsConsole then
  86. begin
  87. Close(stderr);
  88. Close(stdout);
  89. Close(erroutput);
  90. Close(Input);
  91. Close(Output);
  92. { what about Input and Output ?? PM }
  93. { now handled, FPK }
  94. end;
  95. if Ole32Dll <> 0 then
  96. begin
  97. WinFreeLibrary(Ole32Dll); { Careful, FreeLibrary should not be called from DllMain. }
  98. Ole32Dll := 0;
  99. end;
  100. { call exitprocess, with cleanup as required }
  101. ExitProcess(exitcode);
  102. end;
  103. {$ifdef VER3_0}
  104. procedure _FPC_DLLMainCRTStartup(_hinstance : qword;_dllreason : dword;_dllparam:Pointer);stdcall;public name '_DLLMainCRTStartup';
  105. begin
  106. IsConsole:=true;
  107. sysinstance:=_hinstance;
  108. dllreason:=_dllreason;
  109. dllparam:=PtrInt(_dllparam);
  110. DLL_Entry;
  111. end;
  112. procedure _FPC_DLLWinMainCRTStartup(_hinstance : qword;_dllreason : dword;_dllparam:Pointer);stdcall;public name '_DLLWinMainCRTStartup';
  113. begin
  114. IsConsole:=false;
  115. sysinstance:=_hinstance;
  116. dllreason:=_dllreason;
  117. dllparam:=PtrInt(_dllparam);
  118. DLL_Entry;
  119. end;
  120. {$endif VER3_0}
  121. //
  122. // Hardware exception handling
  123. //
  124. {$I seh64.inc}
  125. type
  126. TVectoredExceptionHandler = function (excep : PExceptionPointers) : Longint;
  127. function AddVectoredExceptionHandler(FirstHandler : DWORD;VectoredHandler : TVectoredExceptionHandler) : longint;
  128. external 'kernel32' name 'AddVectoredExceptionHandler';
  129. {$ifndef SYSTEM_USE_WIN_SEH}
  130. const
  131. MaxExceptionLevel = 16;
  132. exceptLevel : Byte = 0;
  133. var
  134. exceptRip : array[0..MaxExceptionLevel-1] of Int64;
  135. exceptError : array[0..MaxExceptionLevel-1] of Byte;
  136. resetFPU : array[0..MaxExceptionLevel-1] of Boolean;
  137. {$ifdef SYSTEMEXCEPTIONDEBUG}
  138. procedure DebugHandleErrorAddrFrame(error : longint; addr, frame : pointer);
  139. begin
  140. if IsConsole then
  141. begin
  142. write(stderr,'HandleErrorAddrFrame(error=',error);
  143. write(stderr,',addr=',hexstr(int64(addr),16));
  144. writeln(stderr,',frame=',hexstr(int64(frame),16),')');
  145. end;
  146. HandleErrorAddrFrame(error,addr,frame);
  147. end;
  148. {$endif SYSTEMEXCEPTIONDEBUG}
  149. procedure JumpToHandleErrorFrame;
  150. var
  151. rip, rbp : int64;
  152. error : longint;
  153. begin
  154. // save ebp
  155. {$ifdef CPUX86_64}
  156. asm
  157. movq (%rbp),%rax
  158. movq %rax,rbp
  159. end;
  160. {$endif}
  161. if exceptLevel>0 then
  162. dec(exceptLevel);
  163. rip:=exceptRip[exceptLevel];
  164. error:=exceptError[exceptLevel];
  165. {$ifdef SYSTEMEXCEPTIONDEBUG}
  166. if IsConsole then
  167. writeln(stderr,'In JumpToHandleErrorFrame error=',error);
  168. {$endif SYSTEMEXCEPTIONDEBUG}
  169. if resetFPU[exceptLevel] then
  170. SysResetFPU;
  171. { build a fake stack }
  172. {$ifdef CPUX86_64}
  173. asm
  174. movq rbp,%r8
  175. movq rip,%rdx
  176. movl error,%ecx
  177. pushq rip
  178. movq rbp,%rbp // Change frame pointer
  179. {$ifdef SYSTEMEXCEPTIONDEBUG}
  180. jmpl DebugHandleErrorAddrFrame
  181. {$else not SYSTEMEXCEPTIONDEBUG}
  182. jmpl HandleErrorAddrFrame
  183. {$endif SYSTEMEXCEPTIONDEBUG}
  184. end;
  185. {$endif}
  186. end;
  187. function syswin64_x86_64_exception_handler(excep : PExceptionPointers) : Longint;public;
  188. var
  189. res: longint;
  190. err: byte;
  191. must_reset_fpu: boolean;
  192. begin
  193. res:=EXCEPTION_CONTINUE_SEARCH;
  194. {$ifdef SYSTEMEXCEPTIONDEBUG}
  195. if IsConsole then
  196. Writeln(stderr,'syswin64_x86_64_exception_handler called');
  197. {$endif SYSTEMEXCEPTIONDEBUG}
  198. if excep^.ContextRecord^.SegSs=_SS then
  199. begin
  200. err := 0;
  201. must_reset_fpu := true;
  202. {$ifdef SYSTEMEXCEPTIONDEBUG}
  203. if IsConsole then Writeln(stderr,'Exception ',
  204. hexstr(excep^.ExceptionRecord^.ExceptionCode,8));
  205. {$endif SYSTEMEXCEPTIONDEBUG}
  206. case cardinal(excep^.ExceptionRecord^.ExceptionCode) of
  207. STATUS_INTEGER_DIVIDE_BY_ZERO,
  208. STATUS_FLOAT_DIVIDE_BY_ZERO :
  209. err := 208;
  210. STATUS_ARRAY_BOUNDS_EXCEEDED :
  211. begin
  212. err := 201;
  213. must_reset_fpu := false;
  214. end;
  215. STATUS_STACK_OVERFLOW :
  216. begin
  217. err := 202;
  218. must_reset_fpu := false;
  219. end;
  220. STATUS_FLOAT_OVERFLOW :
  221. err := 205;
  222. STATUS_FLOAT_DENORMAL_OPERAND,
  223. STATUS_FLOAT_UNDERFLOW :
  224. err := 206;
  225. { excep^.ContextRecord^.FloatSave.StatusWord := excep^.ContextRecord^.FloatSave.StatusWord and $ffffff00;}
  226. STATUS_FLOAT_INEXACT_RESULT,
  227. STATUS_FLOAT_INVALID_OPERATION,
  228. STATUS_FLOAT_STACK_CHECK :
  229. err := 207;
  230. STATUS_INTEGER_OVERFLOW :
  231. begin
  232. err := 215;
  233. must_reset_fpu := false;
  234. end;
  235. STATUS_ILLEGAL_INSTRUCTION:
  236. err := 216;
  237. STATUS_ACCESS_VIOLATION:
  238. { Athlon prefetch bug? }
  239. if is_prefetch(pointer(excep^.ContextRecord^.rip)) then
  240. begin
  241. { if yes, then retry }
  242. excep^.ExceptionRecord^.ExceptionCode := 0;
  243. res:=EXCEPTION_CONTINUE_EXECUTION;
  244. end
  245. else
  246. err := 216;
  247. STATUS_CONTROL_C_EXIT:
  248. err := 217;
  249. STATUS_PRIVILEGED_INSTRUCTION:
  250. begin
  251. err := 218;
  252. must_reset_fpu := false;
  253. end;
  254. else
  255. begin
  256. if ((excep^.ExceptionRecord^.ExceptionCode and SEVERITY_ERROR) = SEVERITY_ERROR) then
  257. err := 217
  258. else
  259. { pass through exceptions which aren't an error. The problem is that vectored handlers
  260. always are called before structured ones so we see also internal exceptions of libraries.
  261. I wonder if there is a better solution (FK)
  262. }
  263. res:=EXCEPTION_CONTINUE_SEARCH;
  264. end;
  265. end;
  266. if (err <> 0) and (exceptLevel < MaxExceptionLevel) then
  267. begin
  268. exceptRip[exceptLevel] := excep^.ContextRecord^.Rip;
  269. exceptError[exceptLevel] := err;
  270. resetFPU[exceptLevel] := must_reset_fpu;
  271. inc(exceptLevel);
  272. excep^.ContextRecord^.Rip := Int64(@JumpToHandleErrorFrame);
  273. excep^.ExceptionRecord^.ExceptionCode := 0;
  274. res := EXCEPTION_CONTINUE_EXECUTION;
  275. {$ifdef SYSTEMEXCEPTIONDEBUG}
  276. if IsConsole then begin
  277. writeln(stderr,'Exception Continue Exception set at ',
  278. hexstr(exceptRip[exceptLevel-1],16));
  279. writeln(stderr,'Rip changed to ',
  280. hexstr(int64(@JumpToHandleErrorFrame),16), ' error=', err);
  281. end;
  282. {$endif SYSTEMEXCEPTIONDEBUG}
  283. end;
  284. end;
  285. syswin64_x86_64_exception_handler := res;
  286. end;
  287. procedure install_exception_handlers;
  288. begin
  289. AddVectoredExceptionHandler(1,@syswin64_x86_64_exception_handler);
  290. end;
  291. {$endif ndef SYSTEM_USE_WIN_SEH}
  292. {$ifdef VER3_0}
  293. procedure LinkIn(p1,p2,p3: Pointer); inline;
  294. begin
  295. end;
  296. procedure _FPC_mainCRTStartup;stdcall;public name '_mainCRTStartup';
  297. begin
  298. IsConsole:=true;
  299. GetConsoleMode(GetStdHandle((Std_Input_Handle)),@StartupConsoleMode);
  300. {$ifdef FPC_USE_TLS_DIRECTORY}
  301. LinkIn(@_tls_used,@FreePascal_TLS_callback,@FreePascal_end_of_TLS_callback);
  302. {$endif FPC_USE_TLS_DIRECTORY}
  303. Exe_entry;
  304. end;
  305. procedure _FPC_WinMainCRTStartup;stdcall;public name '_WinMainCRTStartup';
  306. begin
  307. IsConsole:=false;
  308. {$ifdef FPC_USE_TLS_DIRECTORY}
  309. LinkIn(@_tls_used,@FreePascal_TLS_callback,@FreePascal_end_of_TLS_callback);
  310. {$endif FPC_USE_TLS_DIRECTORY}
  311. Exe_entry;
  312. end;
  313. {$endif VER3_0}
  314. {$ifdef FPC_SECTION_THREADVARS}
  315. function fpc_tls_add(addr: pointer): pointer; assembler; nostackframe;
  316. [public,alias: 'FPC_TLS_ADD']; compilerproc;
  317. asm
  318. sub $56,%rsp { 32 spill area + 16 local vars + 8 misalignment }
  319. .seh_stackalloc 56
  320. .seh_endprologue
  321. lea tls_data_start(%rip),%rax
  322. sub %rax,%rcx
  323. cmpb $0,IsLibrary(%rip)
  324. mov _tls_index(%rip),%eax
  325. jnz .L1
  326. mov %gs:(88),%rdx
  327. add (%rdx,%rax,8),%rcx
  328. mov %rcx,%rax
  329. jmp .L3
  330. .L1:
  331. mov %rcx,32(%rsp)
  332. call GetLastError
  333. mov %rax,40(%rsp) { save LastError }
  334. mov _tls_index(%rip),%ecx
  335. call TlsGetValue
  336. test %rax,%rax
  337. jnz .L2
  338. { This can happen when a thread existed before DLL was loaded,
  339. or if DisableThreadLibraryCalls was called. }
  340. call SysAllocateThreadVars
  341. mov $0x1000000,%rcx
  342. call InitThread
  343. mov _tls_index(%rip),%ecx
  344. call TlsGetValue
  345. .L2:
  346. add %rax,32(%rsp)
  347. mov 40(%rsp),%rcx
  348. call SetLastError
  349. mov 32(%rsp),%rax
  350. .L3:
  351. add $56,%rsp
  352. end;
  353. {$endif FPC_SECTION_THREADVARS}
  354. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt;
  355. type
  356. tdosheader = packed record
  357. e_magic : word;
  358. e_cblp : word;
  359. e_cp : word;
  360. e_crlc : word;
  361. e_cparhdr : word;
  362. e_minalloc : word;
  363. e_maxalloc : word;
  364. e_ss : word;
  365. e_sp : word;
  366. e_csum : word;
  367. e_ip : word;
  368. e_cs : word;
  369. e_lfarlc : word;
  370. e_ovno : word;
  371. e_res : array[0..3] of word;
  372. e_oemid : word;
  373. e_oeminfo : word;
  374. e_res2 : array[0..9] of word;
  375. e_lfanew : longint;
  376. end;
  377. tpeheader = packed record
  378. PEMagic : longint;
  379. Machine : word;
  380. NumberOfSections : word;
  381. TimeDateStamp : longint;
  382. PointerToSymbolTable : longint;
  383. NumberOfSymbols : longint;
  384. SizeOfOptionalHeader : word;
  385. Characteristics : word;
  386. Magic : word;
  387. MajorLinkerVersion : byte;
  388. MinorLinkerVersion : byte;
  389. SizeOfCode : longint;
  390. SizeOfInitializedData : longint;
  391. SizeOfUninitializedData : longint;
  392. AddressOfEntryPoint : longint;
  393. BaseOfCode : longint;
  394. {$ifdef win32}
  395. BaseOfData : longint;
  396. {$endif win32}
  397. ImageBase : PtrInt;
  398. SectionAlignment : longint;
  399. FileAlignment : longint;
  400. MajorOperatingSystemVersion : word;
  401. MinorOperatingSystemVersion : word;
  402. MajorImageVersion : word;
  403. MinorImageVersion : word;
  404. MajorSubsystemVersion : word;
  405. MinorSubsystemVersion : word;
  406. Reserved1 : longint;
  407. SizeOfImage : longint;
  408. SizeOfHeaders : longint;
  409. CheckSum : longint;
  410. Subsystem : word;
  411. DllCharacteristics : word;
  412. SizeOfStackReserve : PtrInt;
  413. SizeOfStackCommit : PtrInt;
  414. SizeOfHeapReserve : PtrInt;
  415. SizeOfHeapCommit : PtrInt;
  416. LoaderFlags : longint;
  417. NumberOfRvaAndSizes : longint;
  418. DataDirectory : array[1..$80] of byte;
  419. end;
  420. begin
  421. result:=tpeheader((pointer(getmodulehandle(nil))+(tdosheader(pointer(getmodulehandle(nil))^).e_lfanew))^).SizeOfStackReserve;
  422. end;
  423. initialization
  424. { pass dummy value }
  425. StackLength := CheckInitialStkLen($1000000);
  426. StackBottom := StackTop - StackLength;
  427. SetThreadStackGuarantee(@StackMargin);
  428. { get some helpful informations }
  429. GetStartupInfo(@startupinfo);
  430. { some misc Win32 stuff }
  431. if not IsLibrary then
  432. FPCSysInstance^:=getmodulehandle(nil);
  433. MainInstance:=FPCSysInstance^;
  434. cmdshow:=startupinfo.wshowwindow;
  435. { Setup heap and threading, these may be already initialized from TLS callback }
  436. if not Assigned(CurrentTM.BeginThread) then
  437. begin
  438. InitHeap;
  439. InitSystemThreads;
  440. end;
  441. SysInitExceptions;
  442. initunicodestringmanager;
  443. InitWin32Widestrings;
  444. SysInitStdIO;
  445. { Arguments }
  446. setup_arguments;
  447. InitSystemDynLibs;
  448. { Reset IO Error }
  449. InOutRes:=0;
  450. ProcessID := GetCurrentProcessID;
  451. DispCallByIDProc:=@DoDispCallByIDError;
  452. finalization
  453. WinFinalizeSystem;
  454. end.