sysutils.pp 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 1999-2000 by Florian Klaempfl
  4. member of the Free Pascal development team
  5. Sysutils unit for OS/2
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. **********************************************************************}
  12. unit sysutils;
  13. interface
  14. {$MODE objfpc}
  15. {$MODESWITCH OUT}
  16. { force ansistrings }
  17. {$H+}
  18. {$modeswitch typehelpers}
  19. {$modeswitch advancedrecords}
  20. {$DEFINE HAS_SLEEP}
  21. {$DEFINE HAS_OSERROR}
  22. { used OS file system APIs use ansistring }
  23. {$define SYSUTILS_HAS_ANSISTR_FILEUTIL_IMPL}
  24. { OS has an ansistring/single byte environment variable API }
  25. {$define SYSUTILS_HAS_ANSISTR_ENVVAR_IMPL}
  26. { OS has an ansistring/single byte API for executing other processes }
  27. {$DEFINE EXECUTEPROCUNI}
  28. { Include platform independent interface part }
  29. {$i sysutilh.inc}
  30. implementation
  31. uses
  32. sysconst, DosCalls;
  33. type
  34. (* Necessary here due to a different definition of TDateTime in DosCalls. *)
  35. TDateTime = System.TDateTime;
  36. threadvar
  37. LastOSError: cardinal;
  38. {$DEFINE FPC_FEXPAND_UNC} (* UNC paths are supported *)
  39. {$DEFINE FPC_FEXPAND_DRIVES} (* Full paths begin with drive specification *)
  40. {$DEFINE FPC_FEXPAND_GETENV_PCHAR}
  41. {$DEFINE HAS_GETTICKCOUNT}
  42. {$DEFINE HAS_GETTICKCOUNT64}
  43. { Include platform independent implementation part }
  44. {$i sysutils.inc}
  45. {****************************************************************************
  46. File Functions
  47. ****************************************************************************}
  48. const
  49. ofRead = $0000; {Open for reading}
  50. ofWrite = $0001; {Open for writing}
  51. ofReadWrite = $0002; {Open for reading/writing}
  52. doDenyRW = $0010; {DenyAll (no sharing)}
  53. faCreateNew = $00010000; {Create if file does not exist}
  54. faOpenReplace = $00040000; {Truncate if file exists}
  55. faCreate = $00050000; {Create if file does not exist, truncate otherwise}
  56. FindResvdMask = $00003737 {Allowed bits for DosFindFirst parameter Attribute}
  57. and $000000FF; {combined with a mask for allowed attributes only}
  58. function FileOpen (const FileName: rawbytestring; Mode: integer): THandle;
  59. Var
  60. SystemFileName: RawByteString;
  61. Handle: THandle;
  62. Rc, Action: cardinal;
  63. begin
  64. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  65. (* DenyReadWrite if sharing not specified. *)
  66. if (Mode and 112 = 0) or (Mode and 112 > 64) then
  67. Mode := Mode or doDenyRW;
  68. Rc:=Sys_DosOpenL(PChar (SystemFileName), Handle, Action, 0, 0, 1, Mode, nil);
  69. If Rc=0 then
  70. FileOpen:=Handle
  71. else
  72. begin
  73. FileOpen:=feInvalidHandle; //FileOpen:=-RC;
  74. //should return feInvalidHandle(=-1) if fail, other negative returned value are no more errors
  75. OSErrorWatch (RC);
  76. end;
  77. end;
  78. function FileCreate (const FileName: RawByteString): THandle;
  79. begin
  80. FileCreate := FileCreate (FileName, doDenyRW, 777); (* Sharing to DenyAll *)
  81. end;
  82. function FileCreate (const FileName: RawByteString; Rights: integer): THandle;
  83. begin
  84. FileCreate := FileCreate (FileName, doDenyRW, Rights);
  85. (* Sharing to DenyAll *)
  86. end;
  87. function FileCreate (const FileName: RawByteString; ShareMode: integer;
  88. Rights: integer): THandle;
  89. var
  90. SystemFileName: RawByteString;
  91. Handle: THandle;
  92. RC, Action: cardinal;
  93. begin
  94. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  95. ShareMode := ShareMode and 112;
  96. (* Sharing to DenyAll as default in case of values not allowed by OS/2. *)
  97. if (ShareMode = 0) or (ShareMode > 64) then
  98. ShareMode := doDenyRW;
  99. RC := Sys_DosOpenL (PChar (SystemFileName), Handle, Action, 0, 0, $12,
  100. faCreate or ofReadWrite or ShareMode, nil);
  101. if RC = 0 then
  102. FileCreate := Handle
  103. else
  104. begin
  105. FileCreate := feInvalidHandle;
  106. OSErrorWatch (RC);
  107. end;
  108. End;
  109. function FileRead (Handle: THandle; Out Buffer; Count: longint): longint;
  110. Var
  111. T: cardinal;
  112. RC: cardinal;
  113. begin
  114. RC := DosRead (Handle, Buffer, Count, T);
  115. if RC = 0 then
  116. FileRead := longint (T)
  117. else
  118. begin
  119. FileRead := -1;
  120. OSErrorWatch (RC);
  121. end;
  122. end;
  123. function FileWrite (Handle: THandle; const Buffer; Count: longint): longint;
  124. Var
  125. T: cardinal;
  126. RC: cardinal;
  127. begin
  128. RC := DosWrite (Handle, Buffer, Count, T);
  129. if RC = 0 then
  130. FileWrite := longint (T)
  131. else
  132. begin
  133. FileWrite := -1;
  134. OSErrorWatch (RC);
  135. end;
  136. end;
  137. function FileSeek (Handle: THandle; FOffset, Origin: longint): longint;
  138. var
  139. NPos: int64;
  140. RC: cardinal;
  141. begin
  142. RC := Sys_DosSetFilePtrL (Handle, FOffset, Origin, NPos);
  143. if (RC = 0) and (NPos < high (longint)) then
  144. FileSeek:= longint (NPos)
  145. else
  146. begin
  147. FileSeek:=-1;
  148. OSErrorWatch (RC);
  149. end;
  150. end;
  151. function FileSeek (Handle: THandle; FOffset: Int64; Origin: Longint): Int64;
  152. var
  153. NPos: int64;
  154. RC: cardinal;
  155. begin
  156. RC := Sys_DosSetFilePtrL (Handle, FOffset, Origin, NPos);
  157. if RC = 0 then
  158. FileSeek:= NPos
  159. else
  160. begin
  161. FileSeek:=-1;
  162. OSErrorWatch (RC);
  163. end;
  164. end;
  165. procedure FileClose (Handle: THandle);
  166. var
  167. RC: cardinal;
  168. begin
  169. RC := DosClose (Handle);
  170. if RC <> 0 then
  171. OSErrorWatch (RC);
  172. end;
  173. function FileTruncate (Handle: THandle; Size: Int64): boolean;
  174. var
  175. RC: cardinal;
  176. begin
  177. RC := Sys_DosSetFileSizeL(Handle, Size);
  178. FileTruncate := RC = 0;
  179. if RC = 0 then
  180. FileSeek(Handle, 0, 2)
  181. else
  182. OSErrorWatch (RC);
  183. end;
  184. function FileAge (const FileName: RawByteString): longint;
  185. var Handle: longint;
  186. begin
  187. Handle := FileOpen (FileName, 0);
  188. if Handle <> -1 then
  189. begin
  190. Result := FileGetDate (Handle);
  191. FileClose (Handle);
  192. end
  193. else
  194. Result := -1;
  195. end;
  196. function FileGetSymLinkTarget(const FileName: RawByteString; out SymLinkRec: TRawbyteSymLinkRec): Boolean;
  197. begin
  198. Result := False;
  199. end;
  200. function FileExists (const FileName: RawByteString; FollowLink : Boolean): boolean;
  201. var
  202. L: longint;
  203. begin
  204. { no need to convert to DefaultFileSystemEncoding, FileGetAttr will do that }
  205. if FileName = '' then
  206. Result := false
  207. else
  208. begin
  209. L := FileGetAttr (FileName);
  210. Result := (L >= 0) and (L and (faDirectory or faVolumeID) = 0);
  211. (* Neither VolumeIDs nor directories are files. *)
  212. end;
  213. end;
  214. type TRec = record
  215. T, D: word;
  216. end;
  217. PSearchRec = ^TSearchRec;
  218. Function InternalFindFirst (Const Path : RawByteString; Attr : Longint; out Rslt : TAbstractSearchRec; var Name: RawByteString) : Longint;
  219. var SR: PSearchRec;
  220. FStat: PFileFindBuf3L;
  221. Count: cardinal;
  222. Err: cardinal;
  223. I: cardinal;
  224. SystemEncodedPath: RawByteString;
  225. begin
  226. SystemEncodedPath := ToSingleByteFileSystemEncodedFileName(Path);
  227. New (FStat);
  228. Rslt.FindHandle := THandle ($FFFFFFFF);
  229. Count := 1;
  230. if FSApi64 then
  231. Err := DosFindFirst (PChar (SystemEncodedPath), Rslt.FindHandle,
  232. Attr and FindResvdMask, FStat, SizeOf (FStat^), Count, ilStandardL)
  233. else
  234. Err := DosFindFirst (PChar (SystemEncodedPath), Rslt.FindHandle,
  235. Attr and FindResvdMask, FStat, SizeOf (FStat^), Count, ilStandard);
  236. if Err <> 0 then
  237. OSErrorWatch (Err)
  238. else if Count = 0 then
  239. Err := 18;
  240. InternalFindFirst := -Err;
  241. if Err = 0 then
  242. begin
  243. Rslt.ExcludeAttr := 0;
  244. TRec (Rslt.Time).T := FStat^.TimeLastWrite;
  245. TRec (Rslt.Time).D := FStat^.DateLastWrite;
  246. if FSApi64 then
  247. begin
  248. Rslt.Size := FStat^.FileSize;
  249. Name := FStat^.Name;
  250. Rslt.Attr := FStat^.AttrFile;
  251. end
  252. else
  253. begin
  254. Rslt.Size := PFileFindBuf3 (FStat)^.FileSize;
  255. Name := PFileFindBuf3 (FStat)^.Name;
  256. Rslt.Attr := PFileFindBuf3 (FStat)^.AttrFile;
  257. end;
  258. SetCodePage (Name, DefaultFileSystemCodePage, false);
  259. end
  260. else
  261. InternalFindClose(Rslt.FindHandle);
  262. Dispose (FStat);
  263. end;
  264. Function InternalFindNext (var Rslt : TAbstractSearchRec; var Name : RawByteString) : Longint;
  265. var
  266. SR: PSearchRec;
  267. FStat: PFileFindBuf3L;
  268. Count: cardinal;
  269. Err: cardinal;
  270. begin
  271. New (FStat);
  272. Count := 1;
  273. Err := DosFindNext (Rslt.FindHandle, FStat, SizeOf (FStat^), Count);
  274. if Err <> 0 then
  275. OSErrorWatch (Err)
  276. else if Count = 0 then
  277. Err := 18;
  278. InternalFindNext := -Err;
  279. if Err = 0 then
  280. begin
  281. Rslt.ExcludeAttr := 0;
  282. TRec (Rslt.Time).T := FStat^.TimeLastWrite;
  283. TRec (Rslt.Time).D := FStat^.DateLastWrite;
  284. if FSApi64 then
  285. begin
  286. Rslt.Size := FStat^.FileSize;
  287. Name := FStat^.Name;
  288. Rslt.Attr := FStat^.AttrFile;
  289. end
  290. else
  291. begin
  292. Rslt.Size := PFileFindBuf3 (FStat)^.FileSize;
  293. Name := PFileFindBuf3 (FStat)^.Name;
  294. Rslt.Attr := PFileFindBuf3 (FStat)^.AttrFile;
  295. end;
  296. SetCodePage (Name, DefaultFileSystemCodePage, false);
  297. end;
  298. Dispose (FStat);
  299. end;
  300. Procedure InternalFindClose(var Handle: THandle);
  301. var
  302. SR: PSearchRec;
  303. RC: cardinal;
  304. begin
  305. RC := DosFindClose (Handle);
  306. Handle := 0;
  307. if RC <> 0 then
  308. OSErrorWatch (RC);
  309. end;
  310. function FileGetDate (Handle: THandle): longint;
  311. var
  312. FStat: TFileStatus3;
  313. Time: Longint;
  314. RC: cardinal;
  315. begin
  316. RC := DosQueryFileInfo(Handle, ilStandard, @FStat, SizeOf(FStat));
  317. if RC = 0 then
  318. begin
  319. Time := FStat.TimeLastWrite + longint (FStat.DateLastWrite) shl 16;
  320. if Time = 0 then
  321. Time := FStat.TimeCreation + longint (FStat.DateCreation) shl 16;
  322. end else
  323. begin
  324. Time:=0;
  325. OSErrorWatch (RC);
  326. end;
  327. FileGetDate:=Time;
  328. end;
  329. function FileSetDate (Handle: THandle; Age: longint): longint;
  330. var
  331. FStat: PFileStatus3;
  332. RC: cardinal;
  333. begin
  334. New (FStat);
  335. RC := DosQueryFileInfo (Handle, ilStandard, FStat, SizeOf (FStat^));
  336. if RC <> 0 then
  337. begin
  338. FileSetDate := -1;
  339. OSErrorWatch (RC);
  340. end
  341. else
  342. begin
  343. FStat^.DateLastAccess := Hi (Age);
  344. FStat^.DateLastWrite := Hi (Age);
  345. FStat^.TimeLastAccess := Lo (Age);
  346. FStat^.TimeLastWrite := Lo (Age);
  347. RC := DosSetFileInfo (Handle, ilStandard, FStat, SizeOf (FStat^));
  348. if RC <> 0 then
  349. begin
  350. FileSetDate := -1;
  351. OSErrorWatch (RC);
  352. end
  353. else
  354. FileSetDate := 0;
  355. end;
  356. Dispose (FStat);
  357. end;
  358. function FileGetAttr (const FileName: RawByteString): longint;
  359. var
  360. FS: PFileStatus3;
  361. SystemFileName: RawByteString;
  362. RC: cardinal;
  363. begin
  364. SystemFileName:=ToSingleByteFileSystemEncodedFileName(Filename);
  365. New(FS);
  366. RC := DosQueryPathInfo(PChar (SystemFileName), ilStandard, FS, SizeOf(FS^));
  367. if RC = 0 then
  368. Result := FS^.AttrFile
  369. else
  370. begin
  371. Result := - longint (RC);
  372. OSErrorWatch (RC);
  373. end;
  374. Dispose(FS);
  375. end;
  376. function FileSetAttr (const Filename: RawByteString; Attr: longint): longint;
  377. Var
  378. FS: PFileStatus3;
  379. SystemFileName: RawByteString;
  380. RC: cardinal;
  381. Begin
  382. SystemFileName:=ToSingleByteFileSystemEncodedFileName(Filename);
  383. New(FS);
  384. RC := DosQueryPathInfo (PChar (SystemFileName), ilStandard, FS, SizeOf (FS^));
  385. if RC = 0 then
  386. begin
  387. FS^.AttrFile:=Attr;
  388. RC := DosSetPathInfo(PChar (SystemFileName), ilStandard, FS, SizeOf(FS^), 0);
  389. if RC <> 0 then
  390. OSErrorWatch (RC);
  391. end
  392. else
  393. OSErrorWatch (RC);
  394. Result := - longint (RC);
  395. Dispose(FS);
  396. end;
  397. function DeleteFile (const FileName: RawByteString): boolean;
  398. var
  399. SystemFileName: RawByteString;
  400. RC: cardinal;
  401. Begin
  402. SystemFileName:=ToSingleByteFileSystemEncodedFileName(Filename);
  403. RC := DosDelete (PChar (SystemFileName));
  404. if RC <> 0 then
  405. begin
  406. Result := false;
  407. OSErrorWatch (RC);
  408. end
  409. else
  410. Result := true;
  411. End;
  412. function RenameFile (const OldName, NewName: RawByteString): boolean;
  413. var
  414. OldSystemFileName, NewSystemFileName: RawByteString;
  415. RC: cardinal;
  416. Begin
  417. OldSystemFileName:=ToSingleByteFileSystemEncodedFileName(OldName);
  418. NewSystemFileName:=ToSingleByteFileSystemEncodedFileName(NewName);
  419. RC := DosMove (PChar (OldSystemFileName), PChar (NewSystemFileName));
  420. if RC <> 0 then
  421. begin
  422. Result := false;
  423. OSErrorWatch (RC);
  424. end
  425. else
  426. Result := true;
  427. End;
  428. {****************************************************************************
  429. Disk Functions
  430. ****************************************************************************}
  431. function DiskFree (Drive: byte): int64;
  432. var FI: TFSinfo;
  433. RC: cardinal;
  434. begin
  435. {In OS/2, we use the filesystem information.}
  436. RC := DosQueryFSInfo (Drive, 1, FI, SizeOf (FI));
  437. if RC = 0 then
  438. DiskFree := int64 (FI.Free_Clusters) *
  439. int64 (FI.Sectors_Per_Cluster) * int64 (FI.Bytes_Per_Sector)
  440. else
  441. begin
  442. DiskFree := -1;
  443. OSErrorWatch (RC);
  444. end;
  445. end;
  446. function DiskSize (Drive: byte): int64;
  447. var FI: TFSinfo;
  448. RC: cardinal;
  449. begin
  450. {In OS/2, we use the filesystem information.}
  451. RC := DosQueryFSinfo (Drive, 1, FI, SizeOf (FI));
  452. if RC = 0 then
  453. DiskSize := int64 (FI.Total_Clusters) *
  454. int64 (FI.Sectors_Per_Cluster) * int64 (FI.Bytes_Per_Sector)
  455. else
  456. begin
  457. DiskSize := -1;
  458. OSErrorWatch (RC);
  459. end;
  460. end;
  461. function DirectoryExists (const Directory: RawByteString; FollowLink : Boolean): boolean;
  462. var
  463. L: longint;
  464. begin
  465. { no need to convert to DefaultFileSystemEncoding, FileGetAttr will do that }
  466. if Directory = '' then
  467. Result := false
  468. else
  469. begin
  470. if ((Length (Directory) = 2) or
  471. (Length (Directory) = 3) and
  472. (Directory [3] in AllowDirectorySeparators)) and
  473. (Directory [2] in AllowDriveSeparators) and
  474. (UpCase (Directory [1]) in ['A'..'Z']) then
  475. (* Checking attributes for 'x:' is not possible but for 'x:.' it is. *)
  476. L := FileGetAttr (Directory + '.')
  477. else if (Directory [Length (Directory)] in AllowDirectorySeparators) and
  478. (Length (Directory) > 1) and
  479. (* Do not remove '\' in '\\' (invalid path, possibly broken UNC path). *)
  480. not (Directory [Length (Directory) - 1] in AllowDirectorySeparators) then
  481. L := FileGetAttr (Copy (Directory, 1, Length (Directory) - 1))
  482. else
  483. L := FileGetAttr (Directory);
  484. Result := (L > 0) and (L and faDirectory = faDirectory);
  485. end;
  486. end;
  487. {****************************************************************************
  488. Time Functions
  489. ****************************************************************************}
  490. procedure GetLocalTime (var SystemTime: TSystemTime);
  491. var
  492. DT: DosCalls.TDateTime;
  493. begin
  494. DosGetDateTime(DT);
  495. with SystemTime do
  496. begin
  497. Year:=DT.Year;
  498. Month:=DT.Month;
  499. Day:=DT.Day;
  500. Hour:=DT.Hour;
  501. Minute:=DT.Minute;
  502. Second:=DT.Second;
  503. MilliSecond:=DT.Sec100;
  504. end;
  505. end;
  506. {****************************************************************************
  507. Misc Functions
  508. ****************************************************************************}
  509. procedure sysbeep;
  510. begin
  511. DosBeep (800, 250);
  512. end;
  513. {****************************************************************************
  514. Locale Functions
  515. ****************************************************************************}
  516. var
  517. Country: TCountryCode;
  518. CtryInfo: TCountryInfo;
  519. procedure InitAnsi;
  520. var
  521. I: byte;
  522. RC: cardinal;
  523. begin
  524. for I := 0 to 255 do
  525. UpperCaseTable [I] := Chr (I);
  526. Move (UpperCaseTable, LowerCaseTable, SizeOf (UpperCaseTable));
  527. FillChar (Country, SizeOf (Country), 0);
  528. DosMapCase (SizeOf (UpperCaseTable), Country, @UpperCaseTable);
  529. for I := 0 to 255 do
  530. if UpperCaseTable [I] <> Chr (I) then
  531. LowerCaseTable [Ord (UpperCaseTable [I])] := Chr (I);
  532. end;
  533. procedure InitInternational;
  534. var
  535. Size: cardinal;
  536. RC: cardinal;
  537. begin
  538. Size := 0;
  539. FillChar (Country, SizeOf (Country), 0);
  540. FillChar (CtryInfo, SizeOf (CtryInfo), 0);
  541. RC := DosQueryCtryInfo (SizeOf (CtryInfo), Country, CtryInfo, Size);
  542. if RC = 0 then
  543. begin
  544. DateSeparator := CtryInfo.DateSeparator;
  545. case CtryInfo.DateFormat of
  546. 1: begin
  547. ShortDateFormat := 'd/m/y';
  548. LongDateFormat := 'dd" "mmmm" "yyyy';
  549. end;
  550. 2: begin
  551. ShortDateFormat := 'y/m/d';
  552. LongDateFormat := 'yyyy" "mmmm" "dd';
  553. end;
  554. 3: begin
  555. ShortDateFormat := 'm/d/y';
  556. LongDateFormat := 'mmmm" "dd" "yyyy';
  557. end;
  558. end;
  559. TimeSeparator := CtryInfo.TimeSeparator;
  560. DecimalSeparator := CtryInfo.DecimalSeparator;
  561. ThousandSeparator := CtryInfo.ThousandSeparator;
  562. CurrencyFormat := CtryInfo.CurrencyFormat;
  563. CurrencyString := PChar (CtryInfo.CurrencyUnit);
  564. end
  565. else
  566. OSErrorWatch (RC);
  567. InitAnsi;
  568. InitInternationalGeneric;
  569. end;
  570. function SysErrorMessage(ErrorCode: Integer): String;
  571. const
  572. SysMsgFile: array [0..10] of char = 'OSO001.MSG'#0;
  573. var
  574. OutBuf: array [0..999] of char;
  575. RetMsgSize: cardinal;
  576. RC: cardinal;
  577. begin
  578. RC := DosGetMessage (nil, 0, @OutBuf [0], SizeOf (OutBuf),
  579. ErrorCode, @SysMsgFile [0], RetMsgSize);
  580. if RC = 0 then
  581. begin
  582. SetLength (Result, RetMsgSize);
  583. Move (OutBuf [0], Result [1], RetMsgSize);
  584. end
  585. else
  586. begin
  587. Result:=Format(SUnknownErrorCode,[ErrorCode]);
  588. OSErrorWatch (RC);
  589. end;
  590. end;
  591. {****************************************************************************
  592. OS Utils
  593. ****************************************************************************}
  594. function GetEnvPChar (EnvVar: shortstring): PChar;
  595. (* The assembler version is more than three times as fast as Pascal. *)
  596. var
  597. P: PChar;
  598. begin
  599. EnvVar := UpCase (EnvVar);
  600. {$ASMMODE INTEL}
  601. asm
  602. cld
  603. mov edi, Environment
  604. lea esi, EnvVar
  605. xor eax, eax
  606. lodsb
  607. @NewVar:
  608. cmp byte ptr [edi], 0
  609. jz @Stop
  610. push eax { eax contains length of searched variable name }
  611. push esi { esi points to the beginning of the variable name }
  612. mov ecx, -1 { our character ('=' - see below) _must_ be found }
  613. mov edx, edi { pointer to beginning of variable name saved in edx }
  614. mov al, '=' { searching until '=' (end of variable name) }
  615. repne
  616. scasb { scan until '=' not found }
  617. neg ecx { what was the name length? }
  618. dec ecx { corrected }
  619. dec ecx { exclude the '=' character }
  620. pop esi { restore pointer to beginning of variable name }
  621. pop eax { restore length of searched variable name }
  622. push eax { and save both of them again for later use }
  623. push esi
  624. cmp ecx, eax { compare length of searched variable name with name }
  625. jnz @NotEqual { ... of currently found variable, jump if different }
  626. xchg edx, edi { pointer to current variable name restored in edi }
  627. repe
  628. cmpsb { compare till the end of variable name }
  629. xchg edx, edi { pointer to beginning of variable contents in edi }
  630. jz @Equal { finish if they're equal }
  631. @NotEqual:
  632. xor eax, eax { look for 00h }
  633. mov ecx, -1 { it _must_ be found }
  634. repne
  635. scasb { scan until found }
  636. pop esi { restore pointer to beginning of variable name }
  637. pop eax { restore length of searched variable name }
  638. jmp @NewVar { ... or continue with new variable otherwise }
  639. @Stop:
  640. xor eax, eax
  641. mov P, eax { Not found - return nil }
  642. jmp @End
  643. @Equal:
  644. pop esi { restore the stack position }
  645. pop eax
  646. mov P, edi { place pointer to variable contents in P }
  647. @End:
  648. end ['eax','ecx','edx','esi','edi'];
  649. GetEnvPChar := P;
  650. end;
  651. {$ASMMODE ATT}
  652. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  653. begin
  654. GetEnvironmentVariable := GetEnvPChar (EnvVar);
  655. end;
  656. Function GetEnvironmentVariableCount : Integer;
  657. begin
  658. (* Result:=FPCCountEnvVar(EnvP); - the amount is already known... *)
  659. GetEnvironmentVariableCount := EnvC;
  660. end;
  661. Function GetEnvironmentString(Index : Integer) : {$ifdef FPC_RTL_UNICODE}UnicodeString{$else}AnsiString{$endif};
  662. begin
  663. Result:=FPCGetEnvStrFromP (EnvP, Index);
  664. end;
  665. procedure Sleep (Milliseconds: cardinal);
  666. begin
  667. DosSleep (Milliseconds);
  668. end;
  669. function SysTimerTick: QWord;
  670. var
  671. L: cardinal;
  672. begin
  673. DosQuerySysInfo (svMsCount, svMsCount, L, 4);
  674. SysTimerTick := L;
  675. end;
  676. function ExecuteProcess (const Path: RawByteString;
  677. const ComLine: RawByteString;Flags:TExecuteFlags=[]): integer;
  678. var
  679. E: EOSError;
  680. CommandLine: RawByteString;
  681. Args0, Args: DosCalls.PByteArray;
  682. ObjNameBuf: PChar;
  683. ArgSize: word;
  684. Res: TResultCodes;
  685. ObjName: shortstring;
  686. RC: cardinal;
  687. ExecAppType: cardinal;
  688. MaxArgsSize: PtrUInt; (* Amount of memory reserved for arguments in bytes. *)
  689. MaxArgsSizeInc: word;
  690. const
  691. ObjBufSize = 512;
  692. function StartSession: cardinal;
  693. var
  694. HQ: THandle;
  695. SPID, STID, QName: shortstring;
  696. SID, PID: cardinal;
  697. SD: TStartData;
  698. RD: TRequestData;
  699. PCI: PChildInfo;
  700. CISize: cardinal;
  701. Prio: byte;
  702. begin
  703. Result := $FFFFFFFF;
  704. FillChar (SD, SizeOf (SD), 0);
  705. SD.Length := SizeOf (SD);
  706. SD.Related := ssf_Related_Child;
  707. if FileExists (Path) then
  708. (* Full path necessary for starting different executable files from current *)
  709. (* directory. *)
  710. CommandLine := ExpandFileName (Path)
  711. else
  712. CommandLine := Path;
  713. SD.PgmName := PChar (CommandLine);
  714. if ComLine <> '' then
  715. SD.PgmInputs := PChar (ComLine);
  716. if ExecInheritsHandles in Flags then
  717. SD.InheritOpt := ssf_InhertOpt_Parent;
  718. Str (GetProcessID, SPID);
  719. Str (ThreadID, STID);
  720. QName := '\QUEUES\FPC_ExecuteProcess_p' + SPID + 't' + STID + '.QUE'#0;
  721. SD.TermQ := @QName [1];
  722. SD.ObjectBuffer := ObjNameBuf;
  723. SD.ObjectBuffLen := ObjBufSize;
  724. RC := DosCreateQueue (HQ, quFIFO or quConvert_Address, @QName [1]);
  725. if RC <> 0 then
  726. begin
  727. Move (QName [1], ObjNameBuf^, Length (QName));
  728. OSErrorWatch (RC);
  729. end
  730. else
  731. begin
  732. RC := DosStartSession (SD, SID, PID);
  733. if (RC = 0) or (RC = 457) then
  734. begin
  735. RC := DosReadQueue (HQ, RD, CISize, PCI, 0, 0, Prio, 0);
  736. if RC = 0 then
  737. begin
  738. Result := PCI^.Return;
  739. RC := DosCloseQueue (HQ);
  740. if RC <> 0 then
  741. OSErrorWatch (RC);
  742. RC := DosFreeMem (PCI);
  743. if RC <> 0 then
  744. OSErrorWatch (RC);
  745. FreeMem (ObjNameBuf, ObjBufSize);
  746. end
  747. else
  748. begin
  749. OSErrorWatch (RC);
  750. RC := DosCloseQueue (HQ);
  751. OSErrorWatch (RC);
  752. end;
  753. end
  754. else
  755. begin
  756. OSErrorWatch (RC);
  757. RC := DosCloseQueue (HQ);
  758. if RC <> 0 then
  759. OSErrorWatch (RC);
  760. end;
  761. end;
  762. end;
  763. begin
  764. Result := integer ($FFFFFFFF);
  765. ObjName := '';
  766. GetMem (ObjNameBuf, ObjBufSize);
  767. FillChar (ObjNameBuf^, ObjBufSize, 0);
  768. RC := DosQueryAppType (PChar (Path), ExecAppType);
  769. if RC <> 0 then
  770. begin
  771. OSErrorWatch (RC);
  772. if (RC = 190) or (RC = 191) then
  773. Result := StartSession;
  774. end
  775. else
  776. begin
  777. if (ApplicationType and 3 = ExecAppType and 3) then
  778. (* DosExecPgm should work... *)
  779. begin
  780. MaxArgsSize := Length (ComLine) + Length (Path) + 256; (* More than enough *)
  781. if MaxArgsSize > high (word) then
  782. Exit;
  783. if ComLine = '' then
  784. begin
  785. Args0 := nil;
  786. Args := nil;
  787. end
  788. else
  789. begin
  790. GetMem (Args0, MaxArgsSize);
  791. Args := Args0;
  792. (* Work around a bug in OS/2 - argument to DosExecPgm *)
  793. (* should not cross 64K boundary. *)
  794. while ((PtrUInt (Args) + MaxArgsSize) and $FFFF) < MaxArgsSize do
  795. begin
  796. MaxArgsSizeInc := MaxArgsSize -
  797. ((PtrUInt (Args) + MaxArgsSize) and $FFFF);
  798. Inc (MaxArgsSize, MaxArgsSizeInc);
  799. if MaxArgsSize > high (word) then
  800. Exit;
  801. ReallocMem (Args0, MaxArgsSize);
  802. Inc (pointer (Args), MaxArgsSizeInc);
  803. end;
  804. ArgSize := 0;
  805. Move (Path [1], Args^ [ArgSize], Length (Path));
  806. Inc (ArgSize, Length (Path));
  807. Args^ [ArgSize] := 0;
  808. Inc (ArgSize);
  809. {Now do the real arguments.}
  810. Move (ComLine [1], Args^ [ArgSize], Length (ComLine));
  811. Inc (ArgSize, Length (ComLine));
  812. Args^ [ArgSize] := 0;
  813. Inc (ArgSize);
  814. Args^ [ArgSize] := 0;
  815. end;
  816. Res.ExitCode := $FFFFFFFF;
  817. RC := DosExecPgm (ObjNameBuf, ObjBufSize, 0, Args, nil, Res,
  818. PChar (Path));
  819. if RC <> 0 then
  820. OSErrorWatch (RC);
  821. if Args0 <> nil then
  822. FreeMem (Args0, MaxArgsSize);
  823. if RC = 0 then
  824. begin
  825. Result := Res.ExitCode;
  826. FreeMem (ObjNameBuf, ObjBufSize);
  827. end
  828. end
  829. end;
  830. if RC <> 0 then
  831. begin
  832. ObjName := StrPas (ObjNameBuf);
  833. FreeMem (ObjNameBuf, ObjBufSize);
  834. if ComLine = '' then
  835. CommandLine := Path
  836. else
  837. CommandLine := Path + ' ' + ComLine;
  838. if ObjName = '' then
  839. E := EOSError.CreateFmt (SExecuteProcessFailed, [CommandLine, RC])
  840. else
  841. E := EOSError.CreateFmt (SExecuteProcessFailed + ' (' + ObjName + ')', [CommandLine, RC]);
  842. E.ErrorCode := Result;
  843. raise E;
  844. end;
  845. end;
  846. function ExecuteProcess (const Path: RawByteString;
  847. const ComLine: array of RawByteString;Flags:TExecuteFlags=[]): integer;
  848. var
  849. CommandLine: AnsiString;
  850. I: integer;
  851. begin
  852. Commandline := '';
  853. for I := 0 to High (ComLine) do
  854. if Pos (' ', ComLine [I]) <> 0 then
  855. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  856. else
  857. CommandLine := CommandLine + ' ' + Comline [I];
  858. ExecuteProcess := ExecuteProcess (Path, CommandLine);
  859. end;
  860. function GetTickCount: LongWord;
  861. var
  862. L: cardinal;
  863. begin
  864. DosQuerySysInfo (svMsCount, svMsCount, L, 4);
  865. GetTickCount := L;
  866. end;
  867. function GetTickCount64: QWord;
  868. var
  869. Freq2: cardinal;
  870. T: QWord;
  871. begin
  872. DosTmrQueryFreq (Freq2);
  873. DosTmrQueryTime (T);
  874. GetTickCount64 := T div (QWord (Freq2) div 1000);
  875. {$NOTE GetTickCount64 takes 20 microseconds on 1GHz CPU, GetTickCount not measurable}
  876. end;
  877. const
  878. OrigOSErrorWatch: TOSErrorWatch = nil;
  879. procedure TrackLastOSError (Error: cardinal);
  880. begin
  881. LastOSError := Error;
  882. OrigOSErrorWatch (Error);
  883. end;
  884. function GetLastOSError: Integer;
  885. begin
  886. GetLastOSError := Integer (LastOSError);
  887. end;
  888. {****************************************************************************
  889. Initialization code
  890. ****************************************************************************}
  891. Initialization
  892. InitExceptions; { Initialize exceptions. OS independent }
  893. InitInternational; { Initialize internationalization settings }
  894. OnBeep:=@SysBeep;
  895. LastOSError := 0;
  896. OrigOSErrorWatch := TOSErrorWatch (SetOSErrorTracking (@TrackLastOSError));
  897. Finalization
  898. DoneExceptions;
  899. end.