syswin32.pp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  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. function paramcount : longint;
  180. begin
  181. paramcount := argc - 1;
  182. end;
  183. { module functions }
  184. function GetModuleFileName(l1:longint;p:pointer;l2:longint):longint;
  185. external 'kernel32' name 'GetModuleFileNameA';
  186. function GetModuleHandle(p : pointer) : longint;
  187. external 'kernel32' name 'GetModuleHandleA';
  188. function GetCommandFile:pchar;forward;
  189. function paramstr(l : longint) : string;
  190. begin
  191. if (l>=0) and (l<argc) then
  192. paramstr:=strpas(argv[l])
  193. else
  194. paramstr:='';
  195. end;
  196. procedure randomize;
  197. begin
  198. randseed:=GetTickCount;
  199. end;
  200. {*****************************************************************************
  201. Heap Management
  202. *****************************************************************************}
  203. { memory functions }
  204. function GlobalAlloc(mode,size:longint):longint;
  205. external 'kernel32' name 'GlobalAlloc';
  206. function GlobalLock(handle:longint):pointer;
  207. external 'kernel32' name 'GlobalLock';
  208. {$ifdef SYSTEMDEBUG}
  209. function GlobalSize(h:longint):longint;
  210. external 'kernel32' name 'GlobalSize';
  211. {$endif}
  212. var
  213. heap : longint;external name 'HEAP';
  214. intern_heapsize : longint;external name 'HEAPSIZE';
  215. function getheapstart:pointer;assembler;
  216. asm
  217. leal HEAP,%eax
  218. end ['EAX'];
  219. function getheapsize:longint;assembler;
  220. asm
  221. movl intern_HEAPSIZE,%eax
  222. end ['EAX'];
  223. function Sbrk(size : longint):longint;
  224. var
  225. h,l : longint;
  226. begin
  227. h:=GlobalAlloc(258,size);
  228. l:=longint(GlobalLock(h));
  229. if l=0 then
  230. l:=-1;
  231. {$ifdef SYSTEMDEBUG}
  232. Writeln('new heap part at $',hexstr(l,8), ' size = ',GlobalSize(h));
  233. {$endif}
  234. sbrk:=l;
  235. end;
  236. { include standard heap management }
  237. {$I heap.inc}
  238. {*****************************************************************************
  239. Low Level File Routines
  240. *****************************************************************************}
  241. function WriteFile(fh:longint;buf:pointer;len:longint;var loaded:longint;
  242. overlap:pointer):longint;
  243. external 'kernel32' name 'WriteFile';
  244. function ReadFile(fh:longint;buf:pointer;len:longint;var loaded:longint;
  245. overlap:pointer):longint;
  246. external 'kernel32' name 'ReadFile';
  247. function CloseHandle(h : longint) : longint;
  248. external 'kernel32' name 'CloseHandle';
  249. function DeleteFile(p : pchar) : longint;
  250. external 'kernel32' name 'DeleteFileA';
  251. function MoveFile(old,_new : pchar) : longint;
  252. external 'kernel32' name 'MoveFileA';
  253. function SetFilePointer(l1,l2 : longint;l3 : pointer;l4 : longint) : longint;
  254. external 'kernel32' name 'SetFilePointer';
  255. function GetFileSize(h:longint;p:pointer) : longint;
  256. external 'kernel32' name 'GetFileSize';
  257. function CreateFile(name : pointer;access,sharing : longint;
  258. security : pointer;how,attr,template : longint) : longint;
  259. external 'kernel32' name 'CreateFileA';
  260. function SetEndOfFile(h : longint) : longbool;
  261. external 'kernel32' name 'SetEndOfFile';
  262. function GetFileType(Handle:DWORD):DWord;
  263. external 'kernel32' name 'GetFileType';
  264. procedure AllowSlash(p:pchar);
  265. var
  266. i : longint;
  267. begin
  268. { allow slash as backslash }
  269. for i:=0 to strlen(p) do
  270. if p[i]='/' then p[i]:='\';
  271. end;
  272. function do_isdevice(handle:longint):boolean;
  273. begin
  274. do_isdevice:=(getfiletype(handle)=2);
  275. end;
  276. procedure do_close(h : longint);
  277. begin
  278. if do_isdevice(h) then
  279. exit;
  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 :
  449. FileRec(f).Handle:=StdInputHandle;
  450. fminout, { this is set by rewrite }
  451. fmoutput :
  452. FileRec(f).Handle:=StdOutputHandle;
  453. fmappend :
  454. begin
  455. FileRec(f).Handle:=StdOutputHandle;
  456. FileRec(f).mode:=fmoutput; {fool fmappend}
  457. end;
  458. end;
  459. exit;
  460. end;
  461. filerec(f).handle:=CreateFile(p,oflags,shflags,nil,cd,FILE_ATTRIBUTE_NORMAL,0);
  462. { append mode }
  463. if (flags and $100)<>0 then
  464. begin
  465. do_seekend(filerec(f).handle);
  466. filerec(f).mode:=fmoutput; {fool fmappend}
  467. end;
  468. { get errors }
  469. { handle -1 is returned sometimes !! (PM) }
  470. if (filerec(f).handle=0) or (filerec(f).handle=-1) then
  471. begin
  472. errno:=GetLastError;
  473. Errno2InoutRes;
  474. end;
  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. { don't call ExitProcess inside
  646. the DLL exit code !!
  647. This crashes Win95 at least PM }
  648. if IsLibrary then
  649. Exit;
  650. if not IsConsole then
  651. begin
  652. Close(stderr);
  653. Close(stdout);
  654. { what about Input and Output ?? PM }
  655. end;
  656. ExitProcess(ExitCode);
  657. end;
  658. {$ifdef dummy}
  659. Function SetUpStack : longint;
  660. { This routine does the following : }
  661. { returns the value of the initial SP - __stklen }
  662. begin
  663. asm
  664. pushl %ebx
  665. pushl %eax
  666. movl __stklen,%ebx
  667. movl %esp,%eax
  668. subl %ebx,%eax
  669. movl %eax,__RESULT
  670. popl %eax
  671. popl %ebx
  672. end;
  673. end;
  674. {$endif}
  675. procedure install_exception_handlers;forward;
  676. procedure PascalMain;external name 'PASCALMAIN';
  677. procedure fpc_do_exit;external name 'FPC_DO_EXIT';
  678. var
  679. { value of the stack segment
  680. to check if the call stack can be written on exceptions }
  681. _SS : longint;
  682. procedure Exe_entry;[public, alias : '_FPC_EXE_Entry'];
  683. begin
  684. IsLibrary:=false;
  685. { install the handlers for exe only ?
  686. or should we install them for DLL also ? (PM) }
  687. install_exception_handlers;
  688. { This strange construction is needed to solve the _SS problem
  689. with a smartlinked syswin32 (PFV) }
  690. asm
  691. pushl %ebp
  692. xorl %ebp,%ebp
  693. movl %esp,%eax
  694. movl %eax,Win32StackTop
  695. movw %ss,%bp
  696. movl %ebp,_SS
  697. xorl %ebp,%ebp
  698. call PASCALMAIN
  699. popl %ebp
  700. end;
  701. { if we pass here there was no error ! }
  702. system_exit;
  703. end;
  704. Const
  705. { DllEntryPoint }
  706. DLL_PROCESS_ATTACH = 1;
  707. DLL_THREAD_ATTACH = 2;
  708. DLL_PROCESS_DETACH = 0;
  709. DLL_THREAD_DETACH = 3;
  710. function Dll_entry : longbool;[public, alias : '_FPC_DLL_Entry'];
  711. var
  712. res : longbool;
  713. begin
  714. IsLibrary:=true;
  715. case DLLreason of
  716. DLL_PROCESS_ATTACH :
  717. begin
  718. asm
  719. movl %esp,%eax
  720. movl %eax,Win32StackTop
  721. xorl %edi,%edi
  722. movw %ss,%di
  723. movl %edi,_SS
  724. end;
  725. if assigned(Dll_Process_Attach_Hook) then
  726. begin
  727. res:=Dll_Process_Attach_Hook(DllParam);
  728. if not res then
  729. begin
  730. Dll_entry:=false;
  731. exit;
  732. end;
  733. end;
  734. PASCALMAIN;
  735. Dll_entry:=true;
  736. end;
  737. DLL_THREAD_ATTACH :
  738. begin
  739. inc(Thread_count);
  740. if assigned(Dll_Thread_Attach_Hook) then
  741. Dll_Thread_Attach_Hook(DllParam);
  742. Dll_entry:=true; { return value is ignored }
  743. end;
  744. DLL_THREAD_DETACH :
  745. begin
  746. dec(Thread_count);
  747. if assigned(Dll_Thread_Detach_Hook) then
  748. Dll_Thread_Detach_Hook(DllParam);
  749. Dll_entry:=true; { return value is ignored }
  750. end;
  751. DLL_PROCESS_DETACH :
  752. begin
  753. inc(Thread_count);
  754. Dll_entry:=true; { return value is ignored }
  755. FPC_DO_EXIT;
  756. if assigned(Dll_Process_Detach_Hook) then
  757. Dll_Process_Detach_Hook(DllParam);
  758. end;
  759. end;
  760. end;
  761. {$ifdef Set_i386_Exception_handler}
  762. const
  763. EXCEPTION_MAXIMUM_PARAMETERS = 15;
  764. EXCEPTION_ACCESS_VIOLATION = $c0000005;
  765. EXCEPTION_BREAKPOINT = $80000003;
  766. EXCEPTION_DATATYPE_MISALIGNMENT = $80000002;
  767. EXCEPTION_SINGLE_STEP = $80000004;
  768. EXCEPTION_ARRAY_BOUNDS_EXCEEDED = $c000008c;
  769. EXCEPTION_FLT_DENORMAL_OPERAND = $c000008d;
  770. EXCEPTION_FLT_DIVIDE_BY_ZERO = $c000008e;
  771. EXCEPTION_FLT_INEXACT_RESULT = $c000008f;
  772. EXCEPTION_FLT_INVALID_OPERATION = $c0000090;
  773. EXCEPTION_FLT_OVERFLOW = $c0000091;
  774. EXCEPTION_FLT_STACK_CHECK = $c0000092;
  775. EXCEPTION_FLT_UNDERFLOW = $c0000093;
  776. EXCEPTION_INT_DIVIDE_BY_ZERO = $c0000094;
  777. EXCEPTION_INT_OVERFLOW = $c0000095;
  778. EXCEPTION_INVALID_HANDLE = $c0000008;
  779. EXCEPTION_PRIV_INSTRUCTION = $c0000096;
  780. EXCEPTION_NONCONTINUABLE_EXCEPTION = $c0000025;
  781. EXCEPTION_NONCONTINUABLE = $1;
  782. EXCEPTION_STACK_OVERFLOW = $c00000fd;
  783. EXCEPTION_INVALID_DISPOSITION = $c0000026;
  784. ExceptionContinueExecution = 0;
  785. ExceptionContinueSearch = 1;
  786. type
  787. FLOATING_SAVE_AREA = record
  788. ControlWord : DWORD;
  789. StatusWord : DWORD;
  790. TagWord : DWORD;
  791. ErrorOffset : DWORD;
  792. ErrorSelector : DWORD;
  793. DataOffset : DWORD;
  794. DataSelector : DWORD;
  795. RegisterArea : array[0..79] of BYTE;
  796. Cr0NpxState : DWORD;
  797. end;
  798. _FLOATING_SAVE_AREA = FLOATING_SAVE_AREA;
  799. TFLOATINGSAVEAREA = FLOATING_SAVE_AREA;
  800. PFLOATINGSAVEAREA = ^FLOATING_SAVE_AREA;
  801. CONTEXT = record
  802. ContextFlags : DWORD;
  803. Dr0 : DWORD;
  804. Dr1 : DWORD;
  805. Dr2 : DWORD;
  806. Dr3 : DWORD;
  807. Dr6 : DWORD;
  808. Dr7 : DWORD;
  809. FloatSave : FLOATING_SAVE_AREA;
  810. SegGs : DWORD;
  811. SegFs : DWORD;
  812. SegEs : DWORD;
  813. SegDs : DWORD;
  814. Edi : DWORD;
  815. Esi : DWORD;
  816. Ebx : DWORD;
  817. Edx : DWORD;
  818. Ecx : DWORD;
  819. Eax : DWORD;
  820. Ebp : DWORD;
  821. Eip : DWORD;
  822. SegCs : DWORD;
  823. EFlags : DWORD;
  824. Esp : DWORD;
  825. SegSs : DWORD;
  826. end;
  827. LPCONTEXT = ^CONTEXT;
  828. _CONTEXT = CONTEXT;
  829. TCONTEXT = CONTEXT;
  830. PCONTEXT = ^CONTEXT;
  831. type pexception_record = ^exception_record;
  832. EXCEPTION_RECORD = record
  833. ExceptionCode : longint;
  834. ExceptionFlags : longint;
  835. ExceptionRecord : pexception_record;
  836. ExceptionAddress : pointer;
  837. NumberParameters : longint;
  838. ExceptionInformation : array[0..EXCEPTION_MAXIMUM_PARAMETERS-1] of pointer;
  839. end;
  840. PEXCEPTION_POINTERS = ^EXCEPTION_POINTERS;
  841. EXCEPTION_POINTERS = record
  842. ExceptionRecord : PEXCEPTION_RECORD ;
  843. ContextRecord : PCONTEXT ;
  844. end;
  845. { type of functions that should be used for exception handling }
  846. LPTOP_LEVEL_EXCEPTION_FILTER = function(excep :PEXCEPTION_POINTERS) : longint;
  847. function SetUnhandledExceptionFilter(lpTopLevelExceptionFilter : LPTOP_LEVEL_EXCEPTION_FILTER)
  848. : LPTOP_LEVEL_EXCEPTION_FILTER;
  849. external 'kernel32' name 'SetUnhandledExceptionFilter';
  850. function syswin32_i386_exception_handler(excep :PEXCEPTION_POINTERS) : longint;
  851. var frame : longint;
  852. begin
  853. { default : unhandled !}
  854. if excep^.ContextRecord^.SegSs=_SS then
  855. frame:=excep^.ContextRecord^.Ebp
  856. else
  857. frame:=0;
  858. syswin32_i386_exception_handler:=ExceptionContinueSearch;
  859. case excep^.ExceptionRecord^.ExceptionCode of
  860. EXCEPTION_ACCESS_VIOLATION :
  861. HandleErrorFrame(216,frame);
  862. { EXCEPTION_BREAKPOINT = $80000003;
  863. EXCEPTION_DATATYPE_MISALIGNMENT = $80000002;
  864. EXCEPTION_SINGLE_STEP = $80000004; }
  865. EXCEPTION_ARRAY_BOUNDS_EXCEEDED :
  866. HandleErrorFrame(201,frame);
  867. { EXCEPTION_FLT_DENORMAL_OPERAND = $c000008d; }
  868. EXCEPTION_FLT_DIVIDE_BY_ZERO :
  869. HandleErrorFrame(200,frame);
  870. {EXCEPTION_FLT_INEXACT_RESULT = $c000008f;
  871. EXCEPTION_FLT_INVALID_OPERATION = $c0000090;}
  872. EXCEPTION_FLT_OVERFLOW :
  873. HandleErrorFrame(205,frame);
  874. EXCEPTION_FLT_STACK_CHECK :
  875. HandleErrorFrame(207,frame);
  876. { EXCEPTION_FLT_UNDERFLOW :
  877. HandleErrorFrame(206,frame); should be accepted as zero !! }
  878. EXCEPTION_INT_DIVIDE_BY_ZERO :
  879. HandleErrorFrame(200,frame);
  880. EXCEPTION_INT_OVERFLOW :
  881. HandleErrorFrame(215,frame);
  882. {EXCEPTION_INVALID_HANDLE = $c0000008;
  883. EXCEPTION_PRIV_INSTRUCTION = $c0000096;
  884. EXCEPTION_NONCONTINUABLE_EXCEPTION = $c0000025;
  885. EXCEPTION_NONCONTINUABLE = $1;}
  886. EXCEPTION_STACK_OVERFLOW :
  887. HandleErrorFrame(202,frame);
  888. {EXCEPTION_INVALID_DISPOSITION = $c0000026;}
  889. end;
  890. end;
  891. procedure install_exception_handlers;
  892. begin
  893. SetUnhandledExceptionFilter(@syswin32_i386_exception_handler);
  894. end;
  895. {$else not i386 (Processor specific !!)}
  896. procedure install_exception_handlers;
  897. begin
  898. end;
  899. {$endif Set_i386_Exception_handler}
  900. {****************************************************************************
  901. Error Message writing using messageboxes
  902. ****************************************************************************}
  903. function MessageBox(w1:longint;l1,l2:pointer;w2:longint):longint;
  904. external 'user32' name 'MessageBoxA';
  905. const
  906. ErrorBufferLength = 1024;
  907. var
  908. ErrorBuf : array[0..ErrorBufferLength] of char;
  909. ErrorLen : longint;
  910. Function ErrorWrite(Var F: TextRec): Integer;
  911. {
  912. An error message should always end with #13#10#13#10
  913. }
  914. var
  915. p : pchar;
  916. i : longint;
  917. Begin
  918. if F.BufPos>0 then
  919. begin
  920. if F.BufPos+ErrorLen>ErrorBufferLength then
  921. i:=ErrorBufferLength-ErrorLen
  922. else
  923. i:=F.BufPos;
  924. Move(F.BufPtr^,ErrorBuf[ErrorLen],i);
  925. inc(ErrorLen,i);
  926. ErrorBuf[ErrorLen]:=#0;
  927. end;
  928. if ErrorLen>3 then
  929. begin
  930. p:=@ErrorBuf[ErrorLen];
  931. for i:=1 to 4 do
  932. begin
  933. dec(p);
  934. if not(p^ in [#10,#13]) then
  935. break;
  936. end;
  937. end;
  938. if ErrorLen=ErrorBufferLength then
  939. i:=4;
  940. if (i=4) then
  941. begin
  942. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  943. ErrorLen:=0;
  944. end;
  945. F.BufPos:=0;
  946. ErrorWrite:=0;
  947. End;
  948. Function ErrorClose(Var F: TextRec): Integer;
  949. begin
  950. if ErrorLen>0 then
  951. begin
  952. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  953. ErrorLen:=0;
  954. end;
  955. ErrorLen:=0;
  956. ErrorClose:=0;
  957. end;
  958. Function ErrorOpen(Var F: TextRec): Integer;
  959. Begin
  960. TextRec(F).InOutFunc:=@ErrorWrite;
  961. TextRec(F).FlushFunc:=@ErrorWrite;
  962. TextRec(F).CloseFunc:=@ErrorClose;
  963. ErrorOpen:=0;
  964. End;
  965. procedure AssignError(Var T: Text);
  966. begin
  967. Assign(T,'');
  968. TextRec(T).OpenFunc:=@ErrorOpen;
  969. Rewrite(T);
  970. end;
  971. const
  972. Exe_entry_code : pointer = @Exe_entry;
  973. Dll_entry_code : pointer = @Dll_entry;
  974. begin
  975. { get some helpful informations }
  976. GetStartupInfo(@startupinfo);
  977. { some misc Win32 stuff }
  978. hprevinst:=0;
  979. if not IsLibrary then
  980. HInstance:=getmodulehandle(GetCommandFile);
  981. MainInstance:=HInstance;
  982. { No idea how to know this issue !! }
  983. IsMultithreaded:=false;
  984. cmdshow:=startupinfo.wshowwindow;
  985. { to test stack depth }
  986. loweststack:=maxlongint;
  987. { real test stack depth }
  988. { stacklimit := setupstack; }
  989. { Setup heap }
  990. InitHeap;
  991. InitExceptions;
  992. { Setup stdin, stdout and stderr, for GUI apps redirect stderr,stdout to be
  993. displayed in and messagebox }
  994. StdInputHandle:=longint(GetStdHandle(STD_INPUT_HANDLE));
  995. StdOutputHandle:=longint(GetStdHandle(STD_OUTPUT_HANDLE));
  996. StdErrorHandle:=longint(GetStdHandle(STD_ERROR_HANDLE));
  997. if not IsConsole then
  998. begin
  999. AssignError(stderr);
  1000. AssignError(stdout);
  1001. Assign(Output,'');
  1002. Assign(Input,'');
  1003. end
  1004. else
  1005. begin
  1006. OpenStdIO(Input,fmInput,StdInputHandle);
  1007. OpenStdIO(Output,fmOutput,StdOutputHandle);
  1008. OpenStdIO(StdOut,fmOutput,StdOutputHandle);
  1009. OpenStdIO(StdErr,fmOutput,StdErrorHandle);
  1010. end;
  1011. { Arguments }
  1012. setup_arguments;
  1013. { Reset IO Error }
  1014. InOutRes:=0;
  1015. { Reset internal error variable }
  1016. errno:=0;
  1017. end.
  1018. {
  1019. $Log$
  1020. Revision 1.60 2000-02-09 16:59:34 peter
  1021. * truncated log
  1022. Revision 1.59 2000/02/09 12:24:39 peter
  1023. * halt moved to system.inc
  1024. Revision 1.58 2000/01/20 23:38:02 peter
  1025. * support fm_inout as stdoutput for assign(f,'');rewrite(f,1); becuase
  1026. rewrite opens always with filemode 2
  1027. Revision 1.57 2000/01/18 09:03:04 pierre
  1028. * DLL crash fixed : ExitProcess can not be called in DLL system_exit
  1029. Problem : Halt or RunError code inside DLL will return to caller !!
  1030. * Changed the "if h<4 then" into "if do_isdevice(h) then " in do_close
  1031. to avoid closing of standard files
  1032. Revision 1.56 2000/01/16 23:05:03 peter
  1033. * fixed typo
  1034. Revision 1.55 2000/01/16 22:25:38 peter
  1035. * check handle for file closing
  1036. Revision 1.54 2000/01/07 16:41:52 daniel
  1037. * copyright 2000
  1038. Revision 1.53 2000/01/07 16:32:34 daniel
  1039. * copyright 2000 added
  1040. Revision 1.52 2000/01/06 23:40:36 peter
  1041. * fixed exitprocess call, it's now in system_exit and uses exitcode
  1042. Revision 1.51 1999/12/01 22:57:31 peter
  1043. * cmdline support
  1044. Revision 1.50 1999/11/20 00:16:44 pierre
  1045. + DLL Hooks for the four callings added
  1046. Revision 1.49 1999/11/18 22:19:57 pierre
  1047. * bug fix for web bug703 and 704
  1048. Revision 1.48 1999/11/09 22:34:00 pierre
  1049. * Check ErrorBuf at exit
  1050. + Win32StackTop
  1051. Revision 1.47 1999/10/26 12:25:51 peter
  1052. * report stderr,stdout to message box for errors
  1053. * close input,output when GUI app is made
  1054. Revision 1.46 1999/10/22 14:47:19 peter
  1055. * allocate an extra byte for argv[0]
  1056. Revision 1.45 1999/10/03 19:39:05 peter
  1057. * fixed argv[0] length
  1058. Revision 1.44 1999/09/10 15:40:35 peter
  1059. * fixed do_open flags to be > $100, becuase filemode can be upto 255
  1060. }