system.pp 30 KB

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