2
0

system.pp 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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. { include system-independent routine headers }
  19. {$I systemh.inc}
  20. const
  21. LineEnding = #13#10;
  22. LFNSupport = true;
  23. DirectorySeparator = '\';
  24. DriveSeparator = ':';
  25. PathSeparator = ';';
  26. { FileNameCaseSensitive is defined separately below!!! }
  27. maxExitCode = 65535;
  28. MaxPathLen = 260;
  29. type
  30. PEXCEPTION_FRAME = ^TEXCEPTION_FRAME;
  31. TEXCEPTION_FRAME = record
  32. next : PEXCEPTION_FRAME;
  33. handler : pointer;
  34. end;
  35. const
  36. { Default filehandles }
  37. UnusedHandle : THandle = THandle(-1);
  38. StdInputHandle : THandle = 0;
  39. StdOutputHandle : THandle = 0;
  40. StdErrorHandle : THandle = 0;
  41. FileNameCaseSensitive : boolean = true;
  42. CtrlZMarksEOF: boolean = true; (* #26 not considered as end of file *)
  43. sLineBreak = LineEnding;
  44. DefaultTextLineBreakStyle : TTextLineBreakStyle = tlbsCRLF;
  45. { Thread count for DLL }
  46. Thread_count : longint = 0;
  47. type
  48. TStartupInfo = record
  49. cb : longint;
  50. lpReserved : Pointer;
  51. lpDesktop : Pointer;
  52. lpTitle : Pointer;
  53. dwX : longint;
  54. dwY : longint;
  55. dwXSize : longint;
  56. dwYSize : longint;
  57. dwXCountChars : longint;
  58. dwYCountChars : longint;
  59. dwFillAttribute : longint;
  60. dwFlags : longint;
  61. wShowWindow : Word;
  62. cbReserved2 : Word;
  63. lpReserved2 : Pointer;
  64. hStdInput : THandle;
  65. hStdOutput : THandle;
  66. hStdError : THandle;
  67. end;
  68. var
  69. { C compatible arguments }
  70. argc : longint;
  71. argv : ppchar;
  72. { Win32 Info }
  73. startupinfo : tstartupinfo;
  74. hprevinst,
  75. MainInstance,
  76. cmdshow : longint;
  77. DLLreason,DLLparam:longint;
  78. type
  79. TDLL_Process_Entry_Hook = function (dllparam : longint) : longbool;
  80. TDLL_Entry_Hook = procedure (dllparam : longint);
  81. const
  82. Dll_Process_Attach_Hook : TDLL_Process_Entry_Hook = nil;
  83. Dll_Process_Detach_Hook : TDLL_Entry_Hook = nil;
  84. Dll_Thread_Attach_Hook : TDLL_Entry_Hook = nil;
  85. Dll_Thread_Detach_Hook : TDLL_Entry_Hook = nil;
  86. implementation
  87. var
  88. SysInstance : Longint;public;
  89. {$define HAS_RESOURCES}
  90. {$i winres.inc}
  91. { used by wstrings.inc because wstrings.inc is included before sysos.inc
  92. this is put here (FK) }
  93. function SysAllocStringLen(psz:pointer;len:dword):pointer;stdcall;
  94. external 'oleaut32.dll' name 'SysAllocStringLen';
  95. procedure SysFreeString(bstr:pointer);stdcall;
  96. external 'oleaut32.dll' name 'SysFreeString';
  97. function SysReAllocStringLen(var bstr:pointer;psz: pointer;
  98. len:dword): Integer; stdcall;external 'oleaut32.dll' name 'SysReAllocStringLen';
  99. { include system independent routines }
  100. {$I system.inc}
  101. {*****************************************************************************
  102. Parameter Handling
  103. *****************************************************************************}
  104. var
  105. ModuleName : array[0..255] of char;
  106. function GetCommandFile:pchar;
  107. begin
  108. GetModuleFileName(0,@ModuleName,255);
  109. GetCommandFile:=@ModuleName;
  110. end;
  111. procedure setup_arguments;
  112. var
  113. arglen,
  114. count : longint;
  115. argstart,
  116. pc,arg : pchar;
  117. quote : char;
  118. argvlen : longint;
  119. procedure allocarg(idx,len:longint);
  120. var
  121. oldargvlen : longint;
  122. begin
  123. if idx>=argvlen then
  124. begin
  125. oldargvlen:=argvlen;
  126. argvlen:=(idx+8) and (not 7);
  127. sysreallocmem(argv,argvlen*sizeof(pointer));
  128. fillchar(argv[oldargvlen],(argvlen-oldargvlen)*sizeof(pointer),0);
  129. end;
  130. { use realloc to reuse already existing memory }
  131. { always allocate, even if length is zero, since }
  132. { the arg. is still present! }
  133. sysreallocmem(argv[idx],len+1);
  134. end;
  135. begin
  136. SetupProcVars;
  137. { create commandline, it starts with the executed filename which is argv[0] }
  138. { Win32 passes the command NOT via the args, but via getmodulefilename}
  139. count:=0;
  140. argv:=nil;
  141. argvlen:=0;
  142. pc:=getcommandfile;
  143. Arglen:=0;
  144. repeat
  145. Inc(Arglen);
  146. until (pc[Arglen]=#0);
  147. allocarg(count,arglen);
  148. move(pc^,argv[count]^,arglen+1);
  149. { Setup cmdline variable }
  150. cmdline:=GetCommandLine;
  151. { process arguments }
  152. pc:=cmdline;
  153. {$IfDef SYSTEM_DEBUG_STARTUP}
  154. Writeln(stderr,'Win32 GetCommandLine is #',pc,'#');
  155. {$EndIf }
  156. while pc^<>#0 do
  157. begin
  158. { skip leading spaces }
  159. while pc^ in [#1..#32] do
  160. inc(pc);
  161. if pc^=#0 then
  162. break;
  163. { calc argument length }
  164. quote:=' ';
  165. argstart:=pc;
  166. arglen:=0;
  167. while (pc^<>#0) do
  168. begin
  169. case pc^ of
  170. #1..#32 :
  171. begin
  172. if quote<>' ' then
  173. inc(arglen)
  174. else
  175. break;
  176. end;
  177. '"' :
  178. begin
  179. if quote<>'''' then
  180. begin
  181. if pchar(pc+1)^<>'"' then
  182. begin
  183. if quote='"' then
  184. quote:=' '
  185. else
  186. quote:='"';
  187. end
  188. else
  189. inc(pc);
  190. end
  191. else
  192. inc(arglen);
  193. end;
  194. '''' :
  195. begin
  196. if quote<>'"' then
  197. begin
  198. if pchar(pc+1)^<>'''' then
  199. begin
  200. if quote='''' then
  201. quote:=' '
  202. else
  203. quote:='''';
  204. end
  205. else
  206. inc(pc);
  207. end
  208. else
  209. inc(arglen);
  210. end;
  211. else
  212. inc(arglen);
  213. end;
  214. inc(pc);
  215. end;
  216. { copy argument }
  217. { Don't copy the first one, it is already there.}
  218. If Count<>0 then
  219. begin
  220. allocarg(count,arglen);
  221. quote:=' ';
  222. pc:=argstart;
  223. arg:=argv[count];
  224. while (pc^<>#0) do
  225. begin
  226. case pc^ of
  227. #1..#32 :
  228. begin
  229. if quote<>' ' then
  230. begin
  231. arg^:=pc^;
  232. inc(arg);
  233. end
  234. else
  235. break;
  236. end;
  237. '"' :
  238. begin
  239. if quote<>'''' then
  240. begin
  241. if pchar(pc+1)^<>'"' then
  242. begin
  243. if quote='"' then
  244. quote:=' '
  245. else
  246. quote:='"';
  247. end
  248. else
  249. inc(pc);
  250. end
  251. else
  252. begin
  253. arg^:=pc^;
  254. inc(arg);
  255. end;
  256. end;
  257. '''' :
  258. begin
  259. if quote<>'"' then
  260. begin
  261. if pchar(pc+1)^<>'''' then
  262. begin
  263. if quote='''' then
  264. quote:=' '
  265. else
  266. quote:='''';
  267. end
  268. else
  269. inc(pc);
  270. end
  271. else
  272. begin
  273. arg^:=pc^;
  274. inc(arg);
  275. end;
  276. end;
  277. else
  278. begin
  279. arg^:=pc^;
  280. inc(arg);
  281. end;
  282. end;
  283. inc(pc);
  284. end;
  285. arg^:=#0;
  286. end;
  287. {$IfDef SYSTEM_DEBUG_STARTUP}
  288. Writeln(stderr,'dos arg ',count,' #',arglen,'#',argv[count],'#');
  289. {$EndIf SYSTEM_DEBUG_STARTUP}
  290. inc(count);
  291. end;
  292. { get argc and create an nil entry }
  293. argc:=count;
  294. allocarg(argc,0);
  295. { free unused memory }
  296. sysreallocmem(argv,(argc+1)*sizeof(pointer));
  297. end;
  298. function paramcount : longint;
  299. begin
  300. paramcount := argc - 1;
  301. end;
  302. function paramstr(l : longint) : string;
  303. begin
  304. if (l>=0) and (l<argc) then
  305. paramstr:=strpas(argv[l])
  306. else
  307. paramstr:='';
  308. end;
  309. procedure randomize;
  310. begin
  311. randseed:=GetTickCount;
  312. end;
  313. {*****************************************************************************
  314. System Dependent Exit code
  315. *****************************************************************************}
  316. procedure install_exception_handlers;forward;
  317. procedure remove_exception_handlers;forward;
  318. procedure PascalMain;stdcall;external name 'PASCALMAIN';
  319. procedure fpc_do_exit;stdcall;external name 'FPC_DO_EXIT';
  320. Procedure ExitDLL(Exitcode : longint); forward;
  321. Procedure system_exit;
  322. begin
  323. { don't call ExitProcess inside
  324. the DLL exit code !!
  325. This crashes Win95 at least PM }
  326. if IsLibrary then
  327. ExitDLL(ExitCode);
  328. if not IsConsole then
  329. begin
  330. Close(stderr);
  331. Close(stdout);
  332. Close(erroutput);
  333. Close(Input);
  334. Close(Output);
  335. { what about Input and Output ?? PM }
  336. { now handled, FPK }
  337. end;
  338. remove_exception_handlers;
  339. { call exitprocess, with cleanup as required }
  340. ExitProcess(exitcode);
  341. end;
  342. var
  343. { old compilers emitted a reference to _fltused if a module contains
  344. floating type code so the linker could leave away floating point
  345. libraries or not. VC does this as well so we need to define this
  346. symbol as well (FK)
  347. }
  348. _fltused : int64;cvar;public;
  349. { value of the stack segment
  350. to check if the call stack can be written on exceptions }
  351. _SS : Cardinal;
  352. procedure Exe_entry;[public,alias:'_FPC_EXE_Entry'];
  353. var
  354. ST : pointer;
  355. begin
  356. IsLibrary:=false;
  357. { install the handlers for exe only ?
  358. or should we install them for DLL also ? (PM) }
  359. install_exception_handlers;
  360. ExitCode:=0;
  361. asm
  362. { keep stack aligned }
  363. pushq $0
  364. pushq %rbp
  365. movq %rsp,%rax
  366. movq %rax,st
  367. end;
  368. StackTop:=st;
  369. asm
  370. xorl %rax,%rax
  371. movw %ss,%ax
  372. movl %eax,_SS
  373. call SysResetFPU
  374. xorl %rbp,%rbp
  375. call PASCALMAIN
  376. popq %rbp
  377. popq %rax
  378. end;
  379. { if we pass here there was no error ! }
  380. system_exit;
  381. end;
  382. Const
  383. { DllEntryPoint }
  384. DLL_PROCESS_ATTACH = 1;
  385. DLL_THREAD_ATTACH = 2;
  386. DLL_PROCESS_DETACH = 0;
  387. DLL_THREAD_DETACH = 3;
  388. Var
  389. DLLBuf : Jmp_buf;
  390. Const
  391. DLLExitOK : boolean = true;
  392. function Dll_entry : longbool;
  393. var
  394. res : longbool;
  395. begin
  396. IsLibrary:=true;
  397. Dll_entry:=false;
  398. case DLLreason of
  399. DLL_PROCESS_ATTACH :
  400. begin
  401. If SetJmp(DLLBuf) = 0 then
  402. begin
  403. if assigned(Dll_Process_Attach_Hook) then
  404. begin
  405. res:=Dll_Process_Attach_Hook(DllParam);
  406. if not res then
  407. exit(false);
  408. end;
  409. PASCALMAIN;
  410. Dll_entry:=true;
  411. end
  412. else
  413. Dll_entry:=DLLExitOK;
  414. end;
  415. DLL_THREAD_ATTACH :
  416. begin
  417. inclocked(Thread_count);
  418. {$warning Allocate Threadvars !}
  419. if assigned(Dll_Thread_Attach_Hook) then
  420. Dll_Thread_Attach_Hook(DllParam);
  421. Dll_entry:=true; { return value is ignored }
  422. end;
  423. DLL_THREAD_DETACH :
  424. begin
  425. declocked(Thread_count);
  426. if assigned(Dll_Thread_Detach_Hook) then
  427. Dll_Thread_Detach_Hook(DllParam);
  428. {$warning Release Threadvars !}
  429. Dll_entry:=true; { return value is ignored }
  430. end;
  431. DLL_PROCESS_DETACH :
  432. begin
  433. Dll_entry:=true; { return value is ignored }
  434. If SetJmp(DLLBuf) = 0 then
  435. begin
  436. FPC_DO_EXIT;
  437. end;
  438. if assigned(Dll_Process_Detach_Hook) then
  439. Dll_Process_Detach_Hook(DllParam);
  440. end;
  441. end;
  442. end;
  443. Procedure ExitDLL(Exitcode : longint);
  444. begin
  445. DLLExitOK:=ExitCode=0;
  446. LongJmp(DLLBuf,1);
  447. end;
  448. {$ifndef VER2_0}
  449. procedure _FPC_mainCRTStartup;stdcall;public name '_mainCRTStartup';
  450. begin
  451. IsConsole:=true;
  452. Exe_entry;
  453. end;
  454. procedure _FPC_WinMainCRTStartup;stdcall;public name '_WinMainCRTStartup';
  455. begin
  456. IsConsole:=false;
  457. Exe_entry;
  458. end;
  459. procedure _FPC_DLLMainCRTStartup(_hinstance,_dllreason,_dllparam:longint);stdcall;public name '_DLLMainCRTStartup';
  460. begin
  461. IsConsole:=true;
  462. sysinstance:=_hinstance;
  463. dllreason:=_dllreason;
  464. dllparam:=_dllparam;
  465. DLL_Entry;
  466. end;
  467. procedure _FPC_DLLWinMainCRTStartup(_hinstance,_dllreason,_dllparam:longint);stdcall;public name '_DLLWinMainCRTStartup';
  468. begin
  469. IsConsole:=false;
  470. sysinstance:=_hinstance;
  471. dllreason:=_dllreason;
  472. dllparam:=_dllparam;
  473. DLL_Entry;
  474. end;
  475. {$endif VER2_0}
  476. function GetCurrentProcess : dword;
  477. stdcall;external 'kernel32' name 'GetCurrentProcess';
  478. function ReadProcessMemory(process : dword;address : pointer;dest : pointer;size : dword;bytesread : pdword) : longbool;
  479. stdcall;external 'kernel32' name 'ReadProcessMemory';
  480. function is_prefetch(p : pointer) : boolean;
  481. var
  482. a : array[0..15] of byte;
  483. doagain : boolean;
  484. instrlo,instrhi,opcode : byte;
  485. i : longint;
  486. begin
  487. result:=false;
  488. { read memory savely without causing another exeception }
  489. if not(ReadProcessMemory(GetCurrentProcess,p,@a,sizeof(a),nil)) then
  490. exit;
  491. i:=0;
  492. doagain:=true;
  493. while doagain and (i<15) do
  494. begin
  495. opcode:=a[i];
  496. instrlo:=opcode and $f;
  497. instrhi:=opcode and $f0;
  498. case instrhi of
  499. { prefix? }
  500. $20,$30:
  501. doagain:=(instrlo and 7)=6;
  502. $60:
  503. doagain:=(instrlo and $c)=4;
  504. $f0:
  505. doagain:=instrlo in [0,2,3];
  506. $0:
  507. begin
  508. result:=(instrlo=$f) and (a[i+1] in [$d,$18]);
  509. exit;
  510. end;
  511. else
  512. doagain:=false;
  513. end;
  514. inc(i);
  515. end;
  516. end;
  517. //
  518. // Hardware exception handling
  519. //
  520. {
  521. Error code definitions for the Win32 API functions
  522. Values are 32 bit values layed out as follows:
  523. 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
  524. 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
  525. +---+-+-+-----------------------+-------------------------------+
  526. |Sev|C|R| Facility | Code |
  527. +---+-+-+-----------------------+-------------------------------+
  528. where
  529. Sev - is the severity code
  530. 00 - Success
  531. 01 - Informational
  532. 10 - Warning
  533. 11 - Error
  534. C - is the Customer code flag
  535. R - is a reserved bit
  536. Facility - is the facility code
  537. Code - is the facility's status code
  538. }
  539. const
  540. SEVERITY_SUCCESS = $00000000;
  541. SEVERITY_INFORMATIONAL = $40000000;
  542. SEVERITY_WARNING = $80000000;
  543. SEVERITY_ERROR = $C0000000;
  544. const
  545. STATUS_SEGMENT_NOTIFICATION = $40000005;
  546. DBG_TERMINATE_THREAD = $40010003;
  547. DBG_TERMINATE_PROCESS = $40010004;
  548. DBG_CONTROL_C = $40010005;
  549. DBG_CONTROL_BREAK = $40010008;
  550. STATUS_GUARD_PAGE_VIOLATION = $80000001;
  551. STATUS_DATATYPE_MISALIGNMENT = $80000002;
  552. STATUS_BREAKPOINT = $80000003;
  553. STATUS_SINGLE_STEP = $80000004;
  554. DBG_EXCEPTION_NOT_HANDLED = $80010001;
  555. STATUS_ACCESS_VIOLATION = $C0000005;
  556. STATUS_IN_PAGE_ERROR = $C0000006;
  557. STATUS_INVALID_HANDLE = $C0000008;
  558. STATUS_NO_MEMORY = $C0000017;
  559. STATUS_ILLEGAL_INSTRUCTION = $C000001D;
  560. STATUS_NONCONTINUABLE_EXCEPTION = $C0000025;
  561. STATUS_INVALID_DISPOSITION = $C0000026;
  562. STATUS_ARRAY_BOUNDS_EXCEEDED = $C000008C;
  563. STATUS_FLOAT_DENORMAL_OPERAND = $C000008D;
  564. STATUS_FLOAT_DIVIDE_BY_ZERO = $C000008E;
  565. STATUS_FLOAT_INEXACT_RESULT = $C000008F;
  566. STATUS_FLOAT_INVALID_OPERATION = $C0000090;
  567. STATUS_FLOAT_OVERFLOW = $C0000091;
  568. STATUS_FLOAT_STACK_CHECK = $C0000092;
  569. STATUS_FLOAT_UNDERFLOW = $C0000093;
  570. STATUS_INTEGER_DIVIDE_BY_ZERO = $C0000094;
  571. STATUS_INTEGER_OVERFLOW = $C0000095;
  572. STATUS_PRIVILEGED_INSTRUCTION = $C0000096;
  573. STATUS_STACK_OVERFLOW = $C00000FD;
  574. STATUS_CONTROL_C_EXIT = $C000013A;
  575. STATUS_FLOAT_MULTIPLE_FAULTS = $C00002B4;
  576. STATUS_FLOAT_MULTIPLE_TRAPS = $C00002B5;
  577. STATUS_REG_NAT_CONSUMPTION = $C00002C9;
  578. EXCEPTION_EXECUTE_HANDLER = 1;
  579. EXCEPTION_CONTINUE_EXECUTION = -1;
  580. EXCEPTION_CONTINUE_SEARCH = 0;
  581. EXCEPTION_MAXIMUM_PARAMETERS = 15;
  582. CONTEXT_X86 = $00010000;
  583. CONTEXT_CONTROL = CONTEXT_X86 or $00000001;
  584. CONTEXT_INTEGER = CONTEXT_X86 or $00000002;
  585. CONTEXT_SEGMENTS = CONTEXT_X86 or $00000004;
  586. CONTEXT_FLOATING_POINT = CONTEXT_X86 or $00000008;
  587. CONTEXT_DEBUG_REGISTERS = CONTEXT_X86 or $00000010;
  588. CONTEXT_EXTENDED_REGISTERS = CONTEXT_X86 or $00000020;
  589. CONTEXT_FULL = CONTEXT_CONTROL or CONTEXT_INTEGER or CONTEXT_SEGMENTS;
  590. MAXIMUM_SUPPORTED_EXTENSION = 512;
  591. type
  592. M128A = record
  593. Low : QWord;
  594. High : Int64;
  595. end;
  596. PContext = ^TContext;
  597. TContext = record
  598. P1Home : QWord;
  599. P2Home : QWord;
  600. P3Home : QWord;
  601. P4Home : QWord;
  602. P5Home : QWord;
  603. P6Home : QWord;
  604. ContextFlags : DWord;
  605. MxCsr : DWord;
  606. SegCs : word;
  607. SegDs : word;
  608. SegEs : word;
  609. SegFs : word;
  610. SegGs : word;
  611. SegSs : word;
  612. EFlags : DWord;
  613. Dr0 : QWord;
  614. Dr1 : QWord;
  615. Dr2 : QWord;
  616. Dr3 : QWord;
  617. Dr6 : QWord;
  618. Dr7 : QWord;
  619. Rax : QWord;
  620. Rcx : QWord;
  621. Rdx : QWord;
  622. Rbx : QWord;
  623. Rsp : QWord;
  624. Rbp : QWord;
  625. Rsi : QWord;
  626. Rdi : QWord;
  627. R8 : QWord;
  628. R9 : QWord;
  629. R10 : QWord;
  630. R11 : QWord;
  631. R12 : QWord;
  632. R13 : QWord;
  633. R14 : QWord;
  634. R15 : QWord;
  635. Rip : QWord;
  636. Header : array[0..1] of M128A;
  637. Legacy : array[0..7] of M128A;
  638. Xmm0 : M128A;
  639. Xmm1 : M128A;
  640. Xmm2 : M128A;
  641. Xmm3 : M128A;
  642. Xmm4 : M128A;
  643. Xmm5 : M128A;
  644. Xmm6 : M128A;
  645. Xmm7 : M128A;
  646. Xmm8 : M128A;
  647. Xmm9 : M128A;
  648. Xmm10 : M128A;
  649. Xmm11 : M128A;
  650. Xmm12 : M128A;
  651. Xmm13 : M128A;
  652. Xmm14 : M128A;
  653. Xmm15 : M128A;
  654. VectorRegister : array[0..25] of M128A;
  655. VectorControl : QWord;
  656. DebugControl : QWord;
  657. LastBranchToRip : QWord;
  658. LastBranchFromRip : QWord;
  659. LastExceptionToRip : QWord;
  660. LastExceptionFromRip : QWord;
  661. end;
  662. type
  663. PExceptionRecord = ^TExceptionRecord;
  664. TExceptionRecord = record
  665. ExceptionCode : DWord;
  666. ExceptionFlags : DWord;
  667. ExceptionRecord : PExceptionRecord;
  668. ExceptionAddress : Pointer;
  669. NumberParameters : DWord;
  670. ExceptionInformation : array[0..EXCEPTION_MAXIMUM_PARAMETERS-1] of Pointer;
  671. end;
  672. PExceptionPointers = ^TExceptionPointers;
  673. TExceptionPointers = packed record
  674. ExceptionRecord : PExceptionRecord;
  675. ContextRecord : PContext;
  676. end;
  677. TVectoredExceptionHandler = function (excep : PExceptionPointers) : Longint;
  678. function AddVectoredExceptionHandler(FirstHandler : DWORD;VectoredHandler : TVectoredExceptionHandler) : longint;
  679. external 'kernel32' name 'AddVectoredExceptionHandler';
  680. const
  681. MaxExceptionLevel = 16;
  682. exceptLevel : Byte = 0;
  683. var
  684. exceptRip : array[0..MaxExceptionLevel-1] of Int64;
  685. exceptError : array[0..MaxExceptionLevel-1] of Byte;
  686. resetFPU : array[0..MaxExceptionLevel-1] of Boolean;
  687. {$ifdef SYSTEMEXCEPTIONDEBUG}
  688. procedure DebugHandleErrorAddrFrame(error : longint; addr, frame : pointer);
  689. begin
  690. if IsConsole then
  691. begin
  692. write(stderr,'HandleErrorAddrFrame(error=',error);
  693. write(stderr,',addr=',hexstr(int64(addr),16));
  694. writeln(stderr,',frame=',hexstr(int64(frame),16),')');
  695. end;
  696. HandleErrorAddrFrame(error,addr,frame);
  697. end;
  698. {$endif SYSTEMEXCEPTIONDEBUG}
  699. procedure JumpToHandleErrorFrame;
  700. var
  701. rip, rbp : int64;
  702. error : longint;
  703. begin
  704. // save ebp
  705. asm
  706. movq (%rbp),%rax
  707. movq %rax,rbp
  708. end;
  709. if exceptLevel>0 then
  710. dec(exceptLevel);
  711. rip:=exceptRip[exceptLevel];
  712. error:=exceptError[exceptLevel];
  713. {$ifdef SYSTEMEXCEPTIONDEBUG}
  714. if IsConsole then
  715. writeln(stderr,'In JumpToHandleErrorFrame error=',error);
  716. {$endif SYSTEMEXCEPTIONDEBUG}
  717. if resetFPU[exceptLevel] then
  718. SysResetFPU;
  719. { build a fake stack }
  720. asm
  721. movq rbp,%r8
  722. movq rip,%rdx
  723. movl error,%ecx
  724. pushq rip
  725. movq rbp,%rbp // Change frame pointer
  726. {$ifdef SYSTEMEXCEPTIONDEBUG}
  727. jmpl DebugHandleErrorAddrFrame
  728. {$else not SYSTEMEXCEPTIONDEBUG}
  729. jmpl HandleErrorAddrFrame
  730. {$endif SYSTEMEXCEPTIONDEBUG}
  731. end;
  732. end;
  733. function syswin64_x86_64_exception_handler(excep : PExceptionPointers) : Longint;public;
  734. var
  735. res: longint;
  736. err: byte;
  737. must_reset_fpu: boolean;
  738. begin
  739. res:=EXCEPTION_CONTINUE_SEARCH;
  740. {$ifdef SYSTEMEXCEPTIONDEBUG}
  741. if IsConsole then
  742. Writeln(stderr,'syswin64_x86_64_exception_handler called');
  743. {$endif SYSTEMEXCEPTIONDEBUG}
  744. if excep^.ContextRecord^.SegSs=_SS then
  745. begin
  746. err := 0;
  747. must_reset_fpu := true;
  748. {$ifdef SYSTEMEXCEPTIONDEBUG}
  749. if IsConsole then Writeln(stderr,'Exception ',
  750. hexstr(excep^.ExceptionRecord^.ExceptionCode,8));
  751. {$endif SYSTEMEXCEPTIONDEBUG}
  752. case cardinal(excep^.ExceptionRecord^.ExceptionCode) of
  753. STATUS_INTEGER_DIVIDE_BY_ZERO,
  754. STATUS_FLOAT_DIVIDE_BY_ZERO :
  755. err := 200;
  756. STATUS_ARRAY_BOUNDS_EXCEEDED :
  757. begin
  758. err := 201;
  759. must_reset_fpu := false;
  760. end;
  761. STATUS_STACK_OVERFLOW :
  762. begin
  763. err := 202;
  764. must_reset_fpu := false;
  765. end;
  766. STATUS_FLOAT_OVERFLOW :
  767. err := 205;
  768. STATUS_FLOAT_DENORMAL_OPERAND,
  769. STATUS_FLOAT_UNDERFLOW :
  770. err := 206;
  771. { excep^.ContextRecord^.FloatSave.StatusWord := excep^.ContextRecord^.FloatSave.StatusWord and $ffffff00;}
  772. STATUS_FLOAT_INEXACT_RESULT,
  773. STATUS_FLOAT_INVALID_OPERATION,
  774. STATUS_FLOAT_STACK_CHECK :
  775. err := 207;
  776. STATUS_INTEGER_OVERFLOW :
  777. begin
  778. err := 215;
  779. must_reset_fpu := false;
  780. end;
  781. STATUS_ILLEGAL_INSTRUCTION:
  782. err := 216;
  783. STATUS_ACCESS_VIOLATION:
  784. { Athlon prefetch bug? }
  785. if is_prefetch(pointer(excep^.ContextRecord^.rip)) then
  786. begin
  787. { if yes, then retry }
  788. excep^.ExceptionRecord^.ExceptionCode := 0;
  789. res:=EXCEPTION_CONTINUE_EXECUTION;
  790. end
  791. else
  792. err := 216;
  793. STATUS_CONTROL_C_EXIT:
  794. err := 217;
  795. STATUS_PRIVILEGED_INSTRUCTION:
  796. begin
  797. err := 218;
  798. must_reset_fpu := false;
  799. end;
  800. else
  801. begin
  802. if ((excep^.ExceptionRecord^.ExceptionCode and SEVERITY_ERROR) = SEVERITY_ERROR) then
  803. err := 217
  804. else
  805. { pass through exceptions which aren't an error. The problem is that vectored handlers
  806. always are called before structured ones so we see also internal exceptions of libraries.
  807. I wonder if there is a better solution (FK)
  808. }
  809. res:=EXCEPTION_CONTINUE_SEARCH;
  810. end;
  811. end;
  812. if (err <> 0) and (exceptLevel < MaxExceptionLevel) then
  813. begin
  814. exceptRip[exceptLevel] := excep^.ContextRecord^.Rip;
  815. exceptError[exceptLevel] := err;
  816. resetFPU[exceptLevel] := must_reset_fpu;
  817. inc(exceptLevel);
  818. excep^.ContextRecord^.Rip := Int64(@JumpToHandleErrorFrame);
  819. excep^.ExceptionRecord^.ExceptionCode := 0;
  820. res := EXCEPTION_CONTINUE_EXECUTION;
  821. {$ifdef SYSTEMEXCEPTIONDEBUG}
  822. if IsConsole then begin
  823. writeln(stderr,'Exception Continue Exception set at ',
  824. hexstr(exceptRip[exceptLevel-1],16));
  825. writeln(stderr,'Rip changed to ',
  826. hexstr(int64(@JumpToHandleErrorFrame),16), ' error=', err);
  827. end;
  828. {$endif SYSTEMEXCEPTIONDEBUG}
  829. end;
  830. end;
  831. syswin64_x86_64_exception_handler := res;
  832. end;
  833. procedure install_exception_handlers;
  834. begin
  835. AddVectoredExceptionHandler(1,@syswin64_x86_64_exception_handler);
  836. end;
  837. procedure remove_exception_handlers;
  838. begin
  839. end;
  840. procedure fpc_cpucodeinit;
  841. begin
  842. end;
  843. {****************************************************************************
  844. OS dependend widestrings
  845. ****************************************************************************}
  846. const
  847. { MultiByteToWideChar }
  848. MB_PRECOMPOSED = 1;
  849. CP_ACP = 0;
  850. function MultiByteToWideChar(CodePage:UINT; dwFlags:DWORD; lpMultiByteStr:PChar; cchMultiByte:longint; lpWideCharStr:PWideChar;cchWideChar:longint):longint;
  851. stdcall; external 'kernel32' name 'MultiByteToWideChar';
  852. function WideCharToMultiByte(CodePage:UINT; dwFlags:DWORD; lpWideCharStr:PWideChar; cchWideChar:longint; lpMultiByteStr:PChar;cchMultiByte:longint; lpDefaultChar:PChar; lpUsedDefaultChar:pointer):longint;
  853. stdcall; external 'kernel32' name 'WideCharToMultiByte';
  854. function CharUpperBuff(lpsz:LPWSTR; cchLength:DWORD):DWORD;
  855. stdcall; external 'user32' name 'CharUpperBuffW';
  856. function CharLowerBuff(lpsz:LPWSTR; cchLength:DWORD):DWORD;
  857. stdcall; external 'user32' name 'CharLowerBuffW';
  858. procedure Win32Wide2AnsiMove(source:pwidechar;var dest:ansistring;len:SizeInt);
  859. var
  860. destlen: SizeInt;
  861. begin
  862. // retrieve length including trailing #0
  863. destlen:=WideCharToMultiByte(CP_ACP, 0, source, len+1, nil, 0, nil, nil);
  864. setlength(dest, destlen-1);
  865. WideCharToMultiByte(CP_ACP, 0, source, len+1, @dest[1], destlen, nil, nil);
  866. end;
  867. procedure Win32Ansi2WideMove(source:pchar;var dest:widestring;len:SizeInt);
  868. var
  869. destlen: SizeInt;
  870. begin
  871. // retrieve length including trailing #0
  872. destlen:=MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, source, len+1, nil, 0);
  873. setlength(dest, destlen-1);
  874. MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, source, len+1, @dest[1], destlen);
  875. end;
  876. function Win32WideUpper(const s : WideString) : WideString;
  877. begin
  878. result:=s;
  879. UniqueString(result);
  880. if length(result)>0 then
  881. CharUpperBuff(LPWSTR(result),length(result));
  882. end;
  883. function Win32WideLower(const s : WideString) : WideString;
  884. begin
  885. result:=s;
  886. UniqueString(result);
  887. if length(result)>0 then
  888. CharLowerBuff(LPWSTR(result),length(result));
  889. end;
  890. { there is a similiar procedure in sysutils which inits the fields which
  891. are only relevant for the sysutils units }
  892. procedure InitWin32Widestrings;
  893. begin
  894. widestringmanager.Wide2AnsiMoveProc:=@Win32Wide2AnsiMove;
  895. widestringmanager.Ansi2WideMoveProc:=@Win32Ansi2WideMove;
  896. widestringmanager.UpperWideStringProc:=@Win32WideUpper;
  897. widestringmanager.LowerWideStringProc:=@Win32WideLower;
  898. end;
  899. {****************************************************************************
  900. Error Message writing using messageboxes
  901. ****************************************************************************}
  902. function MessageBox(w1:longint;l1,l2:pointer;w2:longint):longint;
  903. stdcall;external 'user32' name 'MessageBoxA';
  904. const
  905. ErrorBufferLength = 1024;
  906. var
  907. ErrorBuf : array[0..ErrorBufferLength] of char;
  908. ErrorLen : longint;
  909. Function ErrorWrite(Var F: TextRec): Integer;
  910. {
  911. An error message should always end with #13#10#13#10
  912. }
  913. var
  914. p : pchar;
  915. i : longint;
  916. Begin
  917. if F.BufPos>0 then
  918. begin
  919. if F.BufPos+ErrorLen>ErrorBufferLength then
  920. i:=ErrorBufferLength-ErrorLen
  921. else
  922. i:=F.BufPos;
  923. Move(F.BufPtr^,ErrorBuf[ErrorLen],i);
  924. inc(ErrorLen,i);
  925. ErrorBuf[ErrorLen]:=#0;
  926. end;
  927. if ErrorLen>3 then
  928. begin
  929. p:=@ErrorBuf[ErrorLen];
  930. for i:=1 to 4 do
  931. begin
  932. dec(p);
  933. if not(p^ in [#10,#13]) then
  934. break;
  935. end;
  936. end;
  937. if ErrorLen=ErrorBufferLength then
  938. i:=4;
  939. if (i=4) then
  940. begin
  941. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  942. ErrorLen:=0;
  943. end;
  944. F.BufPos:=0;
  945. ErrorWrite:=0;
  946. End;
  947. Function ErrorClose(Var F: TextRec): Integer;
  948. begin
  949. if ErrorLen>0 then
  950. begin
  951. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  952. ErrorLen:=0;
  953. end;
  954. ErrorLen:=0;
  955. ErrorClose:=0;
  956. end;
  957. Function ErrorOpen(Var F: TextRec): Integer;
  958. Begin
  959. TextRec(F).InOutFunc:=@ErrorWrite;
  960. TextRec(F).FlushFunc:=@ErrorWrite;
  961. TextRec(F).CloseFunc:=@ErrorClose;
  962. ErrorOpen:=0;
  963. End;
  964. procedure AssignError(Var T: Text);
  965. begin
  966. Assign(T,'');
  967. TextRec(T).OpenFunc:=@ErrorOpen;
  968. Rewrite(T);
  969. end;
  970. procedure SysInitStdIO;
  971. begin
  972. { Setup stdin, stdout and stderr, for GUI apps redirect stderr,stdout to be
  973. displayed in a messagebox }
  974. StdInputHandle:=THandle(GetStdHandle(STD_INPUT_HANDLE));
  975. StdOutputHandle:=THandle(GetStdHandle(STD_OUTPUT_HANDLE));
  976. StdErrorHandle:=THandle(GetStdHandle(STD_ERROR_HANDLE));
  977. if not IsConsole then
  978. begin
  979. AssignError(stderr);
  980. AssignError(stdout);
  981. Assign(Output,'');
  982. Assign(Input,'');
  983. Assign(ErrOutput,'');
  984. end
  985. else
  986. begin
  987. OpenStdIO(Input,fmInput,StdInputHandle);
  988. OpenStdIO(Output,fmOutput,StdOutputHandle);
  989. OpenStdIO(ErrOutput,fmOutput,StdErrorHandle);
  990. OpenStdIO(StdOut,fmOutput,StdOutputHandle);
  991. OpenStdIO(StdErr,fmOutput,StdErrorHandle);
  992. end;
  993. end;
  994. (* ProcessID cached to avoid repeated calls to GetCurrentProcess. *)
  995. var
  996. ProcessID: SizeUInt;
  997. function GetProcessID: SizeUInt;
  998. begin
  999. GetProcessID := ProcessID;
  1000. end;
  1001. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt;
  1002. begin
  1003. result := stklen;
  1004. end;
  1005. begin
  1006. SysResetFPU;
  1007. StackLength := CheckInitialStkLen(InitialStkLen);
  1008. StackBottom := StackTop - StackLength;
  1009. { get some helpful informations }
  1010. GetStartupInfo(@startupinfo);
  1011. { some misc Win32 stuff }
  1012. hprevinst:=0;
  1013. if not IsLibrary then
  1014. SysInstance:=getmodulehandle(GetCommandFile);
  1015. MainInstance:=HInstance;
  1016. cmdshow:=startupinfo.wshowwindow;
  1017. { Setup heap }
  1018. InitHeap;
  1019. SysInitExceptions;
  1020. { setup fastmove stuff }
  1021. fpc_cpucodeinit;
  1022. SysInitStdIO;
  1023. { Arguments }
  1024. setup_arguments;
  1025. { Reset IO Error }
  1026. InOutRes:=0;
  1027. ProcessID := GetCurrentProcessID;
  1028. { threading }
  1029. InitSystemThreads;
  1030. { Reset internal error variable }
  1031. errno:=0;
  1032. initvariantmanager;
  1033. initwidestringmanager;
  1034. InitWin32Widestrings;
  1035. DispCallByIDProc:=@DoDispCallByIDError;
  1036. end.