syswin32.pp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  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. unit syswin32;
  14. interface
  15. {$ifdef i386}
  16. {$define Set_i386_Exception_handler}
  17. {$endif i386}
  18. { include system-independent routine headers }
  19. {$I systemh.inc}
  20. { include heap support headers }
  21. {$I heaph.inc}
  22. const
  23. { Default filehandles }
  24. UnusedHandle : longint = -1;
  25. StdInputHandle : longint = 0;
  26. StdOutputHandle : longint = 0;
  27. StdErrorHandle : longint = 0;
  28. FileNameCaseSensitive : boolean = true;
  29. type
  30. TStartupInfo=packed record
  31. cb : longint;
  32. lpReserved : Pointer;
  33. lpDesktop : Pointer;
  34. lpTitle : Pointer;
  35. dwX : longint;
  36. dwY : longint;
  37. dwXSize : longint;
  38. dwYSize : longint;
  39. dwXCountChars : longint;
  40. dwYCountChars : longint;
  41. dwFillAttribute : longint;
  42. dwFlags : longint;
  43. wShowWindow : Word;
  44. cbReserved2 : Word;
  45. lpReserved2 : Pointer;
  46. hStdInput : longint;
  47. hStdOutput : longint;
  48. hStdError : longint;
  49. end;
  50. var
  51. { C compatible arguments }
  52. argc : longint;
  53. argv : ppchar;
  54. { Win32 Info }
  55. startupinfo : tstartupinfo;
  56. hprevinst,
  57. HInstance,
  58. MainInstance,
  59. cmdshow : longint;
  60. IsLibrary,IsMultiThreaded,IsConsole : boolean;
  61. DLLreason,DLLparam:longint;
  62. Win32StackTop : Dword;
  63. { Thread count for DLL }
  64. const
  65. Thread_count : longint = 0;
  66. type
  67. TDLL_Process_Entry_Hook = function (dllparam : longint) : longbool;
  68. TDLL_Entry_Hook = procedure (dllparam : longint);
  69. const
  70. Dll_Process_Attach_Hook : TDLL_Process_Entry_Hook = nil;
  71. Dll_Process_Detach_Hook : TDLL_Entry_Hook = nil;
  72. Dll_Thread_Attach_Hook : TDLL_Entry_Hook = nil;
  73. Dll_Thread_Detach_Hook : TDLL_Entry_Hook = nil;
  74. implementation
  75. { include system independent routines }
  76. {$I system.inc}
  77. { some declarations for Win32 API calls }
  78. {$I win32.inc}
  79. CONST
  80. { These constants are used for conversion of error codes }
  81. { from win32 i/o errors to tp i/o errors }
  82. { errors 1 to 18 are the same as in Turbo Pascal }
  83. { DO NOT MODIFY UNLESS YOU KNOW EXACTLY WHAT YOU ARE DOING! }
  84. { The media is write protected. }
  85. ERROR_WRITE_PROTECT = 19;
  86. { The system cannot find the device specified. }
  87. ERROR_BAD_UNIT = 20;
  88. { The device is not ready. }
  89. ERROR_NOT_READY = 21;
  90. { The device does not recognize the command. }
  91. ERROR_BAD_COMMAND = 22;
  92. { Data error (cyclic redundancy check) }
  93. ERROR_CRC = 23;
  94. { The program issued a command but the }
  95. { command length is incorrect. }
  96. ERROR_BAD_LENGTH = 24;
  97. { The drive cannot locate a specific }
  98. { area or track on the disk. }
  99. ERROR_SEEK = 25;
  100. { The specified disk or diskette cannot be accessed. }
  101. ERROR_NOT_DOS_DISK = 26;
  102. { The drive cannot find the sector requested. }
  103. ERROR_SECTOR_NOT_FOUND = 27;
  104. { The printer is out of paper. }
  105. ERROR_OUT_OF_PAPER = 28;
  106. { The system cannot write to the specified device. }
  107. ERROR_WRITE_FAULT = 29;
  108. { The system cannot read from the specified device. }
  109. ERROR_READ_FAULT = 30;
  110. { A device attached to the system is not functioning.}
  111. ERROR_GEN_FAILURE = 31;
  112. { The process cannot access the file because }
  113. { it is being used by another process. }
  114. ERROR_SHARING_VIOLATION = 32;
  115. var
  116. errno : longint;
  117. {$ASMMODE ATT}
  118. { misc. functions }
  119. function GetLastError : DWORD;
  120. external 'kernel32' name 'GetLastError';
  121. { time and date functions }
  122. function GetTickCount : longint;
  123. external 'kernel32' name 'GetTickCount';
  124. { process functions }
  125. procedure ExitProcess(uExitCode : UINT);
  126. external 'kernel32' name 'ExitProcess';
  127. Procedure Errno2InOutRes;
  128. Begin
  129. { DO NOT MODIFY UNLESS YOU KNOW EXACTLY WHAT YOU ARE DOING }
  130. if (errno >= ERROR_WRITE_PROTECT) and (errno <= ERROR_GEN_FAILURE) THEN
  131. BEGIN
  132. { This is the offset to the Win32 to add to directly map }
  133. { to the DOS/TP compatible error codes when in this range }
  134. InOutRes := word(errno)+131;
  135. END
  136. else
  137. { This case is special }
  138. if errno=ERROR_SHARING_VIOLATION THEN
  139. BEGIN
  140. InOutRes :=5;
  141. END
  142. else
  143. { other error codes can directly be mapped }
  144. InOutRes := Word(errno);
  145. errno:=0;
  146. end;
  147. {$ifdef dummy}
  148. procedure int_stackcheck(stack_size:longint);[public,alias: 'STACKCHECK'];
  149. {
  150. called when trying to get local stack if the compiler directive $S
  151. is set this function must preserve esi !!!! because esi is set by
  152. the calling proc for methods it must preserve all registers !!
  153. With a 2048 byte safe area used to write to StdIo without crossing
  154. the stack boundary
  155. }
  156. begin
  157. asm
  158. pushl %eax
  159. pushl %ebx
  160. movl stack_size,%ebx
  161. addl $2048,%ebx
  162. movl %esp,%eax
  163. subl %ebx,%eax
  164. movl stacklimit,%ebx
  165. cmpl %eax,%ebx
  166. jae .L__short_on_stack
  167. popl %ebx
  168. popl %eax
  169. leave
  170. ret $4
  171. .L__short_on_stack:
  172. { can be usefull for error recovery !! }
  173. popl %ebx
  174. popl %eax
  175. end['EAX','EBX'];
  176. HandleError(202);
  177. end;
  178. {$endif dummy}
  179. procedure halt(errnum : byte);
  180. begin
  181. ExitCode:=errnum;
  182. do_exit;
  183. system_exit;
  184. end;
  185. function paramcount : longint;
  186. begin
  187. paramcount := argc - 1;
  188. end;
  189. { module functions }
  190. function GetModuleFileName(l1:longint;p:pointer;l2:longint):longint;
  191. external 'kernel32' name 'GetModuleFileNameA';
  192. function GetModuleHandle(p : pointer) : longint;
  193. external 'kernel32' name 'GetModuleHandleA';
  194. function GetCommandFile:pchar;forward;
  195. function paramstr(l : longint) : string;
  196. begin
  197. if (l>=0) and (l<argc) then
  198. paramstr:=strpas(argv[l])
  199. else
  200. paramstr:='';
  201. end;
  202. procedure randomize;
  203. begin
  204. randseed:=GetTickCount;
  205. end;
  206. {*****************************************************************************
  207. Heap Management
  208. *****************************************************************************}
  209. { memory functions }
  210. function GlobalAlloc(mode,size:longint):longint;
  211. external 'kernel32' name 'GlobalAlloc';
  212. function GlobalLock(handle:longint):pointer;
  213. external 'kernel32' name 'GlobalLock';
  214. {$ifdef SYSTEMDEBUG}
  215. function GlobalSize(h:longint):longint;
  216. external 'kernel32' name 'GlobalSize';
  217. {$endif}
  218. var
  219. heap : longint;external name 'HEAP';
  220. intern_heapsize : longint;external name 'HEAPSIZE';
  221. function getheapstart:pointer;assembler;
  222. asm
  223. leal HEAP,%eax
  224. end ['EAX'];
  225. function getheapsize:longint;assembler;
  226. asm
  227. movl intern_HEAPSIZE,%eax
  228. end ['EAX'];
  229. function Sbrk(size : longint):longint;
  230. var
  231. h,l : longint;
  232. begin
  233. h:=GlobalAlloc(258,size);
  234. l:=longint(GlobalLock(h));
  235. if l=0 then
  236. l:=-1;
  237. {$ifdef SYSTEMDEBUG}
  238. Writeln('new heap part at $',hexstr(l,8), ' size = ',GlobalSize(h));
  239. {$endif}
  240. sbrk:=l;
  241. end;
  242. { include standard heap management }
  243. {$I heap.inc}
  244. {*****************************************************************************
  245. Low Level File Routines
  246. *****************************************************************************}
  247. function WriteFile(fh:longint;buf:pointer;len:longint;var loaded:longint;
  248. overlap:pointer):longint;
  249. external 'kernel32' name 'WriteFile';
  250. function ReadFile(fh:longint;buf:pointer;len:longint;var loaded:longint;
  251. overlap:pointer):longint;
  252. external 'kernel32' name 'ReadFile';
  253. function CloseHandle(h : longint) : longint;
  254. external 'kernel32' name 'CloseHandle';
  255. function DeleteFile(p : pchar) : longint;
  256. external 'kernel32' name 'DeleteFileA';
  257. function MoveFile(old,_new : pchar) : longint;
  258. external 'kernel32' name 'MoveFileA';
  259. function SetFilePointer(l1,l2 : longint;l3 : pointer;l4 : longint) : longint;
  260. external 'kernel32' name 'SetFilePointer';
  261. function GetFileSize(h:longint;p:pointer) : longint;
  262. external 'kernel32' name 'GetFileSize';
  263. function CreateFile(name : pointer;access,sharing : longint;
  264. security : pointer;how,attr,template : longint) : longint;
  265. external 'kernel32' name 'CreateFileA';
  266. function SetEndOfFile(h : longint) : longbool;
  267. external 'kernel32' name 'SetEndOfFile';
  268. function GetFileType(Handle:DWORD):DWord;
  269. external 'kernel32' name 'GetFileType';
  270. procedure AllowSlash(p:pchar);
  271. var
  272. i : longint;
  273. begin
  274. { allow slash as backslash }
  275. for i:=0 to strlen(p) do
  276. if p[i]='/' then p[i]:='\';
  277. end;
  278. procedure do_close(h : longint);
  279. begin
  280. closehandle(h);
  281. end;
  282. procedure do_erase(p : pchar);
  283. begin
  284. AllowSlash(p);
  285. if DeleteFile(p)=0 then
  286. Begin
  287. errno:=GetLastError;
  288. Errno2InoutRes;
  289. end;
  290. end;
  291. procedure do_rename(p1,p2 : pchar);
  292. begin
  293. AllowSlash(p1);
  294. AllowSlash(p2);
  295. if MoveFile(p1,p2)=0 then
  296. Begin
  297. errno:=GetLastError;
  298. Errno2InoutRes;
  299. end;
  300. end;
  301. function do_write(h,addr,len : longint) : longint;
  302. var
  303. size:longint;
  304. begin
  305. if writefile(h,pointer(addr),len,size,nil)=0 then
  306. Begin
  307. errno:=GetLastError;
  308. Errno2InoutRes;
  309. end;
  310. do_write:=size;
  311. end;
  312. function do_read(h,addr,len : longint) : longint;
  313. var
  314. _result:longint;
  315. begin
  316. if readfile(h,pointer(addr),len,_result,nil)=0 then
  317. Begin
  318. errno:=GetLastError;
  319. Errno2InoutRes;
  320. end;
  321. do_read:=_result;
  322. end;
  323. function do_filepos(handle : longint) : longint;
  324. var
  325. l:longint;
  326. begin
  327. l:=SetFilePointer(handle,0,nil,FILE_CURRENT);
  328. if l=-1 then
  329. begin
  330. l:=0;
  331. errno:=GetLastError;
  332. Errno2InoutRes;
  333. end;
  334. do_filepos:=l;
  335. end;
  336. procedure do_seek(handle,pos : longint);
  337. begin
  338. if SetFilePointer(handle,pos,nil,FILE_BEGIN)=-1 then
  339. Begin
  340. errno:=GetLastError;
  341. Errno2InoutRes;
  342. end;
  343. end;
  344. function do_seekend(handle:longint):longint;
  345. begin
  346. do_seekend:=SetFilePointer(handle,0,nil,FILE_END);
  347. if do_seekend=-1 then
  348. begin
  349. errno:=GetLastError;
  350. Errno2InoutRes;
  351. end;
  352. end;
  353. function do_filesize(handle : longint) : longint;
  354. var
  355. aktfilepos : longint;
  356. begin
  357. aktfilepos:=do_filepos(handle);
  358. do_filesize:=do_seekend(handle);
  359. do_seek(handle,aktfilepos);
  360. end;
  361. procedure do_truncate (handle,pos:longint);
  362. begin
  363. do_seek(handle,pos);
  364. if not(SetEndOfFile(handle)) then
  365. begin
  366. errno:=GetLastError;
  367. Errno2InoutRes;
  368. end;
  369. end;
  370. procedure do_open(var f;p : pchar;flags:longint);
  371. {
  372. filerec and textrec have both handle and mode as the first items so
  373. they could use the same routine for opening/creating.
  374. when (flags and $100) the file will be append
  375. when (flags and $1000) the file will be truncate/rewritten
  376. when (flags and $10000) there is no check for close (needed for textfiles)
  377. }
  378. Const
  379. file_Share_Read = $00000001;
  380. file_Share_Write = $00000002;
  381. fmShareCompat = $00000000;
  382. fmShareExclusive = $10;
  383. fmShareDenyWrite = $20;
  384. fmShareDenyRead = $30;
  385. fmShareDenyNone = $40;
  386. Var
  387. shflags,
  388. oflags,cd : longint;
  389. begin
  390. AllowSlash(p);
  391. { close first if opened }
  392. if ((flags and $10000)=0) then
  393. begin
  394. case filerec(f).mode of
  395. fminput,fmoutput,fminout : Do_Close(filerec(f).handle);
  396. fmclosed : ;
  397. else
  398. begin
  399. {not assigned}
  400. inoutres:=102;
  401. exit;
  402. end;
  403. end;
  404. end;
  405. { reset file handle }
  406. filerec(f).handle:=UnusedHandle;
  407. { convert filesharing }
  408. shflags:=0;
  409. if ((filemode and fmshareExclusive) = fmshareExclusive) then
  410. { no sharing }
  411. else
  412. if (filemode = fmShareCompat) or ((filemode and fmshareDenyWrite) = fmshareDenyWrite) then
  413. shflags := file_Share_Read
  414. else
  415. if ((filemode and fmshareDenyRead) = fmshareDenyRead) then
  416. shflags := file_Share_Write
  417. else
  418. if ((filemode and fmshareDenyNone) = fmshareDenyNone) then
  419. shflags := file_Share_Read + file_Share_Write;
  420. { convert filemode to filerec modes }
  421. case (flags and 3) of
  422. 0 : begin
  423. filerec(f).mode:=fminput;
  424. oflags:=GENERIC_READ;
  425. end;
  426. 1 : begin
  427. filerec(f).mode:=fmoutput;
  428. oflags:=GENERIC_WRITE;
  429. end;
  430. 2 : begin
  431. filerec(f).mode:=fminout;
  432. oflags:=GENERIC_WRITE or GENERIC_READ;
  433. end;
  434. end;
  435. { standard is opening and existing file }
  436. cd:=OPEN_EXISTING;
  437. { create it ? }
  438. if (flags and $1000)<>0 then
  439. cd:=CREATE_ALWAYS
  440. { or append ? }
  441. else
  442. if (flags and $100)<>0 then
  443. cd:=OPEN_ALWAYS;
  444. { empty name is special }
  445. if p[0]=#0 then
  446. begin
  447. case filerec(f).mode of
  448. fminput : filerec(f).handle:=StdInputHandle;
  449. fmappend,
  450. fmoutput : begin
  451. filerec(f).handle:=StdOutputHandle;
  452. filerec(f).mode:=fmoutput; {fool fmappend}
  453. end;
  454. end;
  455. exit;
  456. end;
  457. filerec(f).handle:=CreateFile(p,oflags,shflags,nil,cd,FILE_ATTRIBUTE_NORMAL,0);
  458. { append mode }
  459. if (flags and $100)<>0 then
  460. begin
  461. do_seekend(filerec(f).handle);
  462. filerec(f).mode:=fmoutput; {fool fmappend}
  463. end;
  464. { get errors }
  465. { handle -1 is returned sometimes !! (PM) }
  466. if (filerec(f).handle=0) or (filerec(f).handle=-1) then
  467. begin
  468. errno:=GetLastError;
  469. Errno2InoutRes;
  470. end;
  471. end;
  472. function do_isdevice(handle:longint):boolean;
  473. begin
  474. do_isdevice:=(getfiletype(handle)=2);
  475. end;
  476. {*****************************************************************************
  477. UnTyped File Handling
  478. *****************************************************************************}
  479. {$i file.inc}
  480. {*****************************************************************************
  481. Typed File Handling
  482. *****************************************************************************}
  483. {$i typefile.inc}
  484. {*****************************************************************************
  485. Text File Handling
  486. *****************************************************************************}
  487. {$DEFINE EOF_CTRLZ}
  488. {$i text.inc}
  489. {*****************************************************************************
  490. Directory Handling
  491. *****************************************************************************}
  492. function CreateDirectory(name : pointer;sec : pointer) : longint;
  493. external 'kernel32' name 'CreateDirectoryA';
  494. function RemoveDirectory(name:pointer):longint;
  495. external 'kernel32' name 'RemoveDirectoryA';
  496. function SetCurrentDirectory(name : pointer) : longint;
  497. external 'kernel32' name 'SetCurrentDirectoryA';
  498. function GetCurrentDirectory(bufsize : longint;name : pchar) : longint;
  499. external 'kernel32' name 'GetCurrentDirectoryA';
  500. type
  501. TDirFnType=function(name:pointer):word;
  502. procedure dirfn(afunc : TDirFnType;const s:string);
  503. var
  504. buffer : array[0..255] of char;
  505. begin
  506. move(s[1],buffer,length(s));
  507. buffer[length(s)]:=#0;
  508. AllowSlash(pchar(@buffer));
  509. if aFunc(@buffer)=0 then
  510. begin
  511. errno:=GetLastError;
  512. Errno2InoutRes;
  513. end;
  514. end;
  515. function CreateDirectoryTrunc(name:pointer):word;
  516. begin
  517. CreateDirectoryTrunc:=CreateDirectory(name,nil);
  518. end;
  519. procedure mkdir(const s:string);[IOCHECK];
  520. begin
  521. If InOutRes <> 0 then exit;
  522. dirfn(TDirFnType(@CreateDirectoryTrunc),s);
  523. end;
  524. procedure rmdir(const s:string);[IOCHECK];
  525. begin
  526. If InOutRes <> 0 then exit;
  527. dirfn(TDirFnType(@RemoveDirectory),s);
  528. end;
  529. procedure chdir(const s:string);[IOCHECK];
  530. begin
  531. If InOutRes <> 0 then exit;
  532. dirfn(TDirFnType(@SetCurrentDirectory),s);
  533. end;
  534. procedure getdir(drivenr:byte;var dir:shortstring);
  535. const
  536. Drive:array[0..3]of char=(#0,':',#0,#0);
  537. var
  538. defaultdrive:boolean;
  539. DirBuf,SaveBuf:array[0..259] of Char;
  540. begin
  541. defaultdrive:=drivenr=0;
  542. if not defaultdrive then
  543. begin
  544. byte(Drive[0]):=Drivenr+64;
  545. GetCurrentDirectory(SizeOf(SaveBuf),SaveBuf);
  546. SetCurrentDirectory(@Drive);
  547. end;
  548. GetCurrentDirectory(SizeOf(DirBuf),DirBuf);
  549. if not defaultdrive then
  550. SetCurrentDirectory(@SaveBuf);
  551. dir:=strpas(DirBuf);
  552. if not FileNameCaseSensitive then
  553. dir:=upcase(dir);
  554. end;
  555. {*****************************************************************************
  556. SystemUnit Initialization
  557. *****************************************************************************}
  558. { Startup }
  559. procedure GetStartupInfo(p : pointer);
  560. external 'kernel32' name 'GetStartupInfoA';
  561. function GetStdHandle(nStdHandle:DWORD):THANDLE;
  562. external 'kernel32' name 'GetStdHandle';
  563. { command line/enviroment functions }
  564. function GetCommandLine : pchar;
  565. external 'kernel32' name 'GetCommandLineA';
  566. var
  567. ModuleName : array[0..255] of char;
  568. function GetCommandFile:pchar;
  569. begin
  570. GetModuleFileName(0,@ModuleName,255);
  571. GetCommandFile:=@ModuleName;
  572. end;
  573. procedure setup_arguments;
  574. var
  575. arglen,
  576. count : longint;
  577. argstart,
  578. pc : pchar;
  579. quote : set of char;
  580. argsbuf : array[0..127] of pchar;
  581. begin
  582. { create commandline, it starts with the executed filename which is argv[0] }
  583. { Win32 passes the command NOT via the args, but via getmodulefilename}
  584. count:=0;
  585. pc:=getcommandfile;
  586. Arglen:=0;
  587. repeat
  588. Inc(Arglen);
  589. until (pc[Arglen]=#0);
  590. getmem(argsbuf[count],arglen+1);
  591. move(pc^,argsbuf[count]^,arglen);
  592. { Now skip the first one }
  593. pc:=GetCommandLine;
  594. repeat
  595. { skip leading spaces }
  596. while pc^ in [' ',#9,#13] do
  597. inc(pc);
  598. case pc^ of
  599. #0 : break;
  600. '"' : begin
  601. quote:=['"'];
  602. inc(pc);
  603. end;
  604. '''' : begin
  605. quote:=[''''];
  606. inc(pc);
  607. end;
  608. else
  609. quote:=[' ',#9,#13];
  610. end;
  611. { scan until the end of the argument }
  612. argstart:=pc;
  613. while (pc^<>#0) and not(pc^ in quote) do
  614. inc(pc);
  615. { Don't copy the first one, it is already there.}
  616. If Count<>0 then
  617. begin
  618. { reserve some memory }
  619. arglen:=pc-argstart;
  620. getmem(argsbuf[count],arglen+1);
  621. move(argstart^,argsbuf[count]^,arglen);
  622. argsbuf[count][arglen]:=#0;
  623. end;
  624. { skip quote }
  625. if pc^ in quote then
  626. inc(pc);
  627. inc(count);
  628. until false;
  629. { create argc }
  630. argc:=count;
  631. { create an nil entry }
  632. argsbuf[count]:=nil;
  633. inc(count);
  634. { create the argv }
  635. getmem(argv,count shl 2);
  636. move(argsbuf,argv^,count shl 2);
  637. { Setup cmdline variable }
  638. cmdline:=GetCommandLine;
  639. end;
  640. {*****************************************************************************
  641. System Dependent Exit code
  642. *****************************************************************************}
  643. Procedure system_exit;
  644. begin
  645. if not IsConsole then
  646. begin
  647. Close(stderr);
  648. Close(stdout);
  649. { what about Input and Output ?? PM }
  650. end;
  651. ExitProcess(ExitCode);
  652. end;
  653. {$ifdef dummy}
  654. Function SetUpStack : longint;
  655. { This routine does the following : }
  656. { returns the value of the initial SP - __stklen }
  657. begin
  658. asm
  659. pushl %ebx
  660. pushl %eax
  661. movl __stklen,%ebx
  662. movl %esp,%eax
  663. subl %ebx,%eax
  664. movl %eax,__RESULT
  665. popl %eax
  666. popl %ebx
  667. end;
  668. end;
  669. {$endif}
  670. procedure install_exception_handlers;forward;
  671. procedure PascalMain;external name 'PASCALMAIN';
  672. procedure fpc_do_exit;external name 'FPC_DO_EXIT';
  673. var
  674. { value of the stack segment
  675. to check if the call stack can be written on exceptions }
  676. _SS : longint;
  677. procedure Exe_entry;[public, alias : '_FPC_EXE_Entry'];
  678. begin
  679. IsLibrary:=false;
  680. { install the handlers for exe only ?
  681. or should we install them for DLL also ? (PM) }
  682. install_exception_handlers;
  683. { This strange construction is needed to solve the _SS problem
  684. with a smartlinked syswin32 (PFV) }
  685. asm
  686. pushl %ebp
  687. xorl %ebp,%ebp
  688. movl %esp,%eax
  689. movl %eax,Win32StackTop
  690. movw %ss,%bp
  691. movl %ebp,_SS
  692. xorl %ebp,%ebp
  693. call PASCALMAIN
  694. popl %ebp
  695. end;
  696. { if we pass here there was no error ! }
  697. system_exit;
  698. end;
  699. Const
  700. { DllEntryPoint }
  701. DLL_PROCESS_ATTACH = 1;
  702. DLL_THREAD_ATTACH = 2;
  703. DLL_PROCESS_DETACH = 0;
  704. DLL_THREAD_DETACH = 3;
  705. function Dll_entry : longbool;[public, alias : '_FPC_DLL_Entry'];
  706. var
  707. res : longbool;
  708. begin
  709. IsLibrary:=true;
  710. case DLLreason of
  711. DLL_PROCESS_ATTACH :
  712. begin
  713. asm
  714. movl %esp,%eax
  715. movl %eax,Win32StackTop
  716. xorl %edi,%edi
  717. movw %ss,%di
  718. movl %edi,_SS
  719. end;
  720. if assigned(Dll_Process_Attach_Hook) then
  721. begin
  722. res:=Dll_Process_Attach_Hook(DllParam);
  723. if not res then
  724. begin
  725. Dll_entry:=false;
  726. exit;
  727. end;
  728. end;
  729. PASCALMAIN;
  730. Dll_entry:=true;
  731. end;
  732. DLL_THREAD_ATTACH :
  733. begin
  734. inc(Thread_count);
  735. if assigned(Dll_Thread_Attach_Hook) then
  736. Dll_Thread_Attach_Hook(DllParam);
  737. Dll_entry:=true; { return value is ignored }
  738. end;
  739. DLL_THREAD_DETACH :
  740. begin
  741. dec(Thread_count);
  742. if assigned(Dll_Thread_Detach_Hook) then
  743. Dll_Thread_Detach_Hook(DllParam);
  744. Dll_entry:=true; { return value is ignored }
  745. end;
  746. DLL_PROCESS_DETACH :
  747. begin
  748. inc(Thread_count);
  749. Dll_entry:=true; { return value is ignored }
  750. FPC_DO_EXIT;
  751. if assigned(Dll_Process_Detach_Hook) then
  752. Dll_Process_Detach_Hook(DllParam);
  753. end;
  754. end;
  755. end;
  756. {$ifdef Set_i386_Exception_handler}
  757. const
  758. EXCEPTION_MAXIMUM_PARAMETERS = 15;
  759. EXCEPTION_ACCESS_VIOLATION = $c0000005;
  760. EXCEPTION_BREAKPOINT = $80000003;
  761. EXCEPTION_DATATYPE_MISALIGNMENT = $80000002;
  762. EXCEPTION_SINGLE_STEP = $80000004;
  763. EXCEPTION_ARRAY_BOUNDS_EXCEEDED = $c000008c;
  764. EXCEPTION_FLT_DENORMAL_OPERAND = $c000008d;
  765. EXCEPTION_FLT_DIVIDE_BY_ZERO = $c000008e;
  766. EXCEPTION_FLT_INEXACT_RESULT = $c000008f;
  767. EXCEPTION_FLT_INVALID_OPERATION = $c0000090;
  768. EXCEPTION_FLT_OVERFLOW = $c0000091;
  769. EXCEPTION_FLT_STACK_CHECK = $c0000092;
  770. EXCEPTION_FLT_UNDERFLOW = $c0000093;
  771. EXCEPTION_INT_DIVIDE_BY_ZERO = $c0000094;
  772. EXCEPTION_INT_OVERFLOW = $c0000095;
  773. EXCEPTION_INVALID_HANDLE = $c0000008;
  774. EXCEPTION_PRIV_INSTRUCTION = $c0000096;
  775. EXCEPTION_NONCONTINUABLE_EXCEPTION = $c0000025;
  776. EXCEPTION_NONCONTINUABLE = $1;
  777. EXCEPTION_STACK_OVERFLOW = $c00000fd;
  778. EXCEPTION_INVALID_DISPOSITION = $c0000026;
  779. ExceptionContinueExecution = 0;
  780. ExceptionContinueSearch = 1;
  781. type
  782. FLOATING_SAVE_AREA = record
  783. ControlWord : DWORD;
  784. StatusWord : DWORD;
  785. TagWord : DWORD;
  786. ErrorOffset : DWORD;
  787. ErrorSelector : DWORD;
  788. DataOffset : DWORD;
  789. DataSelector : DWORD;
  790. RegisterArea : array[0..79] of BYTE;
  791. Cr0NpxState : DWORD;
  792. end;
  793. _FLOATING_SAVE_AREA = FLOATING_SAVE_AREA;
  794. TFLOATINGSAVEAREA = FLOATING_SAVE_AREA;
  795. PFLOATINGSAVEAREA = ^FLOATING_SAVE_AREA;
  796. CONTEXT = record
  797. ContextFlags : DWORD;
  798. Dr0 : DWORD;
  799. Dr1 : DWORD;
  800. Dr2 : DWORD;
  801. Dr3 : DWORD;
  802. Dr6 : DWORD;
  803. Dr7 : DWORD;
  804. FloatSave : FLOATING_SAVE_AREA;
  805. SegGs : DWORD;
  806. SegFs : DWORD;
  807. SegEs : DWORD;
  808. SegDs : DWORD;
  809. Edi : DWORD;
  810. Esi : DWORD;
  811. Ebx : DWORD;
  812. Edx : DWORD;
  813. Ecx : DWORD;
  814. Eax : DWORD;
  815. Ebp : DWORD;
  816. Eip : DWORD;
  817. SegCs : DWORD;
  818. EFlags : DWORD;
  819. Esp : DWORD;
  820. SegSs : DWORD;
  821. end;
  822. LPCONTEXT = ^CONTEXT;
  823. _CONTEXT = CONTEXT;
  824. TCONTEXT = CONTEXT;
  825. PCONTEXT = ^CONTEXT;
  826. type pexception_record = ^exception_record;
  827. EXCEPTION_RECORD = record
  828. ExceptionCode : longint;
  829. ExceptionFlags : longint;
  830. ExceptionRecord : pexception_record;
  831. ExceptionAddress : pointer;
  832. NumberParameters : longint;
  833. ExceptionInformation : array[0..EXCEPTION_MAXIMUM_PARAMETERS-1] of pointer;
  834. end;
  835. PEXCEPTION_POINTERS = ^EXCEPTION_POINTERS;
  836. EXCEPTION_POINTERS = record
  837. ExceptionRecord : PEXCEPTION_RECORD ;
  838. ContextRecord : PCONTEXT ;
  839. end;
  840. { type of functions that should be used for exception handling }
  841. LPTOP_LEVEL_EXCEPTION_FILTER = function(excep :PEXCEPTION_POINTERS) : longint;
  842. function SetUnhandledExceptionFilter(lpTopLevelExceptionFilter : LPTOP_LEVEL_EXCEPTION_FILTER)
  843. : LPTOP_LEVEL_EXCEPTION_FILTER;
  844. external 'kernel32' name 'SetUnhandledExceptionFilter';
  845. function syswin32_i386_exception_handler(excep :PEXCEPTION_POINTERS) : longint;
  846. var frame : longint;
  847. begin
  848. { default : unhandled !}
  849. if excep^.ContextRecord^.SegSs=_SS then
  850. frame:=excep^.ContextRecord^.Ebp
  851. else
  852. frame:=0;
  853. syswin32_i386_exception_handler:=ExceptionContinueSearch;
  854. case excep^.ExceptionRecord^.ExceptionCode of
  855. EXCEPTION_ACCESS_VIOLATION :
  856. HandleErrorFrame(216,frame);
  857. { EXCEPTION_BREAKPOINT = $80000003;
  858. EXCEPTION_DATATYPE_MISALIGNMENT = $80000002;
  859. EXCEPTION_SINGLE_STEP = $80000004; }
  860. EXCEPTION_ARRAY_BOUNDS_EXCEEDED :
  861. HandleErrorFrame(201,frame);
  862. { EXCEPTION_FLT_DENORMAL_OPERAND = $c000008d; }
  863. EXCEPTION_FLT_DIVIDE_BY_ZERO :
  864. HandleErrorFrame(200,frame);
  865. {EXCEPTION_FLT_INEXACT_RESULT = $c000008f;
  866. EXCEPTION_FLT_INVALID_OPERATION = $c0000090;}
  867. EXCEPTION_FLT_OVERFLOW :
  868. HandleErrorFrame(205,frame);
  869. EXCEPTION_FLT_STACK_CHECK :
  870. HandleErrorFrame(207,frame);
  871. { EXCEPTION_FLT_UNDERFLOW :
  872. HandleErrorFrame(206,frame); should be accepted as zero !! }
  873. EXCEPTION_INT_DIVIDE_BY_ZERO :
  874. HandleErrorFrame(200,frame);
  875. EXCEPTION_INT_OVERFLOW :
  876. HandleErrorFrame(215,frame);
  877. {EXCEPTION_INVALID_HANDLE = $c0000008;
  878. EXCEPTION_PRIV_INSTRUCTION = $c0000096;
  879. EXCEPTION_NONCONTINUABLE_EXCEPTION = $c0000025;
  880. EXCEPTION_NONCONTINUABLE = $1;}
  881. EXCEPTION_STACK_OVERFLOW :
  882. HandleErrorFrame(202,frame);
  883. {EXCEPTION_INVALID_DISPOSITION = $c0000026;}
  884. end;
  885. end;
  886. procedure install_exception_handlers;
  887. begin
  888. SetUnhandledExceptionFilter(@syswin32_i386_exception_handler);
  889. end;
  890. {$else not i386 (Processor specific !!)}
  891. procedure install_exception_handlers;
  892. begin
  893. end;
  894. {$endif Set_i386_Exception_handler}
  895. {****************************************************************************
  896. Error Message writing using messageboxes
  897. ****************************************************************************}
  898. function MessageBox(w1:longint;l1,l2:pointer;w2:longint):longint;
  899. external 'user32' name 'MessageBoxA';
  900. const
  901. ErrorBufferLength = 1024;
  902. var
  903. ErrorBuf : array[0..ErrorBufferLength] of char;
  904. ErrorLen : longint;
  905. Function ErrorWrite(Var F: TextRec): Integer;
  906. {
  907. An error message should always end with #13#10#13#10
  908. }
  909. var
  910. p : pchar;
  911. i : longint;
  912. Begin
  913. if F.BufPos>0 then
  914. begin
  915. if F.BufPos+ErrorLen>ErrorBufferLength then
  916. i:=ErrorBufferLength-ErrorLen
  917. else
  918. i:=F.BufPos;
  919. Move(F.BufPtr^,ErrorBuf[ErrorLen],i);
  920. inc(ErrorLen,i);
  921. ErrorBuf[ErrorLen]:=#0;
  922. end;
  923. if ErrorLen>3 then
  924. begin
  925. p:=@ErrorBuf[ErrorLen];
  926. for i:=1 to 4 do
  927. begin
  928. dec(p);
  929. if not(p^ in [#10,#13]) then
  930. break;
  931. end;
  932. end;
  933. if ErrorLen=ErrorBufferLength then
  934. i:=4;
  935. if (i=4) then
  936. begin
  937. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  938. ErrorLen:=0;
  939. end;
  940. F.BufPos:=0;
  941. ErrorWrite:=0;
  942. End;
  943. Function ErrorClose(Var F: TextRec): Integer;
  944. begin
  945. if ErrorLen>0 then
  946. begin
  947. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  948. ErrorLen:=0;
  949. end;
  950. ErrorLen:=0;
  951. ErrorClose:=0;
  952. end;
  953. Function ErrorOpen(Var F: TextRec): Integer;
  954. Begin
  955. TextRec(F).InOutFunc:=@ErrorWrite;
  956. TextRec(F).FlushFunc:=@ErrorWrite;
  957. TextRec(F).CloseFunc:=@ErrorClose;
  958. ErrorOpen:=0;
  959. End;
  960. procedure AssignError(Var T: Text);
  961. begin
  962. Assign(T,'');
  963. TextRec(T).OpenFunc:=@ErrorOpen;
  964. Rewrite(T);
  965. end;
  966. const
  967. Exe_entry_code : pointer = @Exe_entry;
  968. Dll_entry_code : pointer = @Dll_entry;
  969. begin
  970. { get some helpful informations }
  971. GetStartupInfo(@startupinfo);
  972. { some misc Win32 stuff }
  973. hprevinst:=0;
  974. if not IsLibrary then
  975. HInstance:=getmodulehandle(GetCommandFile);
  976. MainInstance:=HInstance;
  977. { No idea how to know this issue !! }
  978. IsMultithreaded:=false;
  979. cmdshow:=startupinfo.wshowwindow;
  980. { to test stack depth }
  981. loweststack:=maxlongint;
  982. { real test stack depth }
  983. { stacklimit := setupstack; }
  984. { Setup heap }
  985. InitHeap;
  986. InitExceptions;
  987. { Setup stdin, stdout and stderr, for GUI apps redirect stderr,stdout to be
  988. displayed in and messagebox }
  989. StdInputHandle:=longint(GetStdHandle(STD_INPUT_HANDLE));
  990. StdOutputHandle:=longint(GetStdHandle(STD_OUTPUT_HANDLE));
  991. StdErrorHandle:=longint(GetStdHandle(STD_ERROR_HANDLE));
  992. if not IsConsole then
  993. begin
  994. AssignError(stderr);
  995. AssignError(stdout);
  996. Assign(Output,'');
  997. Assign(Input,'');
  998. end
  999. else
  1000. begin
  1001. OpenStdIO(Input,fmInput,StdInputHandle);
  1002. OpenStdIO(Output,fmOutput,StdOutputHandle);
  1003. OpenStdIO(StdOut,fmOutput,StdOutputHandle);
  1004. OpenStdIO(StdErr,fmOutput,StdErrorHandle);
  1005. end;
  1006. { Arguments }
  1007. setup_arguments;
  1008. { Reset IO Error }
  1009. InOutRes:=0;
  1010. { Reset internal error variable }
  1011. errno:=0;
  1012. end.
  1013. {
  1014. $Log$
  1015. Revision 1.54 2000-01-07 16:41:52 daniel
  1016. * copyright 2000
  1017. Revision 1.53 2000/01/07 16:32:34 daniel
  1018. * copyright 2000 added
  1019. Revision 1.52 2000/01/06 23:40:36 peter
  1020. * fixed exitprocess call, it's now in system_exit and uses exitcode
  1021. Revision 1.51 1999/12/01 22:57:31 peter
  1022. * cmdline support
  1023. Revision 1.50 1999/11/20 00:16:44 pierre
  1024. + DLL Hooks for the four callings added
  1025. Revision 1.49 1999/11/18 22:19:57 pierre
  1026. * bug fix for web bug703 and 704
  1027. Revision 1.48 1999/11/09 22:34:00 pierre
  1028. * Check ErrorBuf at exit
  1029. + Win32StackTop
  1030. Revision 1.47 1999/10/26 12:25:51 peter
  1031. * report stderr,stdout to message box for errors
  1032. * close input,output when GUI app is made
  1033. Revision 1.46 1999/10/22 14:47:19 peter
  1034. * allocate an extra byte for argv[0]
  1035. Revision 1.45 1999/10/03 19:39:05 peter
  1036. * fixed argv[0] length
  1037. Revision 1.44 1999/09/10 15:40:35 peter
  1038. * fixed do_open flags to be > $100, becuase filemode can be upto 255
  1039. Revision 1.43 1999/07/07 10:04:43 michael
  1040. + Small edit in paramstr
  1041. Revision 1.42 1999/07/07 09:43:16 michael
  1042. Better construction of commandline argv
  1043. Revision 1.41 1999/07/05 20:04:30 peter
  1044. * removed temp defines
  1045. Revision 1.40 1999/06/11 16:26:40 michael
  1046. + Fixed paramstr(0)
  1047. Revision 1.39 1999/05/17 21:52:47 florian
  1048. * most of the Object Pascal stuff moved to the system unit
  1049. Revision 1.38 1999/04/28 11:42:53 peter
  1050. + FileNameCaseSensetive boolean
  1051. Revision 1.37 1999/04/08 12:23:11 peter
  1052. * removed os.inc
  1053. Revision 1.36 1999/03/24 23:25:59 peter
  1054. * fixed file sharing
  1055. Revision 1.35 1999/03/12 00:07:48 pierre
  1056. + code for coff writer
  1057. Revision 1.34 1999/03/10 22:15:31 florian
  1058. + system.cmdline variable for go32v2 and win32 added
  1059. Revision 1.33 1999/01/18 10:05:57 pierre
  1060. + system_exit procedure added
  1061. Revision 1.32 1998/12/28 23:30:11 peter
  1062. * fixes for smartlinking
  1063. Revision 1.31 1998/12/28 15:50:51 peter
  1064. + stdout, which is needed when you write something in the system unit
  1065. to the screen. Like the runtime error
  1066. Revision 1.30 1998/12/21 14:28:23 pierre
  1067. * HandleError -> HandleErrorFrame to avoid problem in
  1068. assembler code in i386.inc
  1069. (call to overloaded function in assembler block !)
  1070. Revision 1.29 1998/12/15 22:43:14 peter
  1071. * removed temp symbols
  1072. Revision 1.28 1998/12/09 17:57:33 pierre
  1073. + exception handling by default
  1074. Revision 1.27 1998/12/01 14:00:08 pierre
  1075. + added conversion from exceptions into run time error
  1076. (only if syswin32 compiled with -ddebug for now !)
  1077. * added HandleErrorFrame(errno,frame)
  1078. where you specify the frame
  1079. needed for win32 exception handling
  1080. Revision 1.26 1998/11/30 13:13:41 pierre
  1081. * needs asw to link correctly wprt0 or wdllprt0 file
  1082. Revision 1.25 1998/11/30 09:16:58 pierre
  1083. + added the changes from Pavel Ozerski after several modifications
  1084. to be able to create DLLs
  1085. Revision 1.24 1998/11/16 15:48:54 peter
  1086. * fixed longbool returns for api calls
  1087. Revision 1.23 1998/11/16 14:14:58 pierre
  1088. * changed getdir(byte,string) to getdir(byte,shortstring)
  1089. Revision 1.22 1998/10/27 15:07:16 florian
  1090. + Is* flags added
  1091. + IsLibrary works also
  1092. Revision 1.21 1998/10/15 16:26:19 peter
  1093. + fpuinit
  1094. + end of backtrace indicator
  1095. Revision 1.20 1998/09/14 10:48:33 peter
  1096. * FPC_ names
  1097. * Heap manager is now system independent
  1098. Revision 1.19 1998/09/02 09:03:46 pierre
  1099. * do_open sometimes returns -1 as handle on fail
  1100. was not checked correctly
  1101. Revision 1.16 1998/08/24 14:45:22 pierre
  1102. * sbrk was wrong
  1103. heap growing now works for win32
  1104. Revision 1.15 1998/08/21 10:10:16 peter
  1105. * winheap turned off by default
  1106. Revision 1.14 1998/07/30 13:27:19 michael
  1107. + Added support for errorproc. Changed runerror to HandleError
  1108. Revision 1.13 1998/07/13 21:19:15 florian
  1109. * some problems with ansi string support fixed
  1110. Revision 1.12 1998/07/07 12:37:28 carl
  1111. * correct mapping of error codes for TP compatibility
  1112. + implemented stack checking in ifdef dummy
  1113. Revision 1.11 1998/07/02 12:33:18 carl
  1114. * IOCheck/InOutRes check for mkdir,rmdir and chdir like in TP
  1115. Revision 1.10 1998/07/01 15:30:02 peter
  1116. * better readln/writeln
  1117. Revision 1.9 1998/06/10 10:39:17 peter
  1118. * working w32 rtl
  1119. Revision 1.8 1998/06/08 23:07:47 peter
  1120. * dos interface is now 100% compatible
  1121. * fixed call PASCALMAIN which must be direct asm
  1122. Revision 1.7 1998/05/06 12:36:51 michael
  1123. + Removed log from before restored version.
  1124. Revision 1.6 1998/04/27 18:29:09 florian
  1125. + do_open implemented, the file-I/O should be now complete
  1126. Revision 1.5 1998/04/27 13:58:21 florian
  1127. + paramstr/paramcount implemented
  1128. Revision 1.4 1998/04/26 22:37:22 florian
  1129. * some small extensions
  1130. Revision 1.3 1998/04/26 21:49:57 florian
  1131. + more stuff added (??dir procedures etc.)
  1132. }