system.pp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705
  1. {
  2. $Id$
  3. This file is part of the Free Pascal run time library.
  4. Copyright (c) 1999-2000 by Florian Klaempfl and Pavel Ozerski
  5. member of the Free Pascal development team.
  6. FPC Pascal system unit for the Win32 API.
  7. See the file COPYING.FPC, included in this distribution,
  8. for details about the copyright.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  12. **********************************************************************}
  13. {$ifndef VER1_0}
  14. { $define MT}
  15. {$endif VER1_0}
  16. unit {$ifdef VER1_0}SysWin32{$else}System{$endif};
  17. interface
  18. {$ifdef SYSTEMDEBUG}
  19. {$define SYSTEMEXCEPTIONDEBUG}
  20. {$endif SYSTEMDEBUG}
  21. {$ifdef cpui386}
  22. {$define Set_i386_Exception_handler}
  23. {$endif cpui386}
  24. { include system-independent routine headers }
  25. {$I systemh.inc}
  26. {Platform specific information}
  27. type
  28. {$ifdef CPU64}
  29. THandle = QWord;
  30. {$else CPU64}
  31. THandle = DWord;
  32. {$endif CPU64}
  33. const
  34. LineEnding = #13#10;
  35. LFNSupport = true;
  36. DirectorySeparator = '\';
  37. DriveSeparator = ':';
  38. PathSeparator = ';';
  39. { FileNameCaseSensitive is defined separately below!!! }
  40. type
  41. PEXCEPTION_FRAME = ^TEXCEPTION_FRAME;
  42. TEXCEPTION_FRAME = record
  43. next : PEXCEPTION_FRAME;
  44. handler : pointer;
  45. end;
  46. { include heap support headers }
  47. {$I heaph.inc}
  48. const
  49. { Default filehandles }
  50. UnusedHandle : THandle = -1;
  51. StdInputHandle : THandle = 0;
  52. StdOutputHandle : THandle = 0;
  53. StdErrorHandle : THandle = 0;
  54. FileNameCaseSensitive : boolean = true;
  55. sLineBreak = LineEnding;
  56. DefaultTextLineBreakStyle : TTextLineBreakStyle = tlbsCRLF;
  57. { Thread count for DLL }
  58. Thread_count : longint = 0;
  59. System_exception_frame : PEXCEPTION_FRAME =nil;
  60. type
  61. TStartupInfo=packed record
  62. cb : longint;
  63. lpReserved : Pointer;
  64. lpDesktop : Pointer;
  65. lpTitle : Pointer;
  66. dwX : longint;
  67. dwY : longint;
  68. dwXSize : longint;
  69. dwYSize : longint;
  70. dwXCountChars : longint;
  71. dwYCountChars : longint;
  72. dwFillAttribute : longint;
  73. dwFlags : longint;
  74. wShowWindow : Word;
  75. cbReserved2 : Word;
  76. lpReserved2 : Pointer;
  77. hStdInput : longint;
  78. hStdOutput : longint;
  79. hStdError : longint;
  80. end;
  81. var
  82. { C compatible arguments }
  83. argc : longint;
  84. argv : ppchar;
  85. { Win32 Info }
  86. startupinfo : tstartupinfo;
  87. hprevinst,
  88. HInstance,
  89. MainInstance,
  90. cmdshow : longint;
  91. DLLreason,DLLparam:longint;
  92. Win32StackTop : Dword;
  93. type
  94. TDLL_Process_Entry_Hook = function (dllparam : longint) : longbool;
  95. TDLL_Entry_Hook = procedure (dllparam : longint);
  96. const
  97. Dll_Process_Attach_Hook : TDLL_Process_Entry_Hook = nil;
  98. Dll_Process_Detach_Hook : TDLL_Entry_Hook = nil;
  99. Dll_Thread_Attach_Hook : TDLL_Entry_Hook = nil;
  100. Dll_Thread_Detach_Hook : TDLL_Entry_Hook = nil;
  101. type
  102. HMODULE = THandle;
  103. implementation
  104. { include system independent routines }
  105. {$I system.inc}
  106. { some declarations for Win32 API calls }
  107. {$I win32.inc}
  108. CONST
  109. { These constants are used for conversion of error codes }
  110. { from win32 i/o errors to tp i/o errors }
  111. { errors 1 to 18 are the same as in Turbo Pascal }
  112. { DO NOT MODIFY UNLESS YOU KNOW EXACTLY WHAT YOU ARE DOING! }
  113. { The media is write protected. }
  114. ERROR_WRITE_PROTECT = 19;
  115. { The system cannot find the device specified. }
  116. ERROR_BAD_UNIT = 20;
  117. { The device is not ready. }
  118. ERROR_NOT_READY = 21;
  119. { The device does not recognize the command. }
  120. ERROR_BAD_COMMAND = 22;
  121. { Data error (cyclic redundancy check) }
  122. ERROR_CRC = 23;
  123. { The program issued a command but the }
  124. { command length is incorrect. }
  125. ERROR_BAD_LENGTH = 24;
  126. { The drive cannot locate a specific }
  127. { area or track on the disk. }
  128. ERROR_SEEK = 25;
  129. { The specified disk or diskette cannot be accessed. }
  130. ERROR_NOT_DOS_DISK = 26;
  131. { The drive cannot find the sector requested. }
  132. ERROR_SECTOR_NOT_FOUND = 27;
  133. { The printer is out of paper. }
  134. ERROR_OUT_OF_PAPER = 28;
  135. { The system cannot write to the specified device. }
  136. ERROR_WRITE_FAULT = 29;
  137. { The system cannot read from the specified device. }
  138. ERROR_READ_FAULT = 30;
  139. { A device attached to the system is not functioning.}
  140. ERROR_GEN_FAILURE = 31;
  141. { The process cannot access the file because }
  142. { it is being used by another process. }
  143. ERROR_SHARING_VIOLATION = 32;
  144. { A pipe has been closed on the other end }
  145. { Removing that error allows eof to works as on other OSes }
  146. ERROR_BROKEN_PIPE = 109;
  147. ERROR_DIR_NOT_EMPTY = 145;
  148. ERROR_ALREADY_EXISTS = 183;
  149. {$IFDEF SUPPORT_THREADVAR}
  150. threadvar
  151. {$ELSE SUPPORT_THREADVAR}
  152. var
  153. {$ENDIF SUPPORT_THREADVAR}
  154. errno : longint;
  155. {$ASMMODE ATT}
  156. { misc. functions }
  157. function GetLastError : DWORD;
  158. stdcall;external 'kernel32' name 'GetLastError';
  159. { time and date functions }
  160. function GetTickCount : longint;
  161. stdcall;external 'kernel32' name 'GetTickCount';
  162. { process functions }
  163. procedure ExitProcess(uExitCode : UINT);
  164. stdcall;external 'kernel32' name 'ExitProcess';
  165. Procedure Errno2InOutRes;
  166. Begin
  167. { DO NOT MODIFY UNLESS YOU KNOW EXACTLY WHAT YOU ARE DOING }
  168. case Errno of
  169. ERROR_WRITE_PROTECT..ERROR_GEN_FAILURE :
  170. begin
  171. { This is the offset to the Win32 to add to directly map }
  172. { to the DOS/TP compatible error codes when in this range }
  173. InOutRes := word(errno)+131;
  174. end;
  175. ERROR_DIR_NOT_EMPTY,
  176. ERROR_ALREADY_EXISTS,
  177. ERROR_SHARING_VIOLATION :
  178. begin
  179. InOutRes :=5;
  180. end;
  181. else
  182. begin
  183. { other error codes can directly be mapped }
  184. InOutRes := Word(errno);
  185. end;
  186. end;
  187. errno:=0;
  188. end;
  189. function paramcount : longint;
  190. begin
  191. paramcount := argc - 1;
  192. end;
  193. { module functions }
  194. function GetModuleFileName(l1:longint;p:pointer;l2:longint):longint;
  195. stdcall;external 'kernel32' name 'GetModuleFileNameA';
  196. function GetModuleHandle(p : pointer) : longint;
  197. stdcall;external 'kernel32' name 'GetModuleHandleA';
  198. function GetCommandFile:pchar;forward;
  199. function paramstr(l : longint) : string;
  200. begin
  201. if (l>=0) and (l<argc) then
  202. paramstr:=strpas(argv[l])
  203. else
  204. paramstr:='';
  205. end;
  206. procedure randomize;
  207. begin
  208. randseed:=GetTickCount;
  209. end;
  210. {*****************************************************************************
  211. Heap Management
  212. *****************************************************************************}
  213. { memory functions }
  214. function GetProcessHeap : DWord;
  215. stdcall;external 'kernel32' name 'GetProcessHeap';
  216. function HeapAlloc(hHeap : DWord; dwFlags : DWord; dwBytes : DWord) : Longint;
  217. stdcall;external 'kernel32' name 'HeapAlloc';
  218. {$IFDEF SYSTEMDEBUG}
  219. function WinAPIHeapSize(hHeap : DWord; dwFlags : DWord; ptr : Pointer) : DWord;
  220. stdcall;external 'kernel32' name 'HeapSize';
  221. {$ENDIF}
  222. var
  223. heap : longint;external name 'HEAP';
  224. intern_heapsize : longint;external name 'HEAPSIZE';
  225. function getheapstart:pointer;
  226. assembler;
  227. asm
  228. leal HEAP,%eax
  229. end ['EAX'];
  230. function getheapsize:longint;
  231. assembler;
  232. asm
  233. movl intern_HEAPSIZE,%eax
  234. end ['EAX'];
  235. function Sbrk(size : longint):pointer;
  236. var
  237. l : longword;
  238. begin
  239. l := HeapAlloc(GetProcessHeap(), 0, size);
  240. {$ifdef DUMPGROW}
  241. Writeln('new heap part at $',hexstr(l,8), ' size = ',WinAPIHeapSize(GetProcessHeap()));
  242. {$endif}
  243. sbrk:=pointer(l);
  244. end;
  245. { include standard heap management }
  246. {$I heap.inc}
  247. {*****************************************************************************
  248. Low Level File Routines
  249. *****************************************************************************}
  250. function WriteFile(fh:longint;buf:pointer;len:longint;var loaded:longint;
  251. overlap:pointer):longint;
  252. stdcall;external 'kernel32' name 'WriteFile';
  253. function ReadFile(fh:longint;buf:pointer;len:longint;var loaded:longint;
  254. overlap:pointer):longint;
  255. stdcall;external 'kernel32' name 'ReadFile';
  256. function CloseHandle(h : longint) : longint;
  257. stdcall;external 'kernel32' name 'CloseHandle';
  258. function DeleteFile(p : pchar) : longint;
  259. stdcall;external 'kernel32' name 'DeleteFileA';
  260. function MoveFile(old,_new : pchar) : longint;
  261. stdcall;external 'kernel32' name 'MoveFileA';
  262. function SetFilePointer(l1,l2 : longint;l3 : pointer;l4 : longint) : longint;
  263. stdcall;external 'kernel32' name 'SetFilePointer';
  264. function GetFileSize(h:longint;p:pointer) : longint;
  265. stdcall;external 'kernel32' name 'GetFileSize';
  266. function CreateFile(lpFileName:pchar; dwDesiredAccess:DWORD; dwShareMode:DWORD;
  267. lpSecurityAttributes:PSECURITYATTRIBUTES; dwCreationDisposition:DWORD;
  268. dwFlagsAndAttributes:DWORD; hTemplateFile:DWORD):longint;
  269. stdcall;external 'kernel32' name 'CreateFileA';
  270. function SetEndOfFile(h : longint) : longbool;
  271. stdcall;external 'kernel32' name 'SetEndOfFile';
  272. function GetFileType(Handle:DWORD):DWord;
  273. stdcall;external 'kernel32' name 'GetFileType';
  274. function GetFileAttributes(p : pchar) : dword;
  275. stdcall;external 'kernel32' name 'GetFileAttributesA';
  276. procedure AllowSlash(p:pchar);
  277. var
  278. i : longint;
  279. begin
  280. { allow slash as backslash }
  281. for i:=0 to strlen(p) do
  282. if p[i]='/' then p[i]:='\';
  283. end;
  284. function do_isdevice(handle:longint):boolean;
  285. begin
  286. do_isdevice:=(getfiletype(handle)=2);
  287. end;
  288. procedure do_close(h : longint);
  289. begin
  290. if do_isdevice(h) then
  291. exit;
  292. CloseHandle(h);
  293. end;
  294. procedure do_erase(p : pchar);
  295. begin
  296. AllowSlash(p);
  297. if DeleteFile(p)=0 then
  298. Begin
  299. errno:=GetLastError;
  300. if errno=5 then
  301. begin
  302. if (GetFileAttributes(p)=FILE_ATTRIBUTE_DIRECTORY) then
  303. errno:=2;
  304. end;
  305. Errno2InoutRes;
  306. end;
  307. end;
  308. procedure do_rename(p1,p2 : pchar);
  309. begin
  310. AllowSlash(p1);
  311. AllowSlash(p2);
  312. if MoveFile(p1,p2)=0 then
  313. Begin
  314. errno:=GetLastError;
  315. Errno2InoutRes;
  316. end;
  317. end;
  318. function do_write(h,addr,len : longint) : longint;
  319. var
  320. size:longint;
  321. begin
  322. if writefile(h,pointer(addr),len,size,nil)=0 then
  323. Begin
  324. errno:=GetLastError;
  325. Errno2InoutRes;
  326. end;
  327. do_write:=size;
  328. end;
  329. function do_read(h,addr,len : longint) : longint;
  330. var
  331. _result:longint;
  332. begin
  333. if readfile(h,pointer(addr),len,_result,nil)=0 then
  334. Begin
  335. errno:=GetLastError;
  336. if errno=ERROR_BROKEN_PIPE then
  337. errno:=0
  338. else
  339. Errno2InoutRes;
  340. end;
  341. do_read:=_result;
  342. end;
  343. function do_filepos(handle : longint) : longint;
  344. var
  345. l:longint;
  346. begin
  347. l:=SetFilePointer(handle,0,nil,FILE_CURRENT);
  348. if l=-1 then
  349. begin
  350. l:=0;
  351. errno:=GetLastError;
  352. Errno2InoutRes;
  353. end;
  354. do_filepos:=l;
  355. end;
  356. procedure do_seek(handle,pos : longint);
  357. begin
  358. if SetFilePointer(handle,pos,nil,FILE_BEGIN)=-1 then
  359. Begin
  360. errno:=GetLastError;
  361. Errno2InoutRes;
  362. end;
  363. end;
  364. function do_seekend(handle:longint):longint;
  365. begin
  366. do_seekend:=SetFilePointer(handle,0,nil,FILE_END);
  367. if do_seekend=-1 then
  368. begin
  369. errno:=GetLastError;
  370. Errno2InoutRes;
  371. end;
  372. end;
  373. function do_filesize(handle : longint) : longint;
  374. var
  375. aktfilepos : longint;
  376. begin
  377. aktfilepos:=do_filepos(handle);
  378. do_filesize:=do_seekend(handle);
  379. do_seek(handle,aktfilepos);
  380. end;
  381. procedure do_truncate (handle,pos:longint);
  382. begin
  383. do_seek(handle,pos);
  384. if not(SetEndOfFile(handle)) then
  385. begin
  386. errno:=GetLastError;
  387. Errno2InoutRes;
  388. end;
  389. end;
  390. procedure do_open(var f;p:pchar;flags:longint);
  391. {
  392. filerec and textrec have both handle and mode as the first items so
  393. they could use the same routine for opening/creating.
  394. when (flags and $100) the file will be append
  395. when (flags and $1000) the file will be truncate/rewritten
  396. when (flags and $10000) there is no check for close (needed for textfiles)
  397. }
  398. Const
  399. file_Share_Read = $00000001;
  400. file_Share_Write = $00000002;
  401. Var
  402. shflags,
  403. oflags,cd : longint;
  404. security : TSecurityAttributes;
  405. begin
  406. AllowSlash(p);
  407. { close first if opened }
  408. if ((flags and $10000)=0) then
  409. begin
  410. case filerec(f).mode of
  411. fminput,fmoutput,fminout : Do_Close(filerec(f).handle);
  412. fmclosed : ;
  413. else
  414. begin
  415. {not assigned}
  416. inoutres:=102;
  417. exit;
  418. end;
  419. end;
  420. end;
  421. { reset file handle }
  422. filerec(f).handle:=UnusedHandle;
  423. { convert filesharing }
  424. shflags:=0;
  425. if ((filemode and fmshareExclusive) = fmshareExclusive) then
  426. { no sharing }
  427. else
  428. if (filemode = fmShareCompat) or ((filemode and fmshareDenyWrite) = fmshareDenyWrite) then
  429. shflags := file_Share_Read
  430. else
  431. if ((filemode and fmshareDenyRead) = fmshareDenyRead) then
  432. shflags := file_Share_Write
  433. else
  434. if ((filemode and fmshareDenyNone) = fmshareDenyNone) then
  435. shflags := file_Share_Read + file_Share_Write;
  436. { convert filemode to filerec modes }
  437. case (flags and 3) of
  438. 0 : begin
  439. filerec(f).mode:=fminput;
  440. oflags:=longint(GENERIC_READ);
  441. end;
  442. 1 : begin
  443. filerec(f).mode:=fmoutput;
  444. oflags:=longint(GENERIC_WRITE);
  445. end;
  446. 2 : begin
  447. filerec(f).mode:=fminout;
  448. oflags:=longint(GENERIC_WRITE or GENERIC_READ);
  449. end;
  450. end;
  451. { create it ? }
  452. if (flags and $1000)<>0 then
  453. cd:=CREATE_ALWAYS
  454. { or Append/Open ? }
  455. else
  456. cd:=OPEN_EXISTING;
  457. { empty name is special }
  458. if p[0]=#0 then
  459. begin
  460. case FileRec(f).mode of
  461. fminput :
  462. FileRec(f).Handle:=StdInputHandle;
  463. fminout, { this is set by rewrite }
  464. fmoutput :
  465. FileRec(f).Handle:=StdOutputHandle;
  466. fmappend :
  467. begin
  468. FileRec(f).Handle:=StdOutputHandle;
  469. FileRec(f).mode:=fmoutput; {fool fmappend}
  470. end;
  471. end;
  472. exit;
  473. end;
  474. security.nLength := Sizeof(TSecurityAttributes);
  475. security.bInheritHandle:=true;
  476. security.lpSecurityDescriptor:=nil;
  477. filerec(f).handle:=CreateFile(p,oflags,shflags,@security,cd,FILE_ATTRIBUTE_NORMAL,0);
  478. { append mode }
  479. if ((flags and $100)<>0) and
  480. (filerec(f).handle<>0) and
  481. (filerec(f).handle<>UnusedHandle) then
  482. begin
  483. do_seekend(filerec(f).handle);
  484. filerec(f).mode:=fmoutput; {fool fmappend}
  485. end;
  486. { get errors }
  487. { handle -1 is returned sometimes !! (PM) }
  488. if (filerec(f).handle=0) or (filerec(f).handle=UnusedHandle) then
  489. begin
  490. errno:=GetLastError;
  491. Errno2InoutRes;
  492. end;
  493. end;
  494. {*****************************************************************************
  495. UnTyped File Handling
  496. *****************************************************************************}
  497. {$i file.inc}
  498. {*****************************************************************************
  499. Typed File Handling
  500. *****************************************************************************}
  501. {$i typefile.inc}
  502. {*****************************************************************************
  503. Text File Handling
  504. *****************************************************************************}
  505. {$DEFINE EOF_CTRLZ}
  506. {$i text.inc}
  507. {*****************************************************************************
  508. Directory Handling
  509. *****************************************************************************}
  510. function CreateDirectory(name : pointer;sec : pointer) : longbool;
  511. stdcall;external 'kernel32' name 'CreateDirectoryA';
  512. function RemoveDirectory(name:pointer):longbool;
  513. stdcall;external 'kernel32' name 'RemoveDirectoryA';
  514. function SetCurrentDirectory(name : pointer) : longbool;
  515. stdcall;external 'kernel32' name 'SetCurrentDirectoryA';
  516. function GetCurrentDirectory(bufsize : longint;name : pchar) : longbool;
  517. stdcall;external 'kernel32' name 'GetCurrentDirectoryA';
  518. type
  519. TDirFnType=function(name:pointer):longbool;stdcall;
  520. procedure dirfn(afunc : TDirFnType;const s:string);
  521. var
  522. buffer : array[0..255] of char;
  523. begin
  524. move(s[1],buffer,length(s));
  525. buffer[length(s)]:=#0;
  526. AllowSlash(pchar(@buffer));
  527. if not aFunc(@buffer) then
  528. begin
  529. errno:=GetLastError;
  530. Errno2InoutRes;
  531. end;
  532. end;
  533. function CreateDirectoryTrunc(name:pointer):longbool;stdcall;
  534. begin
  535. CreateDirectoryTrunc:=CreateDirectory(name,nil);
  536. end;
  537. procedure mkdir(const s:string);[IOCHECK];
  538. begin
  539. If (s='') or (InOutRes <> 0) then
  540. exit;
  541. dirfn(TDirFnType(@CreateDirectoryTrunc),s);
  542. end;
  543. procedure rmdir(const s:string);[IOCHECK];
  544. begin
  545. if (s ='.') then
  546. InOutRes := 16;
  547. If (s='') or (InOutRes <> 0) then
  548. exit;
  549. dirfn(TDirFnType(@RemoveDirectory),s);
  550. end;
  551. procedure chdir(const s:string);[IOCHECK];
  552. begin
  553. If (s='') or (InOutRes <> 0) then
  554. exit;
  555. dirfn(TDirFnType(@SetCurrentDirectory),s);
  556. if Inoutres=2 then
  557. Inoutres:=3;
  558. end;
  559. procedure GetDir (DriveNr: byte; var Dir: ShortString);
  560. const
  561. Drive:array[0..3]of char=(#0,':',#0,#0);
  562. var
  563. defaultdrive:boolean;
  564. DirBuf,SaveBuf:array[0..259] of Char;
  565. begin
  566. defaultdrive:=drivenr=0;
  567. if not defaultdrive then
  568. begin
  569. byte(Drive[0]):=Drivenr+64;
  570. GetCurrentDirectory(SizeOf(SaveBuf),SaveBuf);
  571. if not SetCurrentDirectory(@Drive) then
  572. begin
  573. errno := word (GetLastError);
  574. Errno2InoutRes;
  575. Dir := char (DriveNr + 64) + ':\';
  576. SetCurrentDirectory(@SaveBuf);
  577. Exit;
  578. end;
  579. end;
  580. GetCurrentDirectory(SizeOf(DirBuf),DirBuf);
  581. if not defaultdrive then
  582. SetCurrentDirectory(@SaveBuf);
  583. dir:=strpas(DirBuf);
  584. if not FileNameCaseSensitive then
  585. dir:=upcase(dir);
  586. end;
  587. {*****************************************************************************
  588. SystemUnit Initialization
  589. *****************************************************************************}
  590. { Startup }
  591. procedure GetStartupInfo(p : pointer);
  592. stdcall;external 'kernel32' name 'GetStartupInfoA';
  593. function GetStdHandle(nStdHandle:DWORD):THANDLE;
  594. stdcall;external 'kernel32' name 'GetStdHandle';
  595. { command line/enviroment functions }
  596. function GetCommandLine : pchar;
  597. stdcall;external 'kernel32' name 'GetCommandLineA';
  598. function GetCurrentThread : dword;
  599. stdcall; external 'kernel32' name 'GetCurrentThread';
  600. var
  601. ModuleName : array[0..255] of char;
  602. function GetCommandFile:pchar;
  603. begin
  604. GetModuleFileName(0,@ModuleName,255);
  605. GetCommandFile:=@ModuleName;
  606. end;
  607. procedure setup_arguments;
  608. var
  609. arglen,
  610. count : longint;
  611. argstart,
  612. pc,arg : pchar;
  613. quote : char;
  614. argvlen : longint;
  615. procedure allocarg(idx,len:longint);
  616. begin
  617. if idx>=argvlen then
  618. begin
  619. argvlen:=(idx+8) and (not 7);
  620. sysreallocmem(argv,argvlen*sizeof(pointer));
  621. end;
  622. { use realloc to reuse already existing memory }
  623. { always allocate, even if length is zero, since }
  624. { the arg. is still present! }
  625. sysreallocmem(argv[idx],len+1);
  626. end;
  627. begin
  628. { create commandline, it starts with the executed filename which is argv[0] }
  629. { Win32 passes the command NOT via the args, but via getmodulefilename}
  630. count:=0;
  631. argv:=nil;
  632. argvlen:=0;
  633. pc:=getcommandfile;
  634. Arglen:=0;
  635. repeat
  636. Inc(Arglen);
  637. until (pc[Arglen]=#0);
  638. allocarg(count,arglen);
  639. move(pc^,argv[count]^,arglen);
  640. { Setup cmdline variable }
  641. cmdline:=GetCommandLine;
  642. { process arguments }
  643. pc:=cmdline;
  644. {$IfDef SYSTEM_DEBUG_STARTUP}
  645. Writeln(stderr,'Win32 GetCommandLine is #',pc,'#');
  646. {$EndIf }
  647. while pc^<>#0 do
  648. begin
  649. { skip leading spaces }
  650. while pc^ in [#1..#32] do
  651. inc(pc);
  652. if pc^=#0 then
  653. break;
  654. { calc argument length }
  655. quote:=' ';
  656. argstart:=pc;
  657. arglen:=0;
  658. while (pc^<>#0) do
  659. begin
  660. case pc^ of
  661. #1..#32 :
  662. begin
  663. if quote<>' ' then
  664. inc(arglen)
  665. else
  666. break;
  667. end;
  668. '"' :
  669. begin
  670. if quote<>'''' then
  671. begin
  672. if pchar(pc+1)^<>'"' then
  673. begin
  674. if quote='"' then
  675. quote:=' '
  676. else
  677. quote:='"';
  678. end
  679. else
  680. inc(pc);
  681. end
  682. else
  683. inc(arglen);
  684. end;
  685. '''' :
  686. begin
  687. if quote<>'"' then
  688. begin
  689. if pchar(pc+1)^<>'''' then
  690. begin
  691. if quote='''' then
  692. quote:=' '
  693. else
  694. quote:='''';
  695. end
  696. else
  697. inc(pc);
  698. end
  699. else
  700. inc(arglen);
  701. end;
  702. else
  703. inc(arglen);
  704. end;
  705. inc(pc);
  706. end;
  707. { copy argument }
  708. { Don't copy the first one, it is already there.}
  709. If Count<>0 then
  710. begin
  711. allocarg(count,arglen);
  712. quote:=' ';
  713. pc:=argstart;
  714. arg:=argv[count];
  715. while (pc^<>#0) do
  716. begin
  717. case pc^ of
  718. #1..#32 :
  719. begin
  720. if quote<>' ' then
  721. begin
  722. arg^:=pc^;
  723. inc(arg);
  724. end
  725. else
  726. break;
  727. end;
  728. '"' :
  729. begin
  730. if quote<>'''' then
  731. begin
  732. if pchar(pc+1)^<>'"' then
  733. begin
  734. if quote='"' then
  735. quote:=' '
  736. else
  737. quote:='"';
  738. end
  739. else
  740. inc(pc);
  741. end
  742. else
  743. begin
  744. arg^:=pc^;
  745. inc(arg);
  746. end;
  747. end;
  748. '''' :
  749. begin
  750. if quote<>'"' then
  751. begin
  752. if pchar(pc+1)^<>'''' then
  753. begin
  754. if quote='''' then
  755. quote:=' '
  756. else
  757. quote:='''';
  758. end
  759. else
  760. inc(pc);
  761. end
  762. else
  763. begin
  764. arg^:=pc^;
  765. inc(arg);
  766. end;
  767. end;
  768. else
  769. begin
  770. arg^:=pc^;
  771. inc(arg);
  772. end;
  773. end;
  774. inc(pc);
  775. end;
  776. arg^:=#0;
  777. end;
  778. {$IfDef SYSTEM_DEBUG_STARTUP}
  779. Writeln(stderr,'dos arg ',count,' #',arglen,'#',argv[count],'#');
  780. {$EndIf SYSTEM_DEBUG_STARTUP}
  781. inc(count);
  782. end;
  783. { get argc and create an nil entry }
  784. argc:=count;
  785. allocarg(argc,0);
  786. { free unused memory }
  787. sysreallocmem(argv,(argc+1)*sizeof(pointer));
  788. end;
  789. {*****************************************************************************
  790. System Dependent Exit code
  791. *****************************************************************************}
  792. procedure install_exception_handlers;forward;
  793. procedure remove_exception_handlers;forward;
  794. procedure PascalMain;stdcall;external name 'PASCALMAIN';
  795. procedure fpc_do_exit;stdcall;external name 'FPC_DO_EXIT';
  796. Procedure ExitDLL(Exitcode : longint); forward;
  797. procedure asm_exit; stdcall;external name 'asm_exit';
  798. Procedure system_exit;
  799. begin
  800. { don't call ExitProcess inside
  801. the DLL exit code !!
  802. This crashes Win95 at least PM }
  803. if IsLibrary then
  804. ExitDLL(ExitCode);
  805. if not IsConsole then
  806. begin
  807. Close(stderr);
  808. Close(stdout);
  809. { what about Input and Output ?? PM }
  810. end;
  811. remove_exception_handlers;
  812. { call exitprocess, with cleanup as required }
  813. asm
  814. xorl %eax, %eax
  815. movw exitcode,%ax
  816. call asm_exit
  817. end;
  818. end;
  819. var
  820. { value of the stack segment
  821. to check if the call stack can be written on exceptions }
  822. _SS : Cardinal;
  823. procedure Exe_entry;[public, alias : '_FPC_EXE_Entry'];
  824. begin
  825. IsLibrary:=false;
  826. { install the handlers for exe only ?
  827. or should we install them for DLL also ? (PM) }
  828. install_exception_handlers;
  829. { This strange construction is needed to solve the _SS problem
  830. with a smartlinked syswin32 (PFV) }
  831. asm
  832. { allocate space for an exception frame }
  833. pushl $0
  834. pushl %fs:(0)
  835. { movl %esp,%fs:(0)
  836. but don't insert it as it doesn't
  837. point to anything yet
  838. this will be used in signals unit }
  839. movl %esp,%eax
  840. movl %eax,System_exception_frame
  841. pushl %ebp
  842. xorl %ebp,%ebp
  843. movl %esp,%eax
  844. movl %eax,Win32StackTop
  845. movw %ss,%bp
  846. movl %ebp,_SS
  847. call SysResetFPU
  848. xorl %ebp,%ebp
  849. call PASCALMAIN
  850. popl %ebp
  851. end;
  852. { if we pass here there was no error ! }
  853. system_exit;
  854. end;
  855. Const
  856. { DllEntryPoint }
  857. DLL_PROCESS_ATTACH = 1;
  858. DLL_THREAD_ATTACH = 2;
  859. DLL_PROCESS_DETACH = 0;
  860. DLL_THREAD_DETACH = 3;
  861. Var
  862. DLLBuf : Jmp_buf;
  863. Const
  864. DLLExitOK : boolean = true;
  865. function Dll_entry : longbool;[public, alias : '_FPC_DLL_Entry'];
  866. var
  867. res : longbool;
  868. begin
  869. IsLibrary:=true;
  870. Dll_entry:=false;
  871. case DLLreason of
  872. DLL_PROCESS_ATTACH :
  873. begin
  874. If SetJmp(DLLBuf) = 0 then
  875. begin
  876. if assigned(Dll_Process_Attach_Hook) then
  877. begin
  878. res:=Dll_Process_Attach_Hook(DllParam);
  879. if not res then
  880. exit(false);
  881. end;
  882. PASCALMAIN;
  883. Dll_entry:=true;
  884. end
  885. else
  886. Dll_entry:=DLLExitOK;
  887. end;
  888. DLL_THREAD_ATTACH :
  889. begin
  890. inc(Thread_count);
  891. {$warning Allocate Threadvars !}
  892. if assigned(Dll_Thread_Attach_Hook) then
  893. Dll_Thread_Attach_Hook(DllParam);
  894. Dll_entry:=true; { return value is ignored }
  895. end;
  896. DLL_THREAD_DETACH :
  897. begin
  898. dec(Thread_count);
  899. if assigned(Dll_Thread_Detach_Hook) then
  900. Dll_Thread_Detach_Hook(DllParam);
  901. {$warning Release Threadvars !}
  902. Dll_entry:=true; { return value is ignored }
  903. end;
  904. DLL_PROCESS_DETACH :
  905. begin
  906. Dll_entry:=true; { return value is ignored }
  907. If SetJmp(DLLBuf) = 0 then
  908. begin
  909. FPC_DO_EXIT;
  910. end;
  911. if assigned(Dll_Process_Detach_Hook) then
  912. Dll_Process_Detach_Hook(DllParam);
  913. end;
  914. end;
  915. end;
  916. Procedure ExitDLL(Exitcode : longint);
  917. begin
  918. DLLExitOK:=ExitCode=0;
  919. LongJmp(DLLBuf,1);
  920. end;
  921. function GetCurrentProcess : dword;
  922. stdcall;external 'kernel32' name 'GetCurrentProcess';
  923. function ReadProcessMemory(process : dword;address : pointer;dest : pointer;size : dword;bytesread : pdword) : longbool;
  924. stdcall;external 'kernel32' name 'ReadProcessMemory';
  925. function is_prefetch(p : pointer) : boolean;
  926. var
  927. a : array[0..15] of byte;
  928. doagain : boolean;
  929. instrlo,instrhi,opcode : byte;
  930. i : longint;
  931. begin
  932. result:=false;
  933. { read memory savely without causing another exeception }
  934. if not(ReadProcessMemory(GetCurrentProcess,p,@a,sizeof(a),nil)) then
  935. exit;
  936. i:=0;
  937. doagain:=true;
  938. while doagain and (i<15) do
  939. begin
  940. opcode:=a[i];
  941. instrlo:=opcode and $f;
  942. instrhi:=opcode and $f0;
  943. case instrhi of
  944. { prefix? }
  945. $20,$30:
  946. doagain:=(instrlo and 7)=6;
  947. $60:
  948. doagain:=(instrlo and $c)=4;
  949. $f0:
  950. doagain:=instrlo in [0,2,3];
  951. $0:
  952. begin
  953. result:=(instrlo=$f) and (a[i+1] in [$d,$18]);
  954. exit;
  955. end;
  956. else
  957. doagain:=false;
  958. end;
  959. inc(i);
  960. end;
  961. end;
  962. //
  963. // Hardware exception handling
  964. //
  965. {$ifdef Set_i386_Exception_handler}
  966. {
  967. Error code definitions for the Win32 API functions
  968. Values are 32 bit values layed out as follows:
  969. 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
  970. 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
  971. +---+-+-+-----------------------+-------------------------------+
  972. |Sev|C|R| Facility | Code |
  973. +---+-+-+-----------------------+-------------------------------+
  974. where
  975. Sev - is the severity code
  976. 00 - Success
  977. 01 - Informational
  978. 10 - Warning
  979. 11 - Error
  980. C - is the Customer code flag
  981. R - is a reserved bit
  982. Facility - is the facility code
  983. Code - is the facility's status code
  984. }
  985. const
  986. SEVERITY_SUCCESS = $00000000;
  987. SEVERITY_INFORMATIONAL = $40000000;
  988. SEVERITY_WARNING = $80000000;
  989. SEVERITY_ERROR = $C0000000;
  990. const
  991. STATUS_SEGMENT_NOTIFICATION = $40000005;
  992. DBG_TERMINATE_THREAD = $40010003;
  993. DBG_TERMINATE_PROCESS = $40010004;
  994. DBG_CONTROL_C = $40010005;
  995. DBG_CONTROL_BREAK = $40010008;
  996. STATUS_GUARD_PAGE_VIOLATION = $80000001;
  997. STATUS_DATATYPE_MISALIGNMENT = $80000002;
  998. STATUS_BREAKPOINT = $80000003;
  999. STATUS_SINGLE_STEP = $80000004;
  1000. DBG_EXCEPTION_NOT_HANDLED = $80010001;
  1001. STATUS_ACCESS_VIOLATION = $C0000005;
  1002. STATUS_IN_PAGE_ERROR = $C0000006;
  1003. STATUS_INVALID_HANDLE = $C0000008;
  1004. STATUS_NO_MEMORY = $C0000017;
  1005. STATUS_ILLEGAL_INSTRUCTION = $C000001D;
  1006. STATUS_NONCONTINUABLE_EXCEPTION = $C0000025;
  1007. STATUS_INVALID_DISPOSITION = $C0000026;
  1008. STATUS_ARRAY_BOUNDS_EXCEEDED = $C000008C;
  1009. STATUS_FLOAT_DENORMAL_OPERAND = $C000008D;
  1010. STATUS_FLOAT_DIVIDE_BY_ZERO = $C000008E;
  1011. STATUS_FLOAT_INEXACT_RESULT = $C000008F;
  1012. STATUS_FLOAT_INVALID_OPERATION = $C0000090;
  1013. STATUS_FLOAT_OVERFLOW = $C0000091;
  1014. STATUS_FLOAT_STACK_CHECK = $C0000092;
  1015. STATUS_FLOAT_UNDERFLOW = $C0000093;
  1016. STATUS_INTEGER_DIVIDE_BY_ZERO = $C0000094;
  1017. STATUS_INTEGER_OVERFLOW = $C0000095;
  1018. STATUS_PRIVILEGED_INSTRUCTION = $C0000096;
  1019. STATUS_STACK_OVERFLOW = $C00000FD;
  1020. STATUS_CONTROL_C_EXIT = $C000013A;
  1021. STATUS_FLOAT_MULTIPLE_FAULTS = $C00002B4;
  1022. STATUS_FLOAT_MULTIPLE_TRAPS = $C00002B5;
  1023. STATUS_REG_NAT_CONSUMPTION = $C00002C9;
  1024. EXCEPTION_EXECUTE_HANDLER = 1;
  1025. EXCEPTION_CONTINUE_EXECUTION = -1;
  1026. EXCEPTION_CONTINUE_SEARCH = 0;
  1027. EXCEPTION_MAXIMUM_PARAMETERS = 15;
  1028. CONTEXT_X86 = $00010000;
  1029. CONTEXT_CONTROL = CONTEXT_X86 or $00000001;
  1030. CONTEXT_INTEGER = CONTEXT_X86 or $00000002;
  1031. CONTEXT_SEGMENTS = CONTEXT_X86 or $00000004;
  1032. CONTEXT_FLOATING_POINT = CONTEXT_X86 or $00000008;
  1033. CONTEXT_DEBUG_REGISTERS = CONTEXT_X86 or $00000010;
  1034. CONTEXT_EXTENDED_REGISTERS = CONTEXT_X86 or $00000020;
  1035. CONTEXT_FULL = CONTEXT_CONTROL or CONTEXT_INTEGER or CONTEXT_SEGMENTS;
  1036. MAXIMUM_SUPPORTED_EXTENSION = 512;
  1037. type
  1038. PFloatingSaveArea = ^TFloatingSaveArea;
  1039. TFloatingSaveArea = packed record
  1040. ControlWord : Cardinal;
  1041. StatusWord : Cardinal;
  1042. TagWord : Cardinal;
  1043. ErrorOffset : Cardinal;
  1044. ErrorSelector : Cardinal;
  1045. DataOffset : Cardinal;
  1046. DataSelector : Cardinal;
  1047. RegisterArea : array[0..79] of Byte;
  1048. Cr0NpxState : Cardinal;
  1049. end;
  1050. PContext = ^TContext;
  1051. TContext = packed record
  1052. //
  1053. // The flags values within this flag control the contents of
  1054. // a CONTEXT record.
  1055. //
  1056. ContextFlags : Cardinal;
  1057. //
  1058. // This section is specified/returned if CONTEXT_DEBUG_REGISTERS is
  1059. // set in ContextFlags. Note that CONTEXT_DEBUG_REGISTERS is NOT
  1060. // included in CONTEXT_FULL.
  1061. //
  1062. Dr0, Dr1, Dr2,
  1063. Dr3, Dr6, Dr7 : Cardinal;
  1064. //
  1065. // This section is specified/returned if the
  1066. // ContextFlags word contains the flag CONTEXT_FLOATING_POINT.
  1067. //
  1068. FloatSave : TFloatingSaveArea;
  1069. //
  1070. // This section is specified/returned if the
  1071. // ContextFlags word contains the flag CONTEXT_SEGMENTS.
  1072. //
  1073. SegGs, SegFs,
  1074. SegEs, SegDs : Cardinal;
  1075. //
  1076. // This section is specified/returned if the
  1077. // ContextFlags word contains the flag CONTEXT_INTEGER.
  1078. //
  1079. Edi, Esi, Ebx,
  1080. Edx, Ecx, Eax : Cardinal;
  1081. //
  1082. // This section is specified/returned if the
  1083. // ContextFlags word contains the flag CONTEXT_CONTROL.
  1084. //
  1085. Ebp : Cardinal;
  1086. Eip : Cardinal;
  1087. SegCs : Cardinal;
  1088. EFlags, Esp, SegSs : Cardinal;
  1089. //
  1090. // This section is specified/returned if the ContextFlags word
  1091. // contains the flag CONTEXT_EXTENDED_REGISTERS.
  1092. // The format and contexts are processor specific
  1093. //
  1094. ExtendedRegisters : array[0..MAXIMUM_SUPPORTED_EXTENSION-1] of Byte;
  1095. end;
  1096. type
  1097. PExceptionRecord = ^TExceptionRecord;
  1098. TExceptionRecord = packed record
  1099. ExceptionCode : Longint;
  1100. ExceptionFlags : Longint;
  1101. ExceptionRecord : PExceptionRecord;
  1102. ExceptionAddress : Pointer;
  1103. NumberParameters : Longint;
  1104. ExceptionInformation : array[0..EXCEPTION_MAXIMUM_PARAMETERS-1] of Pointer;
  1105. end;
  1106. PExceptionPointers = ^TExceptionPointers;
  1107. TExceptionPointers = packed record
  1108. ExceptionRecord : PExceptionRecord;
  1109. ContextRecord : PContext;
  1110. end;
  1111. { type of functions that should be used for exception handling }
  1112. TTopLevelExceptionFilter = function (excep : PExceptionPointers) : Longint;stdcall;
  1113. function SetUnhandledExceptionFilter(lpTopLevelExceptionFilter : TTopLevelExceptionFilter) : TTopLevelExceptionFilter;
  1114. stdcall;external 'kernel32' name 'SetUnhandledExceptionFilter';
  1115. const
  1116. MaxExceptionLevel = 16;
  1117. exceptLevel : Byte = 0;
  1118. var
  1119. exceptEip : array[0..MaxExceptionLevel-1] of Longint;
  1120. exceptError : array[0..MaxExceptionLevel-1] of Byte;
  1121. resetFPU : array[0..MaxExceptionLevel-1] of Boolean;
  1122. {$ifdef SYSTEMEXCEPTIONDEBUG}
  1123. procedure DebugHandleErrorAddrFrame(error, addr, frame : longint);
  1124. begin
  1125. if IsConsole then begin
  1126. write(stderr,'HandleErrorAddrFrame(error=',error);
  1127. write(stderr,',addr=',hexstr(addr,8));
  1128. writeln(stderr,',frame=',hexstr(frame,8),')');
  1129. end;
  1130. HandleErrorAddrFrame(error,addr,frame);
  1131. end;
  1132. {$endif SYSTEMEXCEPTIONDEBUG}
  1133. procedure JumpToHandleErrorFrame;
  1134. var
  1135. eip, ebp, error : Longint;
  1136. begin
  1137. // save ebp
  1138. asm
  1139. movl (%ebp),%eax
  1140. movl %eax,ebp
  1141. end;
  1142. if (exceptLevel > 0) then
  1143. dec(exceptLevel);
  1144. eip:=exceptEip[exceptLevel];
  1145. error:=exceptError[exceptLevel];
  1146. {$ifdef SYSTEMEXCEPTIONDEBUG}
  1147. if IsConsole then
  1148. writeln(stderr,'In JumpToHandleErrorFrame error=',error);
  1149. {$endif SYSTEMEXCEPTIONDEBUG}
  1150. if resetFPU[exceptLevel] then asm
  1151. fninit
  1152. fldcw fpucw
  1153. end;
  1154. { build a fake stack }
  1155. asm
  1156. {$ifdef REGCALL}
  1157. movl ebp,%ecx
  1158. movl eip,%edx
  1159. movl error,%eax
  1160. pushl eip
  1161. movl ebp,%ebp // Change frame pointer
  1162. {$else}
  1163. movl ebp,%eax
  1164. pushl %eax
  1165. movl eip,%eax
  1166. pushl %eax
  1167. movl error,%eax
  1168. pushl %eax
  1169. movl eip,%eax
  1170. pushl %eax
  1171. movl ebp,%ebp // Change frame pointer
  1172. {$endif}
  1173. {$ifdef SYSTEMEXCEPTIONDEBUG}
  1174. jmpl DebugHandleErrorAddrFrame
  1175. {$else not SYSTEMEXCEPTIONDEBUG}
  1176. jmpl HandleErrorAddrFrame
  1177. {$endif SYSTEMEXCEPTIONDEBUG}
  1178. end;
  1179. end;
  1180. function syswin32_i386_exception_handler(excep : PExceptionPointers) : Longint;stdcall;
  1181. var
  1182. frame,
  1183. res : longint;
  1184. function SysHandleErrorFrame(error, frame : Longint; must_reset_fpu : Boolean) : Longint;
  1185. begin
  1186. if (frame = 0) then
  1187. SysHandleErrorFrame:=EXCEPTION_CONTINUE_SEARCH
  1188. else begin
  1189. if (exceptLevel >= MaxExceptionLevel) then exit;
  1190. exceptEip[exceptLevel] := excep^.ContextRecord^.Eip;
  1191. exceptError[exceptLevel] := error;
  1192. resetFPU[exceptLevel] := must_reset_fpu;
  1193. inc(exceptLevel);
  1194. excep^.ContextRecord^.Eip := Longint(@JumpToHandleErrorFrame);
  1195. excep^.ExceptionRecord^.ExceptionCode := 0;
  1196. SysHandleErrorFrame := EXCEPTION_CONTINUE_EXECUTION;
  1197. {$ifdef SYSTEMEXCEPTIONDEBUG}
  1198. if IsConsole then begin
  1199. writeln(stderr,'Exception Continue Exception set at ',
  1200. hexstr(exceptEip[exceptLevel],8));
  1201. writeln(stderr,'Eip changed to ',
  1202. hexstr(longint(@JumpToHandleErrorFrame),8), ' error=', error);
  1203. end;
  1204. {$endif SYSTEMEXCEPTIONDEBUG}
  1205. end;
  1206. end;
  1207. begin
  1208. if excep^.ContextRecord^.SegSs=_SS then
  1209. frame := excep^.ContextRecord^.Ebp
  1210. else
  1211. frame := 0;
  1212. res := EXCEPTION_CONTINUE_SEARCH;
  1213. {$ifdef SYSTEMEXCEPTIONDEBUG}
  1214. if IsConsole then Writeln(stderr,'Exception ',
  1215. hexstr(excep^.ExceptionRecord^.ExceptionCode, 8));
  1216. {$endif SYSTEMEXCEPTIONDEBUG}
  1217. case cardinal(excep^.ExceptionRecord^.ExceptionCode) of
  1218. STATUS_INTEGER_DIVIDE_BY_ZERO,
  1219. STATUS_FLOAT_DIVIDE_BY_ZERO :
  1220. res := SysHandleErrorFrame(200, frame, true);
  1221. STATUS_ARRAY_BOUNDS_EXCEEDED :
  1222. res := SysHandleErrorFrame(201, frame, false);
  1223. STATUS_STACK_OVERFLOW :
  1224. res := SysHandleErrorFrame(202, frame, false);
  1225. STATUS_FLOAT_OVERFLOW :
  1226. res := SysHandleErrorFrame(205, frame, true);
  1227. STATUS_FLOAT_DENORMAL_OPERAND,
  1228. STATUS_FLOAT_UNDERFLOW :
  1229. res := SysHandleErrorFrame(206, frame, true);
  1230. {excep^.ContextRecord^.FloatSave.StatusWord := excep^.ContextRecord^.FloatSave.StatusWord and $ffffff00;}
  1231. STATUS_FLOAT_INEXACT_RESULT,
  1232. STATUS_FLOAT_INVALID_OPERATION,
  1233. STATUS_FLOAT_STACK_CHECK :
  1234. res := SysHandleErrorFrame(207, frame, true);
  1235. STATUS_INTEGER_OVERFLOW :
  1236. res := SysHandleErrorFrame(215, frame, false);
  1237. STATUS_ILLEGAL_INSTRUCTION:
  1238. res := SysHandleErrorFrame(216, frame, true);
  1239. STATUS_ACCESS_VIOLATION:
  1240. { Athlon prefetch bug? }
  1241. if is_prefetch(pointer(excep^.ContextRecord^.Eip)) then
  1242. begin
  1243. { if yes, then retry }
  1244. excep^.ExceptionRecord^.ExceptionCode := 0;
  1245. res:=EXCEPTION_CONTINUE_EXECUTION;
  1246. end
  1247. else
  1248. res := SysHandleErrorFrame(216, frame, true);
  1249. STATUS_CONTROL_C_EXIT:
  1250. res := SysHandleErrorFrame(217, frame, true);
  1251. STATUS_PRIVILEGED_INSTRUCTION:
  1252. res := SysHandleErrorFrame(218, frame, false);
  1253. else
  1254. begin
  1255. if ((excep^.ExceptionRecord^.ExceptionCode and SEVERITY_ERROR) = SEVERITY_ERROR) then
  1256. res := SysHandleErrorFrame(217, frame, true)
  1257. else
  1258. res := SysHandleErrorFrame(255, frame, true);
  1259. end;
  1260. end;
  1261. syswin32_i386_exception_handler := res;
  1262. end;
  1263. procedure install_exception_handlers;
  1264. {$ifdef SYSTEMEXCEPTIONDEBUG}
  1265. var
  1266. oldexceptaddr,
  1267. newexceptaddr : Longint;
  1268. {$endif SYSTEMEXCEPTIONDEBUG}
  1269. begin
  1270. {$ifdef SYSTEMEXCEPTIONDEBUG}
  1271. asm
  1272. movl $0,%eax
  1273. movl %fs:(%eax),%eax
  1274. movl %eax,oldexceptaddr
  1275. end;
  1276. {$endif SYSTEMEXCEPTIONDEBUG}
  1277. SetUnhandledExceptionFilter(@syswin32_i386_exception_handler);
  1278. {$ifdef SYSTEMEXCEPTIONDEBUG}
  1279. asm
  1280. movl $0,%eax
  1281. movl %fs:(%eax),%eax
  1282. movl %eax,newexceptaddr
  1283. end;
  1284. if IsConsole then
  1285. writeln(stderr,'Old exception ',hexstr(oldexceptaddr,8),
  1286. ' new exception ',hexstr(newexceptaddr,8));
  1287. {$endif SYSTEMEXCEPTIONDEBUG}
  1288. end;
  1289. procedure remove_exception_handlers;
  1290. begin
  1291. SetUnhandledExceptionFilter(nil);
  1292. end;
  1293. {$else not cpui386 (Processor specific !!)}
  1294. procedure install_exception_handlers;
  1295. begin
  1296. end;
  1297. procedure remove_exception_handlers;
  1298. begin
  1299. end;
  1300. {$endif Set_i386_Exception_handler}
  1301. {****************************************************************************
  1302. Error Message writing using messageboxes
  1303. ****************************************************************************}
  1304. function MessageBox(w1:longint;l1,l2:pointer;w2:longint):longint;
  1305. stdcall;external 'user32' name 'MessageBoxA';
  1306. const
  1307. ErrorBufferLength = 1024;
  1308. var
  1309. ErrorBuf : array[0..ErrorBufferLength] of char;
  1310. ErrorLen : longint;
  1311. Function ErrorWrite(Var F: TextRec): Integer;
  1312. {
  1313. An error message should always end with #13#10#13#10
  1314. }
  1315. var
  1316. p : pchar;
  1317. i : longint;
  1318. Begin
  1319. if F.BufPos>0 then
  1320. begin
  1321. if F.BufPos+ErrorLen>ErrorBufferLength then
  1322. i:=ErrorBufferLength-ErrorLen
  1323. else
  1324. i:=F.BufPos;
  1325. Move(F.BufPtr^,ErrorBuf[ErrorLen],i);
  1326. inc(ErrorLen,i);
  1327. ErrorBuf[ErrorLen]:=#0;
  1328. end;
  1329. if ErrorLen>3 then
  1330. begin
  1331. p:=@ErrorBuf[ErrorLen];
  1332. for i:=1 to 4 do
  1333. begin
  1334. dec(p);
  1335. if not(p^ in [#10,#13]) then
  1336. break;
  1337. end;
  1338. end;
  1339. if ErrorLen=ErrorBufferLength then
  1340. i:=4;
  1341. if (i=4) then
  1342. begin
  1343. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  1344. ErrorLen:=0;
  1345. end;
  1346. F.BufPos:=0;
  1347. ErrorWrite:=0;
  1348. End;
  1349. Function ErrorClose(Var F: TextRec): Integer;
  1350. begin
  1351. if ErrorLen>0 then
  1352. begin
  1353. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  1354. ErrorLen:=0;
  1355. end;
  1356. ErrorLen:=0;
  1357. ErrorClose:=0;
  1358. end;
  1359. Function ErrorOpen(Var F: TextRec): Integer;
  1360. Begin
  1361. TextRec(F).InOutFunc:=@ErrorWrite;
  1362. TextRec(F).FlushFunc:=@ErrorWrite;
  1363. TextRec(F).CloseFunc:=@ErrorClose;
  1364. ErrorOpen:=0;
  1365. End;
  1366. procedure AssignError(Var T: Text);
  1367. begin
  1368. Assign(T,'');
  1369. TextRec(T).OpenFunc:=@ErrorOpen;
  1370. Rewrite(T);
  1371. end;
  1372. procedure SysInitStdIO;
  1373. begin
  1374. { Setup stdin, stdout and stderr, for GUI apps redirect stderr,stdout to be
  1375. displayed in and messagebox }
  1376. StdInputHandle:=longint(GetStdHandle(cardinal(STD_INPUT_HANDLE)));
  1377. StdOutputHandle:=longint(GetStdHandle(cardinal(STD_OUTPUT_HANDLE)));
  1378. StdErrorHandle:=longint(GetStdHandle(cardinal(STD_ERROR_HANDLE)));
  1379. if not IsConsole then
  1380. begin
  1381. AssignError(stderr);
  1382. AssignError(stdout);
  1383. Assign(Output,'');
  1384. Assign(Input,'');
  1385. end
  1386. else
  1387. begin
  1388. OpenStdIO(Input,fmInput,StdInputHandle);
  1389. OpenStdIO(Output,fmOutput,StdOutputHandle);
  1390. OpenStdIO(StdOut,fmOutput,StdOutputHandle);
  1391. OpenStdIO(StdErr,fmOutput,StdErrorHandle);
  1392. end;
  1393. end;
  1394. const
  1395. Exe_entry_code : pointer = @Exe_entry;
  1396. Dll_entry_code : pointer = @Dll_entry;
  1397. begin
  1398. StackLength := InitialStkLen;
  1399. StackBottom := Sptr - StackLength;
  1400. { get some helpful informations }
  1401. GetStartupInfo(@startupinfo);
  1402. { some misc Win32 stuff }
  1403. hprevinst:=0;
  1404. if not IsLibrary then
  1405. HInstance:=getmodulehandle(GetCommandFile);
  1406. MainInstance:=HInstance;
  1407. cmdshow:=startupinfo.wshowwindow;
  1408. { Setup heap }
  1409. InitHeap;
  1410. SysInitExceptions;
  1411. SysInitStdIO;
  1412. { Arguments }
  1413. setup_arguments;
  1414. { Reset IO Error }
  1415. InOutRes:=0;
  1416. ThreadID := GetCurrentThread;
  1417. { Reset internal error variable }
  1418. errno:=0;
  1419. {$ifdef HASVARIANT}
  1420. initvariantmanager;
  1421. {$endif HASVARIANT}
  1422. end.
  1423. {
  1424. $Log$
  1425. Revision 1.53 2004-02-02 17:01:47 florian
  1426. * workaround for AMD prefetch bug
  1427. Revision 1.52 2004/01/20 23:12:49 hajny
  1428. * ExecuteProcess fixes, ProcessID and ThreadID added
  1429. Revision 1.51 2003/12/17 21:56:33 peter
  1430. * win32 regcall patches
  1431. Revision 1.50 2003/12/04 20:52:41 peter
  1432. * stdcall for CreateFile
  1433. Revision 1.49 2003/11/24 23:08:37 michael
  1434. + Redefined Fileopen so it corresponds to ascdef.inc definition
  1435. Revision 1.48 2003/11/03 09:42:28 marco
  1436. * Peter's Cardinal<->Longint fixes patch
  1437. Revision 1.47 2003/10/17 22:15:10 olle
  1438. * changed i386 to cpui386
  1439. Revision 1.46 2003/10/16 15:43:13 peter
  1440. * THandle is platform dependent
  1441. Revision 1.45 2003/10/06 23:52:53 florian
  1442. * some data types cleaned up
  1443. Revision 1.44 2003/09/27 11:52:36 peter
  1444. * sbrk returns pointer
  1445. Revision 1.43 2003/09/26 07:30:34 michael
  1446. + Win32 Do_open crahs on append
  1447. Revision 1.42 2003/09/17 15:06:36 peter
  1448. * stdcall patch
  1449. Revision 1.41 2003/09/12 12:33:43 olle
  1450. * nice-ified
  1451. Revision 1.40 2003/01/01 20:56:57 florian
  1452. + added invalid instruction exception
  1453. Revision 1.39 2002/12/24 15:35:15 peter
  1454. * error code fixes
  1455. Revision 1.38 2002/12/07 13:58:45 carl
  1456. * fix warnings
  1457. Revision 1.37 2002/11/30 18:17:35 carl
  1458. + profiling support
  1459. Revision 1.36 2002/10/31 15:17:58 carl
  1460. * always allocate argument even if its empty (bugfix web bug 2202)
  1461. Revision 1.35 2002/10/14 20:40:22 florian
  1462. * InitFPU renamed to SysResetFPU
  1463. Revision 1.34 2002/10/14 19:39:17 peter
  1464. * threads unit added for thread support
  1465. Revision 1.33 2002/10/13 09:28:45 florian
  1466. + call to initvariantmanager inserted
  1467. Revision 1.32 2002/09/07 21:28:10 carl
  1468. - removed os_types
  1469. * fix range check errors
  1470. Revision 1.31 2002/09/07 16:01:29 peter
  1471. * old logs removed and tabs fixed
  1472. Revision 1.30 2002/08/26 13:49:18 pierre
  1473. * fix bug report 2086
  1474. Revision 1.29 2002/07/28 20:43:49 florian
  1475. * several fixes for linux/powerpc
  1476. * several fixes to MT
  1477. Revision 1.28 2002/07/01 16:29:05 peter
  1478. * sLineBreak changed to normal constant like Kylix
  1479. Revision 1.27 2002/06/04 09:25:14 pierre
  1480. * Rename HeapSize to WinAPIHeapSize to avoid conflict with general function
  1481. Revision 1.26 2002/04/12 17:45:13 carl
  1482. + generic stack checking
  1483. Revision 1.25 2002/03/11 19:10:33 peter
  1484. * Regenerated with updated fpcmake
  1485. Revision 1.24 2002/01/30 14:57:11 pierre
  1486. * fix compilation failure
  1487. Revision 1.23 2002/01/25 16:23:03 peter
  1488. * merged filesearch() fix
  1489. }