system.pp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  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. WC_NO_BEST_FIT_CHARS = $400;
  851. function MultiByteToWideChar(CodePage:UINT; dwFlags:DWORD; lpMultiByteStr:PChar; cchMultiByte:longint; lpWideCharStr:PWideChar;cchWideChar:longint):longint;
  852. stdcall; external 'kernel32' name 'MultiByteToWideChar';
  853. function WideCharToMultiByte(CodePage:UINT; dwFlags:DWORD; lpWideCharStr:PWideChar; cchWideChar:longint; lpMultiByteStr:PChar;cchMultiByte:longint; lpDefaultChar:PChar; lpUsedDefaultChar:pointer):longint;
  854. stdcall; external 'kernel32' name 'WideCharToMultiByte';
  855. function CharUpperBuff(lpsz:LPWSTR; cchLength:DWORD):DWORD;
  856. stdcall; external 'user32' name 'CharUpperBuffW';
  857. function CharLowerBuff(lpsz:LPWSTR; cchLength:DWORD):DWORD;
  858. stdcall; external 'user32' name 'CharLowerBuffW';
  859. procedure Win32Wide2AnsiMove(source:pwidechar;var dest:ansistring;len:SizeInt);
  860. var
  861. destlen: SizeInt;
  862. begin
  863. // retrieve length including trailing #0
  864. // not anymore, because this must also be usable for single characters
  865. destlen:=WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, source, len, nil, 0, nil, nil);
  866. // this will null-terminate
  867. setlength(dest, destlen);
  868. WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, source, len, @dest[1], destlen, nil, nil);
  869. end;
  870. procedure Win32Ansi2WideMove(source:pchar;var dest:widestring;len:SizeInt);
  871. var
  872. destlen: SizeInt;
  873. begin
  874. // retrieve length including trailing #0
  875. // not anymore, because this must also be usable for single characters
  876. destlen:=MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, source, len, nil, 0);
  877. // this will null-terminate
  878. setlength(dest, destlen);
  879. MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, source, len, @dest[1], destlen);
  880. end;
  881. function Win32WideUpper(const s : WideString) : WideString;
  882. begin
  883. result:=s;
  884. UniqueString(result);
  885. if length(result)>0 then
  886. CharUpperBuff(LPWSTR(result),length(result));
  887. end;
  888. function Win32WideLower(const s : WideString) : WideString;
  889. begin
  890. result:=s;
  891. UniqueString(result);
  892. if length(result)>0 then
  893. CharLowerBuff(LPWSTR(result),length(result));
  894. end;
  895. { there is a similiar procedure in sysutils which inits the fields which
  896. are only relevant for the sysutils units }
  897. procedure InitWin32Widestrings;
  898. begin
  899. widestringmanager.Wide2AnsiMoveProc:=@Win32Wide2AnsiMove;
  900. widestringmanager.Ansi2WideMoveProc:=@Win32Ansi2WideMove;
  901. widestringmanager.UpperWideStringProc:=@Win32WideUpper;
  902. widestringmanager.LowerWideStringProc:=@Win32WideLower;
  903. end;
  904. {****************************************************************************
  905. Error Message writing using messageboxes
  906. ****************************************************************************}
  907. function MessageBox(w1:longint;l1,l2:pointer;w2:longint):longint;
  908. stdcall;external 'user32' name 'MessageBoxA';
  909. const
  910. ErrorBufferLength = 1024;
  911. var
  912. ErrorBuf : array[0..ErrorBufferLength] of char;
  913. ErrorLen : longint;
  914. Function ErrorWrite(Var F: TextRec): Integer;
  915. {
  916. An error message should always end with #13#10#13#10
  917. }
  918. var
  919. p : pchar;
  920. i : longint;
  921. Begin
  922. if F.BufPos>0 then
  923. begin
  924. if F.BufPos+ErrorLen>ErrorBufferLength then
  925. i:=ErrorBufferLength-ErrorLen
  926. else
  927. i:=F.BufPos;
  928. Move(F.BufPtr^,ErrorBuf[ErrorLen],i);
  929. inc(ErrorLen,i);
  930. ErrorBuf[ErrorLen]:=#0;
  931. end;
  932. if ErrorLen>3 then
  933. begin
  934. p:=@ErrorBuf[ErrorLen];
  935. for i:=1 to 4 do
  936. begin
  937. dec(p);
  938. if not(p^ in [#10,#13]) then
  939. break;
  940. end;
  941. end;
  942. if ErrorLen=ErrorBufferLength then
  943. i:=4;
  944. if (i=4) then
  945. begin
  946. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  947. ErrorLen:=0;
  948. end;
  949. F.BufPos:=0;
  950. ErrorWrite:=0;
  951. End;
  952. Function ErrorClose(Var F: TextRec): Integer;
  953. begin
  954. if ErrorLen>0 then
  955. begin
  956. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  957. ErrorLen:=0;
  958. end;
  959. ErrorLen:=0;
  960. ErrorClose:=0;
  961. end;
  962. Function ErrorOpen(Var F: TextRec): Integer;
  963. Begin
  964. TextRec(F).InOutFunc:=@ErrorWrite;
  965. TextRec(F).FlushFunc:=@ErrorWrite;
  966. TextRec(F).CloseFunc:=@ErrorClose;
  967. ErrorOpen:=0;
  968. End;
  969. procedure AssignError(Var T: Text);
  970. begin
  971. Assign(T,'');
  972. TextRec(T).OpenFunc:=@ErrorOpen;
  973. Rewrite(T);
  974. end;
  975. procedure SysInitStdIO;
  976. begin
  977. { Setup stdin, stdout and stderr, for GUI apps redirect stderr,stdout to be
  978. displayed in a messagebox }
  979. StdInputHandle:=THandle(GetStdHandle(STD_INPUT_HANDLE));
  980. StdOutputHandle:=THandle(GetStdHandle(STD_OUTPUT_HANDLE));
  981. StdErrorHandle:=THandle(GetStdHandle(STD_ERROR_HANDLE));
  982. if not IsConsole then
  983. begin
  984. AssignError(stderr);
  985. AssignError(stdout);
  986. Assign(Output,'');
  987. Assign(Input,'');
  988. Assign(ErrOutput,'');
  989. end
  990. else
  991. begin
  992. OpenStdIO(Input,fmInput,StdInputHandle);
  993. OpenStdIO(Output,fmOutput,StdOutputHandle);
  994. OpenStdIO(ErrOutput,fmOutput,StdErrorHandle);
  995. OpenStdIO(StdOut,fmOutput,StdOutputHandle);
  996. OpenStdIO(StdErr,fmOutput,StdErrorHandle);
  997. end;
  998. end;
  999. (* ProcessID cached to avoid repeated calls to GetCurrentProcess. *)
  1000. var
  1001. ProcessID: SizeUInt;
  1002. function GetProcessID: SizeUInt;
  1003. begin
  1004. GetProcessID := ProcessID;
  1005. end;
  1006. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt;assembler;
  1007. asm
  1008. movq %gs:(8),%rax
  1009. subq %gs:(16),%rax
  1010. end;
  1011. begin
  1012. SysResetFPU;
  1013. if not(IsLibrary) then
  1014. SysInitFPU;
  1015. { pass dummy value }
  1016. StackLength := CheckInitialStkLen($1000000);
  1017. StackBottom := StackTop - StackLength;
  1018. { get some helpful informations }
  1019. GetStartupInfo(@startupinfo);
  1020. { some misc Win32 stuff }
  1021. hprevinst:=0;
  1022. if not IsLibrary then
  1023. SysInstance:=getmodulehandle(GetCommandFile);
  1024. MainInstance:=HInstance;
  1025. cmdshow:=startupinfo.wshowwindow;
  1026. { Setup heap }
  1027. InitHeap;
  1028. SysInitExceptions;
  1029. { setup fastmove stuff }
  1030. fpc_cpucodeinit;
  1031. SysInitStdIO;
  1032. { Arguments }
  1033. setup_arguments;
  1034. { Reset IO Error }
  1035. InOutRes:=0;
  1036. ProcessID := GetCurrentProcessID;
  1037. { Reset internal error variable }
  1038. errno:=0;
  1039. initvariantmanager;
  1040. initwidestringmanager;
  1041. InitWin32Widestrings;
  1042. DispCallByIDProc:=@DoDispCallByIDError;
  1043. end.