2
0

system.pp 14 KB

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