system.pp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  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;
  93. {$ifdef i386}
  94. {$define HAS_RESOURCES}
  95. {$i win32res.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. begin
  185. if quote<>'''' then
  186. begin
  187. if pchar(pc+1)^<>'"' then
  188. begin
  189. if quote='"' then
  190. quote:=' '
  191. else
  192. quote:='"';
  193. end
  194. else
  195. inc(pc);
  196. end
  197. else
  198. inc(arglen);
  199. end;
  200. '''' :
  201. begin
  202. if quote<>'"' then
  203. begin
  204. if pchar(pc+1)^<>'''' then
  205. begin
  206. if quote='''' then
  207. quote:=' '
  208. else
  209. quote:='''';
  210. end
  211. else
  212. inc(pc);
  213. end
  214. else
  215. inc(arglen);
  216. end;
  217. else
  218. inc(arglen);
  219. end;
  220. inc(pc);
  221. end;
  222. { copy argument }
  223. { Don't copy the first one, it is already there.}
  224. If Count<>0 then
  225. begin
  226. allocarg(count,arglen);
  227. quote:=' ';
  228. pc:=argstart;
  229. arg:=argv[count];
  230. while (pc^<>#0) do
  231. begin
  232. case pc^ of
  233. #1..#32 :
  234. begin
  235. if quote<>' ' then
  236. begin
  237. arg^:=pc^;
  238. inc(arg);
  239. end
  240. else
  241. break;
  242. end;
  243. '"' :
  244. begin
  245. if quote<>'''' then
  246. begin
  247. if pchar(pc+1)^<>'"' then
  248. begin
  249. if quote='"' then
  250. quote:=' '
  251. else
  252. quote:='"';
  253. end
  254. else
  255. inc(pc);
  256. end
  257. else
  258. begin
  259. arg^:=pc^;
  260. inc(arg);
  261. end;
  262. end;
  263. '''' :
  264. begin
  265. if quote<>'"' then
  266. begin
  267. if pchar(pc+1)^<>'''' then
  268. begin
  269. if quote='''' then
  270. quote:=' '
  271. else
  272. quote:='''';
  273. end
  274. else
  275. inc(pc);
  276. end
  277. else
  278. begin
  279. arg^:=pc^;
  280. inc(arg);
  281. end;
  282. end;
  283. else
  284. begin
  285. arg^:=pc^;
  286. inc(arg);
  287. end;
  288. end;
  289. inc(pc);
  290. end;
  291. arg^:=#0;
  292. end;
  293. {$IfDef SYSTEM_DEBUG_STARTUP}
  294. Writeln(stderr,'dos arg ',count,' #',arglen,'#',argv[count],'#');
  295. {$EndIf SYSTEM_DEBUG_STARTUP}
  296. inc(count);
  297. end;
  298. { get argc and create an nil entry }
  299. argc:=count;
  300. allocarg(argc,0);
  301. { free unused memory }
  302. sysreallocmem(argv,(argc+1)*sizeof(pointer));
  303. end;
  304. function paramcount : longint;
  305. begin
  306. paramcount := argc - 1;
  307. end;
  308. function paramstr(l : longint) : string;
  309. begin
  310. if (l>=0) and (l<argc) then
  311. paramstr:=strpas(argv[l])
  312. else
  313. paramstr:='';
  314. end;
  315. procedure randomize;
  316. begin
  317. randseed:=GetTickCount;
  318. end;
  319. {*****************************************************************************
  320. System Dependent Exit code
  321. *****************************************************************************}
  322. procedure install_exception_handlers;forward;
  323. procedure remove_exception_handlers;forward;
  324. procedure PascalMain;stdcall;external name 'PASCALMAIN';
  325. procedure fpc_do_exit;stdcall;external name 'FPC_DO_EXIT';
  326. Procedure ExitDLL(Exitcode : longint); forward;
  327. Procedure system_exit;
  328. begin
  329. { don't call ExitProcess inside
  330. the DLL exit code !!
  331. This crashes Win95 at least PM }
  332. if IsLibrary then
  333. ExitDLL(ExitCode);
  334. if not IsConsole then
  335. begin
  336. Close(stderr);
  337. Close(stdout);
  338. Close(erroutput);
  339. Close(Input);
  340. Close(Output);
  341. { what about Input and Output ?? PM }
  342. { now handled, FPK }
  343. end;
  344. remove_exception_handlers;
  345. { call exitprocess, with cleanup as required }
  346. ExitProcess(exitcode);
  347. end;
  348. var
  349. { value of the stack segment
  350. to check if the call stack can be written on exceptions }
  351. _SS : Cardinal;
  352. procedure Exe_entry;[public,alias:'_FPC_EXE_Entry'];
  353. var
  354. ST : pointer;
  355. begin
  356. IsLibrary:=false;
  357. { install the handlers for exe only ?
  358. or should we install them for DLL also ? (PM) }
  359. install_exception_handlers;
  360. { This strange construction is needed to solve the _SS problem
  361. with a smartlinked syswin32 (PFV) }
  362. asm
  363. { allocate space for an exception frame }
  364. pushl $0
  365. pushl %fs:(0)
  366. { movl %esp,%fs:(0)
  367. but don't insert it as it doesn't
  368. point to anything yet
  369. this will be used in signals unit }
  370. movl %esp,%eax
  371. movl %eax,System_exception_frame
  372. pushl %ebp
  373. movl %esp,%eax
  374. movl %eax,st
  375. end;
  376. StackTop:=st;
  377. asm
  378. xorl %eax,%eax
  379. movw %ss,%ax
  380. movl %eax,_SS
  381. call SysResetFPU
  382. xorl %ebp,%ebp
  383. call PASCALMAIN
  384. popl %ebp
  385. end;
  386. { if we pass here there was no error ! }
  387. system_exit;
  388. end;
  389. Const
  390. { DllEntryPoint }
  391. DLL_PROCESS_ATTACH = 1;
  392. DLL_THREAD_ATTACH = 2;
  393. DLL_PROCESS_DETACH = 0;
  394. DLL_THREAD_DETACH = 3;
  395. Var
  396. DLLBuf : Jmp_buf;
  397. Const
  398. DLLExitOK : boolean = true;
  399. function Dll_entry : longbool;
  400. var
  401. res : longbool;
  402. begin
  403. IsLibrary:=true;
  404. Dll_entry:=false;
  405. case DLLreason of
  406. DLL_PROCESS_ATTACH :
  407. begin
  408. If SetJmp(DLLBuf) = 0 then
  409. begin
  410. if assigned(Dll_Process_Attach_Hook) then
  411. begin
  412. res:=Dll_Process_Attach_Hook(DllParam);
  413. if not res then
  414. exit(false);
  415. end;
  416. PASCALMAIN;
  417. Dll_entry:=true;
  418. end
  419. else
  420. Dll_entry:=DLLExitOK;
  421. end;
  422. DLL_THREAD_ATTACH :
  423. begin
  424. inclocked(Thread_count);
  425. {$warning Allocate Threadvars !}
  426. if assigned(Dll_Thread_Attach_Hook) then
  427. Dll_Thread_Attach_Hook(DllParam);
  428. Dll_entry:=true; { return value is ignored }
  429. end;
  430. DLL_THREAD_DETACH :
  431. begin
  432. declocked(Thread_count);
  433. if assigned(Dll_Thread_Detach_Hook) then
  434. Dll_Thread_Detach_Hook(DllParam);
  435. {$warning Release Threadvars !}
  436. Dll_entry:=true; { return value is ignored }
  437. end;
  438. DLL_PROCESS_DETACH :
  439. begin
  440. Dll_entry:=true; { return value is ignored }
  441. If SetJmp(DLLBuf) = 0 then
  442. FPC_Do_Exit;
  443. if assigned(Dll_Process_Detach_Hook) then
  444. Dll_Process_Detach_Hook(DllParam);
  445. end;
  446. end;
  447. end;
  448. Procedure ExitDLL(Exitcode : longint);
  449. begin
  450. DLLExitOK:=ExitCode=0;
  451. LongJmp(DLLBuf,1);
  452. end;
  453. {$ifndef VER2_0}
  454. procedure _FPC_mainCRTStartup;stdcall;public name '_mainCRTStartup';
  455. begin
  456. IsConsole:=true;
  457. Exe_entry;
  458. end;
  459. procedure _FPC_WinMainCRTStartup;stdcall;public name '_WinMainCRTStartup';
  460. begin
  461. IsConsole:=false;
  462. Exe_entry;
  463. end;
  464. procedure _FPC_DLLMainCRTStartup(_hinstance,_dllreason,_dllparam:longint);stdcall;public name '_DLLMainCRTStartup';
  465. begin
  466. IsConsole:=true;
  467. sysinstance:=_hinstance;
  468. dllreason:=_dllreason;
  469. dllparam:=_dllparam;
  470. DLL_Entry;
  471. end;
  472. procedure _FPC_DLLWinMainCRTStartup(_hinstance,_dllreason,_dllparam:longint);stdcall;public name '_DLLWinMainCRTStartup';
  473. begin
  474. IsConsole:=false;
  475. sysinstance:=_hinstance;
  476. dllreason:=_dllreason;
  477. dllparam:=_dllparam;
  478. DLL_Entry;
  479. end;
  480. {$endif VER2_0}
  481. function GetCurrentProcess : dword;
  482. stdcall;external 'kernel32' name 'GetCurrentProcess';
  483. function ReadProcessMemory(process : dword;address : pointer;dest : pointer;size : dword;bytesread : pdword) : longbool;
  484. stdcall;external 'kernel32' name 'ReadProcessMemory';
  485. function is_prefetch(p : pointer) : boolean;
  486. var
  487. a : array[0..15] of byte;
  488. doagain : boolean;
  489. instrlo,instrhi,opcode : byte;
  490. i : longint;
  491. begin
  492. result:=false;
  493. { read memory savely without causing another exeception }
  494. if not(ReadProcessMemory(GetCurrentProcess,p,@a,sizeof(a),nil)) then
  495. exit;
  496. i:=0;
  497. doagain:=true;
  498. while doagain and (i<15) do
  499. begin
  500. opcode:=a[i];
  501. instrlo:=opcode and $f;
  502. instrhi:=opcode and $f0;
  503. case instrhi of
  504. { prefix? }
  505. $20,$30:
  506. doagain:=(instrlo and 7)=6;
  507. $60:
  508. doagain:=(instrlo and $c)=4;
  509. $f0:
  510. doagain:=instrlo in [0,2,3];
  511. $0:
  512. begin
  513. result:=(instrlo=$f) and (a[i+1] in [$d,$18]);
  514. exit;
  515. end;
  516. else
  517. doagain:=false;
  518. end;
  519. inc(i);
  520. end;
  521. end;
  522. //
  523. // Hardware exception handling
  524. //
  525. {$ifdef Set_i386_Exception_handler}
  526. {
  527. Error code definitions for the Win32 API functions
  528. Values are 32 bit values layed out as follows:
  529. 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
  530. 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
  531. +---+-+-+-----------------------+-------------------------------+
  532. |Sev|C|R| Facility | Code |
  533. +---+-+-+-----------------------+-------------------------------+
  534. where
  535. Sev - is the severity code
  536. 00 - Success
  537. 01 - Informational
  538. 10 - Warning
  539. 11 - Error
  540. C - is the Customer code flag
  541. R - is a reserved bit
  542. Facility - is the facility code
  543. Code - is the facility's status code
  544. }
  545. const
  546. SEVERITY_SUCCESS = $00000000;
  547. SEVERITY_INFORMATIONAL = $40000000;
  548. SEVERITY_WARNING = $80000000;
  549. SEVERITY_ERROR = $C0000000;
  550. const
  551. STATUS_SEGMENT_NOTIFICATION = $40000005;
  552. DBG_TERMINATE_THREAD = $40010003;
  553. DBG_TERMINATE_PROCESS = $40010004;
  554. DBG_CONTROL_C = $40010005;
  555. DBG_CONTROL_BREAK = $40010008;
  556. STATUS_GUARD_PAGE_VIOLATION = $80000001;
  557. STATUS_DATATYPE_MISALIGNMENT = $80000002;
  558. STATUS_BREAKPOINT = $80000003;
  559. STATUS_SINGLE_STEP = $80000004;
  560. DBG_EXCEPTION_NOT_HANDLED = $80010001;
  561. STATUS_ACCESS_VIOLATION = $C0000005;
  562. STATUS_IN_PAGE_ERROR = $C0000006;
  563. STATUS_INVALID_HANDLE = $C0000008;
  564. STATUS_NO_MEMORY = $C0000017;
  565. STATUS_ILLEGAL_INSTRUCTION = $C000001D;
  566. STATUS_NONCONTINUABLE_EXCEPTION = $C0000025;
  567. STATUS_INVALID_DISPOSITION = $C0000026;
  568. STATUS_ARRAY_BOUNDS_EXCEEDED = $C000008C;
  569. STATUS_FLOAT_DENORMAL_OPERAND = $C000008D;
  570. STATUS_FLOAT_DIVIDE_BY_ZERO = $C000008E;
  571. STATUS_FLOAT_INEXACT_RESULT = $C000008F;
  572. STATUS_FLOAT_INVALID_OPERATION = $C0000090;
  573. STATUS_FLOAT_OVERFLOW = $C0000091;
  574. STATUS_FLOAT_STACK_CHECK = $C0000092;
  575. STATUS_FLOAT_UNDERFLOW = $C0000093;
  576. STATUS_INTEGER_DIVIDE_BY_ZERO = $C0000094;
  577. STATUS_INTEGER_OVERFLOW = $C0000095;
  578. STATUS_PRIVILEGED_INSTRUCTION = $C0000096;
  579. STATUS_STACK_OVERFLOW = $C00000FD;
  580. STATUS_CONTROL_C_EXIT = $C000013A;
  581. STATUS_FLOAT_MULTIPLE_FAULTS = $C00002B4;
  582. STATUS_FLOAT_MULTIPLE_TRAPS = $C00002B5;
  583. STATUS_REG_NAT_CONSUMPTION = $C00002C9;
  584. EXCEPTION_EXECUTE_HANDLER = 1;
  585. EXCEPTION_CONTINUE_EXECUTION = -1;
  586. EXCEPTION_CONTINUE_SEARCH = 0;
  587. EXCEPTION_MAXIMUM_PARAMETERS = 15;
  588. CONTEXT_X86 = $00010000;
  589. CONTEXT_CONTROL = CONTEXT_X86 or $00000001;
  590. CONTEXT_INTEGER = CONTEXT_X86 or $00000002;
  591. CONTEXT_SEGMENTS = CONTEXT_X86 or $00000004;
  592. CONTEXT_FLOATING_POINT = CONTEXT_X86 or $00000008;
  593. CONTEXT_DEBUG_REGISTERS = CONTEXT_X86 or $00000010;
  594. CONTEXT_EXTENDED_REGISTERS = CONTEXT_X86 or $00000020;
  595. CONTEXT_FULL = CONTEXT_CONTROL or CONTEXT_INTEGER or CONTEXT_SEGMENTS;
  596. MAXIMUM_SUPPORTED_EXTENSION = 512;
  597. type
  598. PFloatingSaveArea = ^TFloatingSaveArea;
  599. TFloatingSaveArea = packed record
  600. ControlWord : Cardinal;
  601. StatusWord : Cardinal;
  602. TagWord : Cardinal;
  603. ErrorOffset : Cardinal;
  604. ErrorSelector : Cardinal;
  605. DataOffset : Cardinal;
  606. DataSelector : Cardinal;
  607. RegisterArea : array[0..79] of Byte;
  608. Cr0NpxState : Cardinal;
  609. end;
  610. PContext = ^TContext;
  611. TContext = packed record
  612. //
  613. // The flags values within this flag control the contents of
  614. // a CONTEXT record.
  615. //
  616. ContextFlags : Cardinal;
  617. //
  618. // This section is specified/returned if CONTEXT_DEBUG_REGISTERS is
  619. // set in ContextFlags. Note that CONTEXT_DEBUG_REGISTERS is NOT
  620. // included in CONTEXT_FULL.
  621. //
  622. Dr0, Dr1, Dr2,
  623. Dr3, Dr6, Dr7 : Cardinal;
  624. //
  625. // This section is specified/returned if the
  626. // ContextFlags word contains the flag CONTEXT_FLOATING_POINT.
  627. //
  628. FloatSave : TFloatingSaveArea;
  629. //
  630. // This section is specified/returned if the
  631. // ContextFlags word contains the flag CONTEXT_SEGMENTS.
  632. //
  633. SegGs, SegFs,
  634. SegEs, SegDs : Cardinal;
  635. //
  636. // This section is specified/returned if the
  637. // ContextFlags word contains the flag CONTEXT_INTEGER.
  638. //
  639. Edi, Esi, Ebx,
  640. Edx, Ecx, Eax : Cardinal;
  641. //
  642. // This section is specified/returned if the
  643. // ContextFlags word contains the flag CONTEXT_CONTROL.
  644. //
  645. Ebp : Cardinal;
  646. Eip : Cardinal;
  647. SegCs : Cardinal;
  648. EFlags, Esp, SegSs : Cardinal;
  649. //
  650. // This section is specified/returned if the ContextFlags word
  651. // contains the flag CONTEXT_EXTENDED_REGISTERS.
  652. // The format and contexts are processor specific
  653. //
  654. ExtendedRegisters : array[0..MAXIMUM_SUPPORTED_EXTENSION-1] of Byte;
  655. end;
  656. type
  657. PExceptionRecord = ^TExceptionRecord;
  658. TExceptionRecord = packed record
  659. ExceptionCode : cardinal;
  660. ExceptionFlags : Longint;
  661. ExceptionRecord : PExceptionRecord;
  662. ExceptionAddress : Pointer;
  663. NumberParameters : Longint;
  664. ExceptionInformation : array[0..EXCEPTION_MAXIMUM_PARAMETERS-1] of Pointer;
  665. end;
  666. PExceptionPointers = ^TExceptionPointers;
  667. TExceptionPointers = packed record
  668. ExceptionRecord : PExceptionRecord;
  669. ContextRecord : PContext;
  670. end;
  671. { type of functions that should be used for exception handling }
  672. TTopLevelExceptionFilter = function (excep : PExceptionPointers) : Longint;stdcall;
  673. function SetUnhandledExceptionFilter(lpTopLevelExceptionFilter : TTopLevelExceptionFilter) : TTopLevelExceptionFilter;
  674. stdcall;external 'kernel32' name 'SetUnhandledExceptionFilter';
  675. const
  676. MaxExceptionLevel = 16;
  677. exceptLevel : Byte = 0;
  678. var
  679. exceptEip : array[0..MaxExceptionLevel-1] of Longint;
  680. exceptError : array[0..MaxExceptionLevel-1] of Byte;
  681. resetFPU : array[0..MaxExceptionLevel-1] of Boolean;
  682. {$ifdef SYSTEMEXCEPTIONDEBUG}
  683. procedure DebugHandleErrorAddrFrame(error, addr, frame : longint);
  684. begin
  685. if IsConsole then
  686. begin
  687. write(stderr,'HandleErrorAddrFrame(error=',error);
  688. write(stderr,',addr=',hexstr(addr,8));
  689. writeln(stderr,',frame=',hexstr(frame,8),')');
  690. end;
  691. HandleErrorAddrFrame(error,addr,frame);
  692. end;
  693. {$endif SYSTEMEXCEPTIONDEBUG}
  694. procedure JumpToHandleErrorFrame;
  695. var
  696. eip, ebp, error : Longint;
  697. begin
  698. // save ebp
  699. asm
  700. movl (%ebp),%eax
  701. movl %eax,ebp
  702. end;
  703. if (exceptLevel > 0) then
  704. dec(exceptLevel);
  705. eip:=exceptEip[exceptLevel];
  706. error:=exceptError[exceptLevel];
  707. {$ifdef SYSTEMEXCEPTIONDEBUG}
  708. if IsConsole then
  709. writeln(stderr,'In JumpToHandleErrorFrame error=',error);
  710. {$endif SYSTEMEXCEPTIONDEBUG}
  711. if resetFPU[exceptLevel] then
  712. SysResetFPU;
  713. { build a fake stack }
  714. asm
  715. {$ifdef REGCALL}
  716. movl ebp,%ecx
  717. movl eip,%edx
  718. movl error,%eax
  719. pushl eip
  720. movl ebp,%ebp // Change frame pointer
  721. {$else}
  722. movl ebp,%eax
  723. pushl %eax
  724. movl eip,%eax
  725. pushl %eax
  726. movl error,%eax
  727. pushl %eax
  728. movl eip,%eax
  729. pushl %eax
  730. movl ebp,%ebp // Change frame pointer
  731. {$endif}
  732. {$ifdef SYSTEMEXCEPTIONDEBUG}
  733. jmpl DebugHandleErrorAddrFrame
  734. {$else not SYSTEMEXCEPTIONDEBUG}
  735. jmpl HandleErrorAddrFrame
  736. {$endif SYSTEMEXCEPTIONDEBUG}
  737. end;
  738. end;
  739. var
  740. { this variable is set to true, if currently an sse check is executed and no sig ill should be generated }
  741. sse_check : boolean;
  742. function syswin32_i386_exception_handler(excep : PExceptionPointers) : Longint;stdcall;
  743. var
  744. res: longint;
  745. err: byte;
  746. must_reset_fpu: boolean;
  747. begin
  748. res := EXCEPTION_CONTINUE_SEARCH;
  749. if excep^.ContextRecord^.SegSs=_SS then 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 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. { if we're testing sse support, simply set the flag and continue }
  787. if sse_check then
  788. begin
  789. os_supports_sse:=false;
  790. { if yes, then retry }
  791. excep^.ExceptionRecord^.ExceptionCode := 0;
  792. res:=EXCEPTION_CONTINUE_EXECUTION;
  793. end
  794. else
  795. err := 216;
  796. STATUS_ACCESS_VIOLATION:
  797. { Athlon prefetch bug? }
  798. if is_prefetch(pointer(excep^.ContextRecord^.Eip)) then
  799. begin
  800. { if yes, then retry }
  801. excep^.ExceptionRecord^.ExceptionCode := 0;
  802. res:=EXCEPTION_CONTINUE_EXECUTION;
  803. end
  804. else
  805. err := 216;
  806. STATUS_CONTROL_C_EXIT:
  807. err := 217;
  808. STATUS_PRIVILEGED_INSTRUCTION:
  809. begin
  810. err := 218;
  811. must_reset_fpu := false;
  812. end;
  813. else
  814. begin
  815. if ((excep^.ExceptionRecord^.ExceptionCode and SEVERITY_ERROR) = SEVERITY_ERROR) then
  816. err := 217
  817. else
  818. err := 255;
  819. end;
  820. end;
  821. if (err <> 0) and (exceptLevel < MaxExceptionLevel) then begin
  822. exceptEip[exceptLevel] := excep^.ContextRecord^.Eip;
  823. exceptError[exceptLevel] := err;
  824. resetFPU[exceptLevel] := must_reset_fpu;
  825. inc(exceptLevel);
  826. excep^.ContextRecord^.Eip := Longint(@JumpToHandleErrorFrame);
  827. excep^.ExceptionRecord^.ExceptionCode := 0;
  828. res := EXCEPTION_CONTINUE_EXECUTION;
  829. {$ifdef SYSTEMEXCEPTIONDEBUG}
  830. if IsConsole then begin
  831. writeln(stderr,'Exception Continue Exception set at ',
  832. hexstr(exceptEip[exceptLevel],8));
  833. writeln(stderr,'Eip changed to ',
  834. hexstr(longint(@JumpToHandleErrorFrame),8), ' error=', error);
  835. end;
  836. {$endif SYSTEMEXCEPTIONDEBUG}
  837. end;
  838. end;
  839. syswin32_i386_exception_handler := res;
  840. end;
  841. procedure install_exception_handlers;
  842. {$ifdef SYSTEMEXCEPTIONDEBUG}
  843. var
  844. oldexceptaddr,
  845. newexceptaddr : Longint;
  846. {$endif SYSTEMEXCEPTIONDEBUG}
  847. begin
  848. {$ifdef SYSTEMEXCEPTIONDEBUG}
  849. asm
  850. movl $0,%eax
  851. movl %fs:(%eax),%eax
  852. movl %eax,oldexceptaddr
  853. end;
  854. {$endif SYSTEMEXCEPTIONDEBUG}
  855. SetUnhandledExceptionFilter(@syswin32_i386_exception_handler);
  856. {$ifdef SYSTEMEXCEPTIONDEBUG}
  857. asm
  858. movl $0,%eax
  859. movl %fs:(%eax),%eax
  860. movl %eax,newexceptaddr
  861. end;
  862. if IsConsole then
  863. writeln(stderr,'Old exception ',hexstr(oldexceptaddr,8),
  864. ' new exception ',hexstr(newexceptaddr,8));
  865. {$endif SYSTEMEXCEPTIONDEBUG}
  866. end;
  867. procedure remove_exception_handlers;
  868. begin
  869. SetUnhandledExceptionFilter(nil);
  870. end;
  871. {$else not cpui386 (Processor specific !!)}
  872. procedure install_exception_handlers;
  873. begin
  874. end;
  875. procedure remove_exception_handlers;
  876. begin
  877. end;
  878. {$endif Set_i386_Exception_handler}
  879. { because of the brain dead sse detection on x86, this test is post poned }
  880. procedure fpc_cpucodeinit;
  881. begin
  882. os_supports_sse:=true;
  883. sse_check:=true;
  884. asm
  885. { force an sse exception if no sse is supported, the exception handler sets
  886. os_supports_sse to false then }
  887. movq %xmm0,%xmm0
  888. end;
  889. sse_check:=false;
  890. has_sse_support:=sse_support;
  891. has_mmx_support:=mmx_support;
  892. SysResetFPU;
  893. setup_fastmove;
  894. end;
  895. {****************************************************************************
  896. OS dependend widestrings
  897. ****************************************************************************}
  898. const
  899. { MultiByteToWideChar }
  900. MB_PRECOMPOSED = 1;
  901. CP_ACP = 0;
  902. function MultiByteToWideChar(CodePage:UINT; dwFlags:DWORD; lpMultiByteStr:PChar; cchMultiByte:longint; lpWideCharStr:PWideChar;cchWideChar:longint):longint;
  903. stdcall; external 'kernel32' name 'MultiByteToWideChar';
  904. function WideCharToMultiByte(CodePage:UINT; dwFlags:DWORD; lpWideCharStr:PWideChar; cchWideChar:longint; lpMultiByteStr:PChar;cchMultiByte:longint; lpDefaultChar:PChar; lpUsedDefaultChar:pointer):longint;
  905. stdcall; external 'kernel32' name 'WideCharToMultiByte';
  906. function CharUpperBuff(lpsz:LPWSTR; cchLength:DWORD):DWORD;
  907. stdcall; external 'user32' name 'CharUpperBuffW';
  908. function CharLowerBuff(lpsz:LPWSTR; cchLength:DWORD):DWORD;
  909. stdcall; external 'user32' name 'CharLowerBuffW';
  910. procedure Win32Wide2AnsiMove(source:pwidechar;var dest:ansistring;len:SizeInt);
  911. var
  912. destlen: SizeInt;
  913. begin
  914. // retrieve length including trailing #0
  915. destlen:=WideCharToMultiByte(CP_ACP, 0, source, len+1, nil, 0, nil, nil);
  916. setlength(dest, destlen-1);
  917. WideCharToMultiByte(CP_ACP, 0, source, len+1, @dest[1], destlen, nil, nil);
  918. end;
  919. procedure Win32Ansi2WideMove(source:pchar;var dest:widestring;len:SizeInt);
  920. var
  921. destlen: SizeInt;
  922. begin
  923. // retrieve length including trailing #0
  924. destlen:=MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, source, len+1, nil, 0);
  925. setlength(dest, destlen-1);
  926. MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, source, len+1, @dest[1], destlen);
  927. end;
  928. function Win32WideUpper(const s : WideString) : WideString;
  929. begin
  930. result:=s;
  931. UniqueString(result);
  932. if length(result)>0 then
  933. CharUpperBuff(LPWSTR(result),length(result));
  934. end;
  935. function Win32WideLower(const s : WideString) : WideString;
  936. begin
  937. result:=s;
  938. UniqueString(result);
  939. if length(result)>0 then
  940. CharLowerBuff(LPWSTR(result),length(result));
  941. end;
  942. { there is a similiar procedure in sysutils which inits the fields which
  943. are only relevant for the sysutils units }
  944. procedure InitWin32Widestrings;
  945. begin
  946. widestringmanager.Wide2AnsiMoveProc:=@Win32Wide2AnsiMove;
  947. widestringmanager.Ansi2WideMoveProc:=@Win32Ansi2WideMove;
  948. widestringmanager.UpperWideStringProc:=@Win32WideUpper;
  949. widestringmanager.LowerWideStringProc:=@Win32WideLower;
  950. end;
  951. {****************************************************************************
  952. Error Message writing using messageboxes
  953. ****************************************************************************}
  954. function MessageBox(w1:longint;l1,l2:pointer;w2:longint):longint;
  955. stdcall;external 'user32' name 'MessageBoxA';
  956. const
  957. ErrorBufferLength = 1024;
  958. var
  959. ErrorBuf : array[0..ErrorBufferLength] of char;
  960. ErrorLen : longint;
  961. Function ErrorWrite(Var F: TextRec): Integer;
  962. {
  963. An error message should always end with #13#10#13#10
  964. }
  965. var
  966. p : pchar;
  967. i : longint;
  968. Begin
  969. if F.BufPos>0 then
  970. begin
  971. if F.BufPos+ErrorLen>ErrorBufferLength then
  972. i:=ErrorBufferLength-ErrorLen
  973. else
  974. i:=F.BufPos;
  975. Move(F.BufPtr^,ErrorBuf[ErrorLen],i);
  976. inc(ErrorLen,i);
  977. ErrorBuf[ErrorLen]:=#0;
  978. end;
  979. if ErrorLen>3 then
  980. begin
  981. p:=@ErrorBuf[ErrorLen];
  982. for i:=1 to 4 do
  983. begin
  984. dec(p);
  985. if not(p^ in [#10,#13]) then
  986. break;
  987. end;
  988. end;
  989. if ErrorLen=ErrorBufferLength then
  990. i:=4;
  991. if (i=4) then
  992. begin
  993. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  994. ErrorLen:=0;
  995. end;
  996. F.BufPos:=0;
  997. ErrorWrite:=0;
  998. End;
  999. Function ErrorClose(Var F: TextRec): Integer;
  1000. begin
  1001. if ErrorLen>0 then
  1002. begin
  1003. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  1004. ErrorLen:=0;
  1005. end;
  1006. ErrorLen:=0;
  1007. ErrorClose:=0;
  1008. end;
  1009. Function ErrorOpen(Var F: TextRec): Integer;
  1010. Begin
  1011. TextRec(F).InOutFunc:=@ErrorWrite;
  1012. TextRec(F).FlushFunc:=@ErrorWrite;
  1013. TextRec(F).CloseFunc:=@ErrorClose;
  1014. ErrorOpen:=0;
  1015. End;
  1016. procedure AssignError(Var T: Text);
  1017. begin
  1018. Assign(T,'');
  1019. TextRec(T).OpenFunc:=@ErrorOpen;
  1020. Rewrite(T);
  1021. end;
  1022. procedure SysInitStdIO;
  1023. begin
  1024. { Setup stdin, stdout and stderr, for GUI apps redirect stderr,stdout to be
  1025. displayed in a messagebox }
  1026. StdInputHandle:=longint(GetStdHandle(cardinal(STD_INPUT_HANDLE)));
  1027. StdOutputHandle:=longint(GetStdHandle(cardinal(STD_OUTPUT_HANDLE)));
  1028. StdErrorHandle:=longint(GetStdHandle(cardinal(STD_ERROR_HANDLE)));
  1029. if not IsConsole then
  1030. begin
  1031. AssignError(stderr);
  1032. AssignError(stdout);
  1033. Assign(Output,'');
  1034. Assign(Input,'');
  1035. Assign(ErrOutput,'');
  1036. end
  1037. else
  1038. begin
  1039. OpenStdIO(Input,fmInput,StdInputHandle);
  1040. OpenStdIO(Output,fmOutput,StdOutputHandle);
  1041. OpenStdIO(ErrOutput,fmOutput,StdErrorHandle);
  1042. OpenStdIO(StdOut,fmOutput,StdOutputHandle);
  1043. OpenStdIO(StdErr,fmOutput,StdErrorHandle);
  1044. end;
  1045. end;
  1046. (* ProcessID cached to avoid repeated calls to GetCurrentProcess. *)
  1047. var
  1048. ProcessID: SizeUInt;
  1049. function GetProcessID: SizeUInt;
  1050. begin
  1051. GetProcessID := ProcessID;
  1052. end;
  1053. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt;
  1054. begin
  1055. result := stklen;
  1056. end;
  1057. {
  1058. const
  1059. Exe_entry_code : pointer = @Exe_entry;
  1060. Dll_entry_code : pointer = @Dll_entry;
  1061. }
  1062. begin
  1063. StackLength := CheckInitialStkLen(InitialStkLen);
  1064. StackBottom := StackTop - StackLength;
  1065. { get some helpful informations }
  1066. GetStartupInfo(@startupinfo);
  1067. { some misc Win32 stuff }
  1068. hprevinst:=0;
  1069. if not IsLibrary then
  1070. SysInstance:=getmodulehandle(GetCommandFile);
  1071. MainInstance:=HInstance;
  1072. cmdshow:=startupinfo.wshowwindow;
  1073. { Setup heap }
  1074. InitHeap;
  1075. SysInitExceptions;
  1076. { setup fastmove stuff }
  1077. fpc_cpucodeinit;
  1078. SysInitStdIO;
  1079. { Arguments }
  1080. setup_arguments;
  1081. { Reset IO Error }
  1082. InOutRes:=0;
  1083. ProcessID := GetCurrentProcessID;
  1084. { threading }
  1085. InitSystemThreads;
  1086. { Reset internal error variable }
  1087. errno:=0;
  1088. initvariantmanager;
  1089. initwidestringmanager;
  1090. InitWin32Widestrings;
  1091. end.