2
0

system.pp 33 KB

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