system.pp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  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. {$ifdef SYSTEMDEBUG}
  15. {$define SYSTEMEXCEPTIONDEBUG}
  16. {$endif SYSTEMDEBUG}
  17. { include system-independent routine headers }
  18. {$I systemh.inc}
  19. const
  20. LineEnding = #13#10;
  21. LFNSupport = true;
  22. DirectorySeparator = '\';
  23. DriveSeparator = ':';
  24. PathSeparator = ';';
  25. { FileNameCaseSensitive is defined separately below!!! }
  26. maxExitCode = 65535;
  27. MaxPathLen = 260;
  28. type
  29. PEXCEPTION_FRAME = ^TEXCEPTION_FRAME;
  30. TEXCEPTION_FRAME = record
  31. next : PEXCEPTION_FRAME;
  32. handler : pointer;
  33. end;
  34. const
  35. { Default filehandles }
  36. UnusedHandle : THandle = THandle(-1);
  37. StdInputHandle : THandle = 0;
  38. StdOutputHandle : THandle = 0;
  39. StdErrorHandle : THandle = 0;
  40. FileNameCaseSensitive : boolean = true;
  41. CtrlZMarksEOF: boolean = true; (* #26 not considered as end of file *)
  42. sLineBreak = LineEnding;
  43. DefaultTextLineBreakStyle : TTextLineBreakStyle = tlbsCRLF;
  44. { Thread count for DLL }
  45. Thread_count : longint = 0;
  46. System_exception_frame : PEXCEPTION_FRAME =nil;
  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. {$ifdef i386}
  90. {$define HAS_RESOURCES}
  91. {$i win32res.inc}
  92. {$endif}
  93. { used by wstrings.inc because wstrings.inc is included before sysos.inc
  94. this is put here (FK) }
  95. function SysAllocStringLen(psz:pointer;len:dword):pointer;stdcall;
  96. external 'oleaut32.dll' name 'SysAllocStringLen';
  97. procedure SysFreeString(bstr:pointer);stdcall;
  98. external 'oleaut32.dll' name 'SysFreeString';
  99. function SysReAllocStringLen(var bstr:pointer;psz: pointer;
  100. len:dword): Integer; stdcall;external 'oleaut32.dll' name 'SysReAllocStringLen';
  101. { include system independent routines }
  102. {$I system.inc}
  103. {*****************************************************************************
  104. Parameter Handling
  105. *****************************************************************************}
  106. var
  107. ModuleName : array[0..255] of char;
  108. function GetCommandFile:pchar;
  109. begin
  110. GetModuleFileName(0,@ModuleName,255);
  111. GetCommandFile:=@ModuleName;
  112. end;
  113. procedure setup_arguments;
  114. var
  115. arglen,
  116. count : longint;
  117. argstart,
  118. pc,arg : pchar;
  119. quote : char;
  120. argvlen : longint;
  121. procedure allocarg(idx,len:longint);
  122. var
  123. oldargvlen : longint;
  124. begin
  125. if idx>=argvlen then
  126. begin
  127. oldargvlen:=argvlen;
  128. argvlen:=(idx+8) and (not 7);
  129. sysreallocmem(argv,argvlen*sizeof(pointer));
  130. fillchar(argv[oldargvlen],(argvlen-oldargvlen)*sizeof(pointer),0);
  131. end;
  132. { use realloc to reuse already existing memory }
  133. { always allocate, even if length is zero, since }
  134. { the arg. is still present! }
  135. sysreallocmem(argv[idx],len+1);
  136. end;
  137. begin
  138. SetupProcVars;
  139. { create commandline, it starts with the executed filename which is argv[0] }
  140. { Win32 passes the command NOT via the args, but via getmodulefilename}
  141. count:=0;
  142. argv:=nil;
  143. argvlen:=0;
  144. pc:=getcommandfile;
  145. Arglen:=0;
  146. repeat
  147. Inc(Arglen);
  148. until (pc[Arglen]=#0);
  149. allocarg(count,arglen);
  150. move(pc^,argv[count]^,arglen+1);
  151. { Setup cmdline variable }
  152. cmdline:=GetCommandLine;
  153. { process arguments }
  154. pc:=cmdline;
  155. {$IfDef SYSTEM_DEBUG_STARTUP}
  156. Writeln(stderr,'Win32 GetCommandLine is #',pc,'#');
  157. {$EndIf }
  158. while pc^<>#0 do
  159. begin
  160. { skip leading spaces }
  161. while pc^ in [#1..#32] do
  162. inc(pc);
  163. if pc^=#0 then
  164. break;
  165. { calc argument length }
  166. quote:=' ';
  167. argstart:=pc;
  168. arglen:=0;
  169. while (pc^<>#0) do
  170. begin
  171. case pc^ of
  172. #1..#32 :
  173. begin
  174. if quote<>' ' then
  175. inc(arglen)
  176. else
  177. break;
  178. end;
  179. '"' :
  180. begin
  181. if quote<>'''' then
  182. begin
  183. if pchar(pc+1)^<>'"' then
  184. begin
  185. if quote='"' then
  186. quote:=' '
  187. else
  188. quote:='"';
  189. end
  190. else
  191. inc(pc);
  192. end
  193. else
  194. inc(arglen);
  195. end;
  196. '''' :
  197. begin
  198. if quote<>'"' then
  199. begin
  200. if pchar(pc+1)^<>'''' then
  201. begin
  202. if quote='''' then
  203. quote:=' '
  204. else
  205. quote:='''';
  206. end
  207. else
  208. inc(pc);
  209. end
  210. else
  211. inc(arglen);
  212. end;
  213. else
  214. inc(arglen);
  215. end;
  216. inc(pc);
  217. end;
  218. { copy argument }
  219. { Don't copy the first one, it is already there.}
  220. If Count<>0 then
  221. begin
  222. allocarg(count,arglen);
  223. quote:=' ';
  224. pc:=argstart;
  225. arg:=argv[count];
  226. while (pc^<>#0) do
  227. begin
  228. case pc^ of
  229. #1..#32 :
  230. begin
  231. if quote<>' ' then
  232. begin
  233. arg^:=pc^;
  234. inc(arg);
  235. end
  236. else
  237. break;
  238. end;
  239. '"' :
  240. begin
  241. if quote<>'''' then
  242. begin
  243. if pchar(pc+1)^<>'"' then
  244. begin
  245. if quote='"' then
  246. quote:=' '
  247. else
  248. quote:='"';
  249. end
  250. else
  251. inc(pc);
  252. end
  253. else
  254. begin
  255. arg^:=pc^;
  256. inc(arg);
  257. end;
  258. end;
  259. '''' :
  260. begin
  261. if quote<>'"' then
  262. begin
  263. if pchar(pc+1)^<>'''' then
  264. begin
  265. if quote='''' then
  266. quote:=' '
  267. else
  268. quote:='''';
  269. end
  270. else
  271. inc(pc);
  272. end
  273. else
  274. begin
  275. arg^:=pc^;
  276. inc(arg);
  277. end;
  278. end;
  279. else
  280. begin
  281. arg^:=pc^;
  282. inc(arg);
  283. end;
  284. end;
  285. inc(pc);
  286. end;
  287. arg^:=#0;
  288. end;
  289. {$IfDef SYSTEM_DEBUG_STARTUP}
  290. Writeln(stderr,'dos arg ',count,' #',arglen,'#',argv[count],'#');
  291. {$EndIf SYSTEM_DEBUG_STARTUP}
  292. inc(count);
  293. end;
  294. { get argc and create an nil entry }
  295. argc:=count;
  296. allocarg(argc,0);
  297. { free unused memory }
  298. sysreallocmem(argv,(argc+1)*sizeof(pointer));
  299. end;
  300. function paramcount : longint;
  301. begin
  302. paramcount := argc - 1;
  303. end;
  304. function paramstr(l : longint) : string;
  305. begin
  306. if (l>=0) and (l<argc) then
  307. paramstr:=strpas(argv[l])
  308. else
  309. paramstr:='';
  310. end;
  311. procedure randomize;
  312. begin
  313. randseed:=GetTickCount;
  314. end;
  315. {*****************************************************************************
  316. System Dependent Exit code
  317. *****************************************************************************}
  318. procedure install_exception_handlers;forward;
  319. procedure remove_exception_handlers;forward;
  320. procedure PascalMain;stdcall;external name 'PASCALMAIN';
  321. procedure fpc_do_exit;stdcall;external name 'FPC_DO_EXIT';
  322. Procedure ExitDLL(Exitcode : longint); forward;
  323. Procedure system_exit;
  324. begin
  325. { don't call ExitProcess inside
  326. the DLL exit code !!
  327. This crashes Win95 at least PM }
  328. if IsLibrary then
  329. ExitDLL(ExitCode);
  330. if not IsConsole then
  331. begin
  332. Close(stderr);
  333. Close(stdout);
  334. { what about Input and Output ?? PM }
  335. end;
  336. remove_exception_handlers;
  337. { call exitprocess, with cleanup as required }
  338. ExitProcess(exitcode);
  339. end;
  340. var
  341. { value of the stack segment
  342. to check if the call stack can be written on exceptions }
  343. _SS : Cardinal;
  344. procedure Exe_entry;[public,alias:'_FPC_EXE_Entry'];
  345. var
  346. ST : pointer;
  347. EBP : pointer;
  348. begin
  349. IsLibrary:=false;
  350. { install the handlers for exe only ?
  351. or should we install them for DLL also ? (PM) }
  352. install_exception_handlers;
  353. { This strange construction is needed to solve the _SS problem
  354. with a smartlinked syswin32 (PFV) }
  355. ExitCode:=0;
  356. asm
  357. { allocate space for an exception frame }
  358. pushq $0
  359. pushq %fs:(0)
  360. { movl %esp,%fs:(0)
  361. but don't insert it as it doesn't
  362. point to anything yet
  363. this will be used in signals unit }
  364. movq %rsp,%rax
  365. movq %rax,System_exception_frame
  366. { keep stack aligned }
  367. pushq $0
  368. pushq %rbp
  369. movq %rsp,%rax
  370. movq %rax,st
  371. end;
  372. StackTop:=st;
  373. asm
  374. xorl %rax,%rax
  375. movw %ss,%ax
  376. movl %eax,_SS
  377. call SysResetFPU
  378. xorl %rbp,%rbp
  379. call PASCALMAIN
  380. popq %rbp
  381. popq %rax
  382. end;
  383. { if we pass here there was no error ! }
  384. system_exit;
  385. end;
  386. Const
  387. { DllEntryPoint }
  388. DLL_PROCESS_ATTACH = 1;
  389. DLL_THREAD_ATTACH = 2;
  390. DLL_PROCESS_DETACH = 0;
  391. DLL_THREAD_DETACH = 3;
  392. Var
  393. DLLBuf : Jmp_buf;
  394. Const
  395. DLLExitOK : boolean = true;
  396. function Dll_entry : longbool;
  397. var
  398. res : longbool;
  399. begin
  400. IsLibrary:=true;
  401. Dll_entry:=false;
  402. case DLLreason of
  403. DLL_PROCESS_ATTACH :
  404. begin
  405. If SetJmp(DLLBuf) = 0 then
  406. begin
  407. if assigned(Dll_Process_Attach_Hook) then
  408. begin
  409. res:=Dll_Process_Attach_Hook(DllParam);
  410. if not res then
  411. exit(false);
  412. end;
  413. PASCALMAIN;
  414. Dll_entry:=true;
  415. end
  416. else
  417. Dll_entry:=DLLExitOK;
  418. end;
  419. DLL_THREAD_ATTACH :
  420. begin
  421. inc(Thread_count);
  422. {$warning Allocate Threadvars !}
  423. if assigned(Dll_Thread_Attach_Hook) then
  424. Dll_Thread_Attach_Hook(DllParam);
  425. Dll_entry:=true; { return value is ignored }
  426. end;
  427. DLL_THREAD_DETACH :
  428. begin
  429. dec(Thread_count);
  430. if assigned(Dll_Thread_Detach_Hook) then
  431. Dll_Thread_Detach_Hook(DllParam);
  432. {$warning Release Threadvars !}
  433. Dll_entry:=true; { return value is ignored }
  434. end;
  435. DLL_PROCESS_DETACH :
  436. begin
  437. Dll_entry:=true; { return value is ignored }
  438. If SetJmp(DLLBuf) = 0 then
  439. begin
  440. FPC_DO_EXIT;
  441. end;
  442. if assigned(Dll_Process_Detach_Hook) then
  443. Dll_Process_Detach_Hook(DllParam);
  444. end;
  445. end;
  446. end;
  447. Procedure ExitDLL(Exitcode : longint);
  448. begin
  449. DLLExitOK:=ExitCode=0;
  450. LongJmp(DLLBuf,1);
  451. end;
  452. {$ifndef VER2_0}
  453. procedure _FPC_mainCRTStartup;stdcall;public name '_mainCRTStartup';
  454. begin
  455. IsConsole:=true;
  456. Exe_entry;
  457. end;
  458. procedure _FPC_WinMainCRTStartup;stdcall;public name '_WinMainCRTStartup';
  459. begin
  460. IsConsole:=false;
  461. Exe_entry;
  462. end;
  463. procedure _FPC_DLLMainCRTStartup(_hinstance,_dllreason,_dllparam:longint);stdcall;public name '_DLLMainCRTStartup';
  464. begin
  465. IsConsole:=true;
  466. sysinstance:=_hinstance;
  467. dllreason:=_dllreason;
  468. dllparam:=_dllparam;
  469. DLL_Entry;
  470. end;
  471. procedure _FPC_DLLWinMainCRTStartup(_hinstance,_dllreason,_dllparam:longint);stdcall;public name '_DLLWinMainCRTStartup';
  472. begin
  473. IsConsole:=false;
  474. sysinstance:=_hinstance;
  475. dllreason:=_dllreason;
  476. dllparam:=_dllparam;
  477. DLL_Entry;
  478. end;
  479. {$endif VER2_0}
  480. function GetCurrentProcess : dword;
  481. stdcall;external 'kernel32' name 'GetCurrentProcess';
  482. function ReadProcessMemory(process : dword;address : pointer;dest : pointer;size : dword;bytesread : pdword) : longbool;
  483. stdcall;external 'kernel32' name 'ReadProcessMemory';
  484. function is_prefetch(p : pointer) : boolean;
  485. var
  486. a : array[0..15] of byte;
  487. doagain : boolean;
  488. instrlo,instrhi,opcode : byte;
  489. i : longint;
  490. begin
  491. result:=false;
  492. { read memory savely without causing another exeception }
  493. if not(ReadProcessMemory(GetCurrentProcess,p,@a,sizeof(a),nil)) then
  494. exit;
  495. i:=0;
  496. doagain:=true;
  497. while doagain and (i<15) do
  498. begin
  499. opcode:=a[i];
  500. instrlo:=opcode and $f;
  501. instrhi:=opcode and $f0;
  502. case instrhi of
  503. { prefix? }
  504. $20,$30:
  505. doagain:=(instrlo and 7)=6;
  506. $60:
  507. doagain:=(instrlo and $c)=4;
  508. $f0:
  509. doagain:=instrlo in [0,2,3];
  510. $0:
  511. begin
  512. result:=(instrlo=$f) and (a[i+1] in [$d,$18]);
  513. exit;
  514. end;
  515. else
  516. doagain:=false;
  517. end;
  518. inc(i);
  519. end;
  520. end;
  521. //
  522. // Hardware exception handling
  523. //
  524. {
  525. Error code definitions for the Win32 API functions
  526. Values are 32 bit values layed out as follows:
  527. 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
  528. 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
  529. +---+-+-+-----------------------+-------------------------------+
  530. |Sev|C|R| Facility | Code |
  531. +---+-+-+-----------------------+-------------------------------+
  532. where
  533. Sev - is the severity code
  534. 00 - Success
  535. 01 - Informational
  536. 10 - Warning
  537. 11 - Error
  538. C - is the Customer code flag
  539. R - is a reserved bit
  540. Facility - is the facility code
  541. Code - is the facility's status code
  542. }
  543. const
  544. SEVERITY_SUCCESS = $00000000;
  545. SEVERITY_INFORMATIONAL = $40000000;
  546. SEVERITY_WARNING = $80000000;
  547. SEVERITY_ERROR = $C0000000;
  548. const
  549. STATUS_SEGMENT_NOTIFICATION = $40000005;
  550. DBG_TERMINATE_THREAD = $40010003;
  551. DBG_TERMINATE_PROCESS = $40010004;
  552. DBG_CONTROL_C = $40010005;
  553. DBG_CONTROL_BREAK = $40010008;
  554. STATUS_GUARD_PAGE_VIOLATION = $80000001;
  555. STATUS_DATATYPE_MISALIGNMENT = $80000002;
  556. STATUS_BREAKPOINT = $80000003;
  557. STATUS_SINGLE_STEP = $80000004;
  558. DBG_EXCEPTION_NOT_HANDLED = $80010001;
  559. STATUS_ACCESS_VIOLATION = $C0000005;
  560. STATUS_IN_PAGE_ERROR = $C0000006;
  561. STATUS_INVALID_HANDLE = $C0000008;
  562. STATUS_NO_MEMORY = $C0000017;
  563. STATUS_ILLEGAL_INSTRUCTION = $C000001D;
  564. STATUS_NONCONTINUABLE_EXCEPTION = $C0000025;
  565. STATUS_INVALID_DISPOSITION = $C0000026;
  566. STATUS_ARRAY_BOUNDS_EXCEEDED = $C000008C;
  567. STATUS_FLOAT_DENORMAL_OPERAND = $C000008D;
  568. STATUS_FLOAT_DIVIDE_BY_ZERO = $C000008E;
  569. STATUS_FLOAT_INEXACT_RESULT = $C000008F;
  570. STATUS_FLOAT_INVALID_OPERATION = $C0000090;
  571. STATUS_FLOAT_OVERFLOW = $C0000091;
  572. STATUS_FLOAT_STACK_CHECK = $C0000092;
  573. STATUS_FLOAT_UNDERFLOW = $C0000093;
  574. STATUS_INTEGER_DIVIDE_BY_ZERO = $C0000094;
  575. STATUS_INTEGER_OVERFLOW = $C0000095;
  576. STATUS_PRIVILEGED_INSTRUCTION = $C0000096;
  577. STATUS_STACK_OVERFLOW = $C00000FD;
  578. STATUS_CONTROL_C_EXIT = $C000013A;
  579. STATUS_FLOAT_MULTIPLE_FAULTS = $C00002B4;
  580. STATUS_FLOAT_MULTIPLE_TRAPS = $C00002B5;
  581. STATUS_REG_NAT_CONSUMPTION = $C00002C9;
  582. EXCEPTION_EXECUTE_HANDLER = 1;
  583. EXCEPTION_CONTINUE_EXECUTION = $fffffffff;
  584. EXCEPTION_CONTINUE_SEARCH = 0;
  585. EXCEPTION_MAXIMUM_PARAMETERS = 15;
  586. CONTEXT_X86 = $00010000;
  587. CONTEXT_CONTROL = CONTEXT_X86 or $00000001;
  588. CONTEXT_INTEGER = CONTEXT_X86 or $00000002;
  589. CONTEXT_SEGMENTS = CONTEXT_X86 or $00000004;
  590. CONTEXT_FLOATING_POINT = CONTEXT_X86 or $00000008;
  591. CONTEXT_DEBUG_REGISTERS = CONTEXT_X86 or $00000010;
  592. CONTEXT_EXTENDED_REGISTERS = CONTEXT_X86 or $00000020;
  593. CONTEXT_FULL = CONTEXT_CONTROL or CONTEXT_INTEGER or CONTEXT_SEGMENTS;
  594. MAXIMUM_SUPPORTED_EXTENSION = 512;
  595. type
  596. M128A = record
  597. Low : QWord;
  598. High : Int64;
  599. end;
  600. PContext = ^TContext;
  601. TContext = record
  602. P1Home : QWord;
  603. P2Home : QWord;
  604. P3Home : QWord;
  605. P4Home : QWord;
  606. P5Home : QWord;
  607. P6Home : QWord;
  608. ContextFlags : DWord;
  609. MxCsr : DWord;
  610. SegCs : word;
  611. SegDs : word;
  612. SegEs : word;
  613. SegFs : word;
  614. SegGs : word;
  615. SegSs : word;
  616. EFlags : DWord;
  617. Dr0 : QWord;
  618. Dr1 : QWord;
  619. Dr2 : QWord;
  620. Dr3 : QWord;
  621. Dr6 : QWord;
  622. Dr7 : QWord;
  623. Rax : QWord;
  624. Rcx : QWord;
  625. Rdx : QWord;
  626. Rbx : QWord;
  627. Rsp : QWord;
  628. Rbp : QWord;
  629. Rsi : QWord;
  630. Rdi : QWord;
  631. R8 : QWord;
  632. R9 : QWord;
  633. R10 : QWord;
  634. R11 : QWord;
  635. R12 : QWord;
  636. R13 : QWord;
  637. R14 : QWord;
  638. R15 : QWord;
  639. Rip : QWord;
  640. Header : array[0..1] of M128A;
  641. Legacy : array[0..7] of M128A;
  642. Xmm0 : M128A;
  643. Xmm1 : M128A;
  644. Xmm2 : M128A;
  645. Xmm3 : M128A;
  646. Xmm4 : M128A;
  647. Xmm5 : M128A;
  648. Xmm6 : M128A;
  649. Xmm7 : M128A;
  650. Xmm8 : M128A;
  651. Xmm9 : M128A;
  652. Xmm10 : M128A;
  653. Xmm11 : M128A;
  654. Xmm12 : M128A;
  655. Xmm13 : M128A;
  656. Xmm14 : M128A;
  657. Xmm15 : M128A;
  658. VectorRegister : array[0..25] of M128A;
  659. VectorControl : QWord;
  660. DebugControl : QWord;
  661. LastBranchToRip : QWord;
  662. LastBranchFromRip : QWord;
  663. LastExceptionToRip : QWord;
  664. LastExceptionFromRip : QWord;
  665. end;
  666. type
  667. PExceptionRecord = ^TExceptionRecord;
  668. TExceptionRecord = record
  669. ExceptionCode : DWord;
  670. ExceptionFlags : DWord;
  671. ExceptionRecord : PExceptionRecord;
  672. ExceptionAddress : Pointer;
  673. NumberParameters : DWord;
  674. ExceptionInformation : array[0..EXCEPTION_MAXIMUM_PARAMETERS-1] of Pointer;
  675. end;
  676. PExceptionPointers = ^TExceptionPointers;
  677. TExceptionPointers = packed record
  678. ExceptionRecord : PExceptionRecord;
  679. ContextRecord : PContext;
  680. end;
  681. TVectoredExceptionHandler = function (excep : PExceptionPointers) : Longint;
  682. function AddVectoredExceptionHandler(FirstHandler : DWORD;VectoredHandler : TVectoredExceptionHandler) : longint;
  683. external 'kernel32' name 'AddVectoredExceptionHandler';
  684. const
  685. MaxExceptionLevel = 16;
  686. exceptLevel : Byte = 0;
  687. var
  688. exceptRip : array[0..MaxExceptionLevel-1] of Int64;
  689. exceptError : array[0..MaxExceptionLevel-1] of Byte;
  690. resetFPU : array[0..MaxExceptionLevel-1] of Boolean;
  691. {$ifdef SYSTEMEXCEPTIONDEBUG}
  692. procedure DebugHandleErrorAddrFrame(error : longint; addr, frame : pointer);
  693. begin
  694. if IsConsole then
  695. begin
  696. write(stderr,'HandleErrorAddrFrame(error=',error);
  697. write(stderr,',addr=',hexstr(int64(addr),16));
  698. writeln(stderr,',frame=',hexstr(int64(frame),16),')');
  699. end;
  700. HandleErrorAddrFrame(error,addr,frame);
  701. end;
  702. {$endif SYSTEMEXCEPTIONDEBUG}
  703. procedure JumpToHandleErrorFrame;
  704. var
  705. rip, rbp : int64;
  706. error : longint;
  707. begin
  708. // save ebp
  709. asm
  710. movq (%rbp),%rax
  711. movq %rax,rbp
  712. end;
  713. if exceptLevel>0 then
  714. dec(exceptLevel);
  715. rip:=exceptRip[exceptLevel];
  716. error:=exceptError[exceptLevel];
  717. {$ifdef SYSTEMEXCEPTIONDEBUG}
  718. if IsConsole then
  719. writeln(stderr,'In JumpToHandleErrorFrame error=',error);
  720. {$endif SYSTEMEXCEPTIONDEBUG}
  721. if resetFPU[exceptLevel] then
  722. SysResetFPU;
  723. { build a fake stack }
  724. asm
  725. movq rbp,%r8
  726. movq rip,%rdx
  727. movl error,%ecx
  728. pushq rip
  729. movq rbp,%rbp // Change frame pointer
  730. {$ifdef SYSTEMEXCEPTIONDEBUG}
  731. jmpl DebugHandleErrorAddrFrame
  732. {$else not SYSTEMEXCEPTIONDEBUG}
  733. jmpl HandleErrorAddrFrame
  734. {$endif SYSTEMEXCEPTIONDEBUG}
  735. end;
  736. end;
  737. function syswin64_x86_64_exception_handler(excep : PExceptionPointers) : Longint;public;
  738. var
  739. res: longint;
  740. err: byte;
  741. must_reset_fpu: boolean;
  742. begin
  743. res:=EXCEPTION_CONTINUE_SEARCH;
  744. {$ifdef SYSTEMEXCEPTIONDEBUG}
  745. if IsConsole then
  746. Writeln(stderr,'syswin64_x86_64_exception_handler called');
  747. {$endif SYSTEMEXCEPTIONDEBUG}
  748. if excep^.ContextRecord^.SegSs=_SS then
  749. begin
  750. err := 0;
  751. must_reset_fpu := true;
  752. {$ifdef SYSTEMEXCEPTIONDEBUG}
  753. if IsConsole then Writeln(stderr,'Exception ',
  754. hexstr(excep^.ExceptionRecord^.ExceptionCode,8));
  755. {$endif SYSTEMEXCEPTIONDEBUG}
  756. case cardinal(excep^.ExceptionRecord^.ExceptionCode) of
  757. STATUS_INTEGER_DIVIDE_BY_ZERO,
  758. STATUS_FLOAT_DIVIDE_BY_ZERO :
  759. err := 200;
  760. STATUS_ARRAY_BOUNDS_EXCEEDED :
  761. begin
  762. err := 201;
  763. must_reset_fpu := false;
  764. end;
  765. STATUS_STACK_OVERFLOW :
  766. begin
  767. err := 202;
  768. must_reset_fpu := false;
  769. end;
  770. STATUS_FLOAT_OVERFLOW :
  771. err := 205;
  772. STATUS_FLOAT_DENORMAL_OPERAND,
  773. STATUS_FLOAT_UNDERFLOW :
  774. err := 206;
  775. { excep^.ContextRecord^.FloatSave.StatusWord := excep^.ContextRecord^.FloatSave.StatusWord and $ffffff00;}
  776. STATUS_FLOAT_INEXACT_RESULT,
  777. STATUS_FLOAT_INVALID_OPERATION,
  778. STATUS_FLOAT_STACK_CHECK :
  779. err := 207;
  780. STATUS_INTEGER_OVERFLOW :
  781. begin
  782. err := 215;
  783. must_reset_fpu := false;
  784. end;
  785. STATUS_ILLEGAL_INSTRUCTION:
  786. err := 216;
  787. STATUS_ACCESS_VIOLATION:
  788. { Athlon prefetch bug? }
  789. if is_prefetch(pointer(excep^.ContextRecord^.rip)) then
  790. begin
  791. { if yes, then retry }
  792. excep^.ExceptionRecord^.ExceptionCode := 0;
  793. res:=EXCEPTION_CONTINUE_EXECUTION;
  794. end
  795. else
  796. err := 216;
  797. STATUS_CONTROL_C_EXIT:
  798. err := 217;
  799. STATUS_PRIVILEGED_INSTRUCTION:
  800. begin
  801. err := 218;
  802. must_reset_fpu := false;
  803. end;
  804. else
  805. begin
  806. if ((excep^.ExceptionRecord^.ExceptionCode and SEVERITY_ERROR) = SEVERITY_ERROR) then
  807. err := 217
  808. else
  809. err := 255;
  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. {
  1006. const
  1007. Exe_entry_code : pointer = @Exe_entry;
  1008. Dll_entry_code : pointer = @Dll_entry;
  1009. }
  1010. begin
  1011. SysResetFPU;
  1012. StackLength := CheckInitialStkLen(InitialStkLen);
  1013. StackBottom := StackTop - StackLength;
  1014. { get some helpful informations }
  1015. GetStartupInfo(@startupinfo);
  1016. { some misc Win32 stuff }
  1017. hprevinst:=0;
  1018. if not IsLibrary then
  1019. SysInstance:=getmodulehandle(GetCommandFile);
  1020. MainInstance:=HInstance;
  1021. cmdshow:=startupinfo.wshowwindow;
  1022. { Setup heap }
  1023. InitHeap;
  1024. SysInitExceptions;
  1025. { setup fastmove stuff }
  1026. fpc_cpucodeinit;
  1027. SysInitStdIO;
  1028. { Arguments }
  1029. setup_arguments;
  1030. { Reset IO Error }
  1031. InOutRes:=0;
  1032. ProcessID := GetCurrentProcessID;
  1033. { threading }
  1034. InitSystemThreads;
  1035. { Reset internal error variable }
  1036. errno:=0;
  1037. initvariantmanager;
  1038. initwidestringmanager;
  1039. InitWin32Widestrings;
  1040. end.