2
0

system.pp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  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. AllFilesMask = '*';
  30. type
  31. PEXCEPTION_FRAME = ^TEXCEPTION_FRAME;
  32. TEXCEPTION_FRAME = record
  33. next : PEXCEPTION_FRAME;
  34. handler : pointer;
  35. end;
  36. const
  37. { Default filehandles }
  38. UnusedHandle : THandle = THandle(-1);
  39. StdInputHandle : THandle = 0;
  40. StdOutputHandle : THandle = 0;
  41. StdErrorHandle : THandle = 0;
  42. FileNameCaseSensitive : boolean = true;
  43. CtrlZMarksEOF: boolean = true; (* #26 is considered as end of file *)
  44. sLineBreak = LineEnding;
  45. DefaultTextLineBreakStyle : TTextLineBreakStyle = tlbsCRLF;
  46. { Thread count for DLL }
  47. Thread_count : longint = 0;
  48. type
  49. TStartupInfo = record
  50. cb : longint;
  51. lpReserved : Pointer;
  52. lpDesktop : Pointer;
  53. lpTitle : Pointer;
  54. dwX : longint;
  55. dwY : longint;
  56. dwXSize : longint;
  57. dwYSize : longint;
  58. dwXCountChars : longint;
  59. dwYCountChars : longint;
  60. dwFillAttribute : longint;
  61. dwFlags : longint;
  62. wShowWindow : Word;
  63. cbReserved2 : Word;
  64. lpReserved2 : Pointer;
  65. hStdInput : THandle;
  66. hStdOutput : THandle;
  67. hStdError : THandle;
  68. end;
  69. var
  70. { C compatible arguments }
  71. argc : longint;
  72. argv : ppchar;
  73. { Win32 Info }
  74. startupinfo : tstartupinfo;
  75. hprevinst,
  76. MainInstance,
  77. cmdshow : longint;
  78. DLLreason,DLLparam:longint;
  79. type
  80. TDLL_Process_Entry_Hook = function (dllparam : longint) : longbool;
  81. TDLL_Entry_Hook = procedure (dllparam : longint);
  82. const
  83. Dll_Process_Attach_Hook : TDLL_Process_Entry_Hook = nil;
  84. Dll_Process_Detach_Hook : TDLL_Entry_Hook = nil;
  85. Dll_Thread_Attach_Hook : TDLL_Entry_Hook = nil;
  86. Dll_Thread_Detach_Hook : TDLL_Entry_Hook = nil;
  87. implementation
  88. var
  89. SysInstance : Longint;public;
  90. {$define HAS_RESOURCES}
  91. {$i winres.inc}
  92. { used by wstrings.inc because wstrings.inc is included before sysos.inc
  93. this is put here (FK) }
  94. function SysAllocStringLen(psz:pointer;len:dword):pointer;stdcall;
  95. external 'oleaut32.dll' name 'SysAllocStringLen';
  96. procedure SysFreeString(bstr:pointer);stdcall;
  97. external 'oleaut32.dll' name 'SysFreeString';
  98. function SysReAllocStringLen(var bstr:pointer;psz: pointer;
  99. len:dword): Integer; stdcall;external 'oleaut32.dll' name 'SysReAllocStringLen';
  100. { include system independent routines }
  101. {$I system.inc}
  102. {*****************************************************************************
  103. Parameter Handling
  104. *****************************************************************************}
  105. var
  106. ModuleName : array[0..255] of char;
  107. function GetCommandFile:pchar;
  108. begin
  109. GetModuleFileName(0,@ModuleName,255);
  110. GetCommandFile:=@ModuleName;
  111. end;
  112. procedure setup_arguments;
  113. var
  114. arglen,
  115. count : longint;
  116. argstart,
  117. pc,arg : pchar;
  118. quote : char;
  119. argvlen : longint;
  120. procedure allocarg(idx,len:longint);
  121. var
  122. oldargvlen : longint;
  123. begin
  124. if idx>=argvlen then
  125. begin
  126. oldargvlen:=argvlen;
  127. argvlen:=(idx+8) and (not 7);
  128. sysreallocmem(argv,argvlen*sizeof(pointer));
  129. fillchar(argv[oldargvlen],(argvlen-oldargvlen)*sizeof(pointer),0);
  130. end;
  131. { use realloc to reuse already existing memory }
  132. { always allocate, even if length is zero, since }
  133. { the arg. is still present! }
  134. sysreallocmem(argv[idx],len+1);
  135. end;
  136. begin
  137. SetupProcVars;
  138. { create commandline, it starts with the executed filename which is argv[0] }
  139. { Win32 passes the command NOT via the args, but via getmodulefilename}
  140. count:=0;
  141. argv:=nil;
  142. argvlen:=0;
  143. pc:=getcommandfile;
  144. Arglen:=0;
  145. repeat
  146. Inc(Arglen);
  147. until (pc[Arglen]=#0);
  148. allocarg(count,arglen);
  149. move(pc^,argv[count]^,arglen+1);
  150. { Setup cmdline variable }
  151. cmdline:=GetCommandLine;
  152. { process arguments }
  153. pc:=cmdline;
  154. {$IfDef SYSTEM_DEBUG_STARTUP}
  155. Writeln(stderr,'Win32 GetCommandLine is #',pc,'#');
  156. {$EndIf }
  157. while pc^<>#0 do
  158. begin
  159. { skip leading spaces }
  160. while pc^ in [#1..#32] do
  161. inc(pc);
  162. if pc^=#0 then
  163. break;
  164. { calc argument length }
  165. quote:=' ';
  166. argstart:=pc;
  167. arglen:=0;
  168. while (pc^<>#0) do
  169. begin
  170. case pc^ of
  171. #1..#32 :
  172. begin
  173. if quote<>' ' then
  174. inc(arglen)
  175. else
  176. break;
  177. end;
  178. '"' :
  179. begin
  180. if quote<>'''' then
  181. begin
  182. if pchar(pc+1)^<>'"' then
  183. begin
  184. if quote='"' then
  185. quote:=' '
  186. else
  187. quote:='"';
  188. end
  189. else
  190. inc(pc);
  191. end
  192. else
  193. inc(arglen);
  194. end;
  195. '''' :
  196. begin
  197. if quote<>'"' then
  198. begin
  199. if pchar(pc+1)^<>'''' then
  200. begin
  201. if quote='''' then
  202. quote:=' '
  203. else
  204. quote:='''';
  205. end
  206. else
  207. inc(pc);
  208. end
  209. else
  210. inc(arglen);
  211. end;
  212. else
  213. inc(arglen);
  214. end;
  215. inc(pc);
  216. end;
  217. { copy argument }
  218. { Don't copy the first one, it is already there.}
  219. If Count<>0 then
  220. begin
  221. allocarg(count,arglen);
  222. quote:=' ';
  223. pc:=argstart;
  224. arg:=argv[count];
  225. while (pc^<>#0) do
  226. begin
  227. case pc^ of
  228. #1..#32 :
  229. begin
  230. if quote<>' ' then
  231. begin
  232. arg^:=pc^;
  233. inc(arg);
  234. end
  235. else
  236. break;
  237. end;
  238. '"' :
  239. begin
  240. if quote<>'''' then
  241. begin
  242. if pchar(pc+1)^<>'"' then
  243. begin
  244. if quote='"' then
  245. quote:=' '
  246. else
  247. quote:='"';
  248. end
  249. else
  250. inc(pc);
  251. end
  252. else
  253. begin
  254. arg^:=pc^;
  255. inc(arg);
  256. end;
  257. end;
  258. '''' :
  259. begin
  260. if quote<>'"' then
  261. begin
  262. if pchar(pc+1)^<>'''' then
  263. begin
  264. if quote='''' then
  265. quote:=' '
  266. else
  267. quote:='''';
  268. end
  269. else
  270. inc(pc);
  271. end
  272. else
  273. begin
  274. arg^:=pc^;
  275. inc(arg);
  276. end;
  277. end;
  278. else
  279. begin
  280. arg^:=pc^;
  281. inc(arg);
  282. end;
  283. end;
  284. inc(pc);
  285. end;
  286. arg^:=#0;
  287. end;
  288. {$IfDef SYSTEM_DEBUG_STARTUP}
  289. Writeln(stderr,'dos arg ',count,' #',arglen,'#',argv[count],'#');
  290. {$EndIf SYSTEM_DEBUG_STARTUP}
  291. inc(count);
  292. end;
  293. { get argc and create an nil entry }
  294. argc:=count;
  295. allocarg(argc,0);
  296. { free unused memory }
  297. sysreallocmem(argv,(argc+1)*sizeof(pointer));
  298. end;
  299. function paramcount : longint;
  300. begin
  301. paramcount := argc - 1;
  302. end;
  303. function paramstr(l : longint) : string;
  304. begin
  305. if (l>=0) and (l<argc) then
  306. paramstr:=strpas(argv[l])
  307. else
  308. paramstr:='';
  309. end;
  310. procedure randomize;
  311. begin
  312. randseed:=GetTickCount;
  313. end;
  314. {*****************************************************************************
  315. System Dependent Exit code
  316. *****************************************************************************}
  317. procedure install_exception_handlers;forward;
  318. procedure remove_exception_handlers;forward;
  319. procedure PascalMain;stdcall;external name 'PASCALMAIN';
  320. procedure fpc_do_exit;stdcall;external name 'FPC_DO_EXIT';
  321. Procedure ExitDLL(Exitcode : longint); forward;
  322. Procedure system_exit;
  323. begin
  324. { don't call ExitProcess inside
  325. the DLL exit code !!
  326. This crashes Win95 at least PM }
  327. if IsLibrary then
  328. ExitDLL(ExitCode);
  329. if not IsConsole then
  330. begin
  331. Close(stderr);
  332. Close(stdout);
  333. Close(erroutput);
  334. Close(Input);
  335. Close(Output);
  336. { what about Input and Output ?? PM }
  337. { now handled, FPK }
  338. end;
  339. remove_exception_handlers;
  340. { call exitprocess, with cleanup as required }
  341. ExitProcess(exitcode);
  342. end;
  343. var
  344. { old compilers emitted a reference to _fltused if a module contains
  345. floating type code so the linker could leave away floating point
  346. libraries or not. VC does this as well so we need to define this
  347. symbol as well (FK)
  348. }
  349. _fltused : int64;cvar;public;
  350. { value of the stack segment
  351. to check if the call stack can be written on exceptions }
  352. _SS : Cardinal;
  353. procedure Exe_entry;[public,alias:'_FPC_EXE_Entry'];
  354. var
  355. ST : pointer;
  356. begin
  357. IsLibrary:=false;
  358. { install the handlers for exe only ?
  359. or should we install them for DLL also ? (PM) }
  360. install_exception_handlers;
  361. ExitCode:=0;
  362. asm
  363. { keep stack aligned }
  364. pushq $0
  365. pushq %rbp
  366. movq %rsp,%rax
  367. movq %rax,st
  368. end;
  369. StackTop:=st;
  370. asm
  371. xorl %rax,%rax
  372. movw %ss,%ax
  373. movl %eax,_SS
  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. // not anymore, because this must also be usable for single characters
  864. destlen:=WideCharToMultiByte(CP_ACP, 0, source, len, nil, 0, nil, nil);
  865. // this will null-terminate
  866. setlength(dest, destlen);
  867. WideCharToMultiByte(CP_ACP, 0, source, len, @dest[1], destlen, nil, nil);
  868. end;
  869. procedure Win32Ansi2WideMove(source:pchar;var dest:widestring;len:SizeInt);
  870. var
  871. destlen: SizeInt;
  872. begin
  873. // retrieve length including trailing #0
  874. // not anymore, because this must also be usable for single characters
  875. destlen:=MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, source, len, nil, 0);
  876. // this will null-terminate
  877. setlength(dest, destlen);
  878. MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, source, len, @dest[1], destlen);
  879. end;
  880. function Win32WideUpper(const s : WideString) : WideString;
  881. begin
  882. result:=s;
  883. UniqueString(result);
  884. if length(result)>0 then
  885. CharUpperBuff(LPWSTR(result),length(result));
  886. end;
  887. function Win32WideLower(const s : WideString) : WideString;
  888. begin
  889. result:=s;
  890. UniqueString(result);
  891. if length(result)>0 then
  892. CharLowerBuff(LPWSTR(result),length(result));
  893. end;
  894. { there is a similiar procedure in sysutils which inits the fields which
  895. are only relevant for the sysutils units }
  896. procedure InitWin32Widestrings;
  897. begin
  898. widestringmanager.Wide2AnsiMoveProc:=@Win32Wide2AnsiMove;
  899. widestringmanager.Ansi2WideMoveProc:=@Win32Ansi2WideMove;
  900. widestringmanager.UpperWideStringProc:=@Win32WideUpper;
  901. widestringmanager.LowerWideStringProc:=@Win32WideLower;
  902. end;
  903. {****************************************************************************
  904. Error Message writing using messageboxes
  905. ****************************************************************************}
  906. function MessageBox(w1:longint;l1,l2:pointer;w2:longint):longint;
  907. stdcall;external 'user32' name 'MessageBoxA';
  908. const
  909. ErrorBufferLength = 1024;
  910. var
  911. ErrorBuf : array[0..ErrorBufferLength] of char;
  912. ErrorLen : longint;
  913. Function ErrorWrite(Var F: TextRec): Integer;
  914. {
  915. An error message should always end with #13#10#13#10
  916. }
  917. var
  918. p : pchar;
  919. i : longint;
  920. Begin
  921. if F.BufPos>0 then
  922. begin
  923. if F.BufPos+ErrorLen>ErrorBufferLength then
  924. i:=ErrorBufferLength-ErrorLen
  925. else
  926. i:=F.BufPos;
  927. Move(F.BufPtr^,ErrorBuf[ErrorLen],i);
  928. inc(ErrorLen,i);
  929. ErrorBuf[ErrorLen]:=#0;
  930. end;
  931. if ErrorLen>3 then
  932. begin
  933. p:=@ErrorBuf[ErrorLen];
  934. for i:=1 to 4 do
  935. begin
  936. dec(p);
  937. if not(p^ in [#10,#13]) then
  938. break;
  939. end;
  940. end;
  941. if ErrorLen=ErrorBufferLength then
  942. i:=4;
  943. if (i=4) then
  944. begin
  945. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  946. ErrorLen:=0;
  947. end;
  948. F.BufPos:=0;
  949. ErrorWrite:=0;
  950. End;
  951. Function ErrorClose(Var F: TextRec): Integer;
  952. begin
  953. if ErrorLen>0 then
  954. begin
  955. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  956. ErrorLen:=0;
  957. end;
  958. ErrorLen:=0;
  959. ErrorClose:=0;
  960. end;
  961. Function ErrorOpen(Var F: TextRec): Integer;
  962. Begin
  963. TextRec(F).InOutFunc:=@ErrorWrite;
  964. TextRec(F).FlushFunc:=@ErrorWrite;
  965. TextRec(F).CloseFunc:=@ErrorClose;
  966. ErrorOpen:=0;
  967. End;
  968. procedure AssignError(Var T: Text);
  969. begin
  970. Assign(T,'');
  971. TextRec(T).OpenFunc:=@ErrorOpen;
  972. Rewrite(T);
  973. end;
  974. procedure SysInitStdIO;
  975. begin
  976. { Setup stdin, stdout and stderr, for GUI apps redirect stderr,stdout to be
  977. displayed in a messagebox }
  978. StdInputHandle:=THandle(GetStdHandle(STD_INPUT_HANDLE));
  979. StdOutputHandle:=THandle(GetStdHandle(STD_OUTPUT_HANDLE));
  980. StdErrorHandle:=THandle(GetStdHandle(STD_ERROR_HANDLE));
  981. if not IsConsole then
  982. begin
  983. AssignError(stderr);
  984. AssignError(stdout);
  985. Assign(Output,'');
  986. Assign(Input,'');
  987. Assign(ErrOutput,'');
  988. end
  989. else
  990. begin
  991. OpenStdIO(Input,fmInput,StdInputHandle);
  992. OpenStdIO(Output,fmOutput,StdOutputHandle);
  993. OpenStdIO(ErrOutput,fmOutput,StdErrorHandle);
  994. OpenStdIO(StdOut,fmOutput,StdOutputHandle);
  995. OpenStdIO(StdErr,fmOutput,StdErrorHandle);
  996. end;
  997. end;
  998. (* ProcessID cached to avoid repeated calls to GetCurrentProcess. *)
  999. var
  1000. ProcessID: SizeUInt;
  1001. function GetProcessID: SizeUInt;
  1002. begin
  1003. GetProcessID := ProcessID;
  1004. end;
  1005. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt;assembler;
  1006. asm
  1007. movq %gs:(8),%rax
  1008. subq %gs:(16),%rax
  1009. end;
  1010. begin
  1011. SysResetFPU;
  1012. if not(IsLibrary) then
  1013. SysInitFPU;
  1014. { pass dummy value }
  1015. StackLength := CheckInitialStkLen($1000000);
  1016. StackBottom := StackTop - StackLength;
  1017. { get some helpful informations }
  1018. GetStartupInfo(@startupinfo);
  1019. { some misc Win32 stuff }
  1020. hprevinst:=0;
  1021. if not IsLibrary then
  1022. SysInstance:=getmodulehandle(GetCommandFile);
  1023. MainInstance:=HInstance;
  1024. cmdshow:=startupinfo.wshowwindow;
  1025. { Setup heap }
  1026. InitHeap;
  1027. SysInitExceptions;
  1028. { setup fastmove stuff }
  1029. fpc_cpucodeinit;
  1030. SysInitStdIO;
  1031. { Arguments }
  1032. setup_arguments;
  1033. { Reset IO Error }
  1034. InOutRes:=0;
  1035. ProcessID := GetCurrentProcessID;
  1036. { threading }
  1037. InitSystemThreads;
  1038. { Reset internal error variable }
  1039. errno:=0;
  1040. initvariantmanager;
  1041. initwidestringmanager;
  1042. InitWin32Widestrings;
  1043. DispCallByIDProc:=@DoDispCallByIDError;
  1044. end.