sysutils.pp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 2014 by Free Pascal development team
  4. Sysutils unit for AmigaOS & clones
  5. Based on Amiga 1.x version by Carl Eric Codere, and other
  6. parts of the RTL
  7. AmigaOS and MorphOS support by Karoly Balogh
  8. AROS support by Marcus Sackrow
  9. See the file COPYING.FPC, included in this distribution,
  10. for details about the copyright.
  11. This program is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  14. **********************************************************************}
  15. unit sysutils;
  16. interface
  17. {$MODE objfpc}
  18. {$MODESWITCH OUT}
  19. {$IFDEF UNICODERTL}
  20. {$MODESWITCH UNICODESTRINGS}
  21. {$ELSE}
  22. {$H+}
  23. {$ENDIF}
  24. {$modeswitch typehelpers}
  25. {$modeswitch advancedrecords}
  26. {$DEFINE OS_FILESETDATEBYNAME}
  27. {$DEFINE HAS_SLEEP}
  28. {$DEFINE HAS_OSERROR}
  29. {$DEFINE HAS_TEMPDIR}
  30. {OS has only 1 byte version for ExecuteProcess}
  31. {$define executeprocuni}
  32. { used OS file system APIs use ansistring }
  33. {$define SYSUTILS_HAS_ANSISTR_FILEUTIL_IMPL}
  34. { OS has an ansistring/single byte environment variable API }
  35. {$define SYSUTILS_HAS_ANSISTR_ENVVAR_IMPL}
  36. { Include platform independent interface part }
  37. {$i sysutilh.inc}
  38. { Platform dependent calls }
  39. function DeviceByIdx(Idx: Integer): string;
  40. function AddDisk(Const Path: string): Integer;
  41. function RefreshDeviceList: Integer;
  42. function DiskSize(Drive: AnsiString): Int64;
  43. function DiskFree(Drive: AnsiString): Int64;
  44. implementation
  45. uses
  46. dos, sysconst;
  47. {$DEFINE FPC_FEXPAND_VOLUMES} (* Full paths begin with drive specification *)
  48. {$DEFINE FPC_FEXPAND_DRIVESEP_IS_ROOT}
  49. {$DEFINE FPC_FEXPAND_NO_DEFAULT_PATHS}
  50. {$DEFINE FPC_FEXPAND_DIRSEP_IS_UPDIR}
  51. { Include platform independent implementation part }
  52. {$i sysutils.inc}
  53. { * Include system specific includes * }
  54. {$include execd.inc}
  55. {$include execf.inc}
  56. {$include timerd.inc}
  57. {$include doslibd.inc}
  58. {$include doslibf.inc}
  59. {$include utilf.inc}
  60. {$ifdef cpum68k}
  61. {$if defined(amiga_v1_0_only) or defined(amiga_v1_2_only)}
  62. {$include legacyexech.inc}
  63. {$include legacydosh.inc}
  64. {$include legacyutilh.inc}
  65. {$endif}
  66. {$endif}
  67. { * Followings are implemented in the system unit! * }
  68. function PathConv(path: shortstring): shortstring; external name 'PATHCONV';
  69. function PathConv(path: RawByteString): RawByteString; external name 'PATHCONVRBS';
  70. procedure AddToList(var l: Pointer; h: THandle); external name 'ADDTOLIST';
  71. function RemoveFromList(var l: Pointer; h: THandle): boolean; external name 'REMOVEFROMLIST';
  72. function CheckInList(var l: Pointer; h: THandle): pointer; external name 'CHECKINLIST';
  73. var
  74. ASYS_FileList: Pointer; external name 'ASYS_FILELIST';
  75. function BADDR(bval: BPTR): Pointer; Inline;
  76. begin
  77. {$if defined(AROS)} // deactivated for now //and (not defined(AROS_BINCOMPAT))}
  78. BADDR := Pointer(bval);
  79. {$else}
  80. BADDR:=Pointer(bval Shl 2);
  81. {$endif}
  82. end;
  83. function BSTR2STRING(s : Pointer): PAnsiChar; Inline;
  84. begin
  85. {$if defined(AROS)} // deactivated for now //and (not defined(AROS_BINCOMPAT))}
  86. BSTR2STRING:=PAnsiChar(s);
  87. {$else}
  88. BSTR2STRING:=PAnsiChar(BADDR(PtrInt(s)))+1;
  89. {$endif}
  90. end;
  91. function BSTR2STRING(s : BPTR): PAnsiChar; Inline;
  92. begin
  93. {$if defined(AROS)} // deactivated for now //and (not defined(AROS_BINCOMPAT))}
  94. BSTR2STRING:=PAnsiChar(s);
  95. {$else}
  96. BSTR2STRING:=PAnsiChar(BADDR(s))+1;
  97. {$endif}
  98. end;
  99. function AmigaFileDateToDateTime(aDate: TDateStamp; out success: boolean): TDateTime;
  100. var
  101. tmpSecs: DWord;
  102. tmpDate: TDateTime;
  103. tmpTime: TDateTime;
  104. clockData: TClockData;
  105. begin
  106. with aDate do
  107. tmpSecs:=(ds_Days * (24 * 60 * 60)) + (ds_Minute * 60) + (ds_Tick div TICKS_PER_SECOND);
  108. Amiga2Date(tmpSecs,@clockData);
  109. {$HINT TODO: implement msec values, if possible}
  110. with clockData do begin
  111. success:=TryEncodeDate(year,month,mday,tmpDate) and
  112. TryEncodeTime(hour,min,sec,0,tmpTime);
  113. end;
  114. result:=ComposeDateTime(tmpDate,tmpTime);
  115. end;
  116. function DateTimeToAmigaDateStamp(dateTime: TDateTime): TDateStamp;
  117. var
  118. tmpSecs: DWord;
  119. clockData: TClockData;
  120. tmpMSec: Word;
  121. begin
  122. {$HINT TODO: implement msec values, if possible}
  123. with clockData do begin
  124. DecodeDate(dateTime,year,month,mday);
  125. DecodeTime(dateTime,hour,min,sec,tmpMSec);
  126. end;
  127. tmpSecs:=Date2Amiga(@clockData);
  128. with result do begin
  129. ds_Days:= tmpSecs div (24 * 60 * 60);
  130. ds_Minute:= (tmpSecs div 60) mod ds_Days;
  131. ds_Tick:= (((tmpSecs mod 60) mod ds_Minute) mod ds_Days) * TICKS_PER_SECOND;
  132. end;
  133. end;
  134. {****************************************************************************
  135. File Functions
  136. ****************************************************************************}
  137. {$I-}{ Required for correct usage of these routines }
  138. (****** non portable routines ******)
  139. function FileOpen(const FileName: rawbytestring; Mode: Integer): THandle;
  140. var
  141. SystemFileName: RawByteString;
  142. dosResult: THandle;
  143. begin
  144. SystemFileName:=PathConv(ToSingleByteFileSystemEncodedFileName(FileName));
  145. {$WARNING FIX ME! To do: FileOpen Access Modes}
  146. dosResult:=Open(PAnsiChar(SystemFileName),MODE_OLDFILE);
  147. if dosResult=0 then
  148. dosResult:=-1
  149. else
  150. AddToList(ASYS_fileList,dosResult);
  151. FileOpen:=dosResult;
  152. end;
  153. function FileGetDate(Handle: THandle) : Int64;
  154. var
  155. tmpFIB : PFileInfoBlock;
  156. tmpDateTime: TDateTime;
  157. validFile: boolean;
  158. begin
  159. validFile:=false;
  160. if (Handle <> 0) then begin
  161. new(tmpFIB);
  162. if ExamineFH(BPTR(Handle),tmpFIB) then begin
  163. tmpDateTime:=AmigaFileDateToDateTime(tmpFIB^.fib_Date,validFile);
  164. end;
  165. dispose(tmpFIB);
  166. end;
  167. if validFile then
  168. result:=DateTimeToFileDate(tmpDateTime)
  169. else
  170. result:=-1;
  171. end;
  172. function FileSetDate(Handle: THandle; Age: Int64) : LongInt;
  173. var
  174. tmpDateStamp: TDateStamp;
  175. tmpName: array[0..255] of AnsiChar;
  176. begin
  177. result:=0;
  178. if (Handle <> 0) then begin
  179. if NameFromFH(BPTR(Handle), @tmpName, 256) then begin
  180. tmpDateStamp:=DateTimeToAmigaDateStamp(FileDateToDateTime(Age));
  181. if not SetFileDate(@tmpName,@tmpDateStamp) then begin
  182. IoErr(); // dump the error code for now (TODO)
  183. result:=-1;
  184. end;
  185. end;
  186. end;
  187. end;
  188. function FileSetDate(const FileName: RawByteString; Age: Int64) : LongInt;
  189. var
  190. tmpDateStamp: TDateStamp;
  191. SystemFileName: RawByteString;
  192. begin
  193. result:=0;
  194. SystemFileName:=PathConv(ToSingleByteFileSystemEncodedFileName(FileName));
  195. tmpDateStamp:=DateTimeToAmigaDateStamp(FileDateToDateTime(Age));
  196. if not SetFileDate(PAnsiChar(SystemFileName),@tmpDateStamp) then begin
  197. IoErr(); // dump the error code for now (TODO)
  198. result:=-1;
  199. end;
  200. end;
  201. function FileCreate(const FileName: RawByteString) : THandle;
  202. var
  203. SystemFileName: RawByteString;
  204. dosResult: THandle;
  205. begin
  206. dosResult:=-1;
  207. { Open file in MODDE_READWRITE, then truncate it by hand rather than
  208. opening it in MODE_NEWFILE, because that returns an exclusive lock
  209. so some operations might fail with it (KB) }
  210. SystemFileName:=PathConv(ToSingleByteFileSystemEncodedFileName(FileName));
  211. dosResult:=Open(PAnsiChar(SystemFileName),MODE_READWRITE);
  212. if dosResult = 0 then exit;
  213. if SetFileSize(dosResult, 0, OFFSET_BEGINNING) = 0 then
  214. AddToList(ASYS_fileList,dosResult)
  215. else begin
  216. dosClose(dosResult);
  217. dosResult:=-1;
  218. end;
  219. FileCreate:=dosResult;
  220. end;
  221. function FileCreate(const FileName: RawByteString; Rights: integer): THandle;
  222. begin
  223. {$WARNING FIX ME! To do: FileCreate Access Modes}
  224. FileCreate:=FileCreate(FileName);
  225. end;
  226. function FileCreate(const FileName: RawByteString; ShareMode: integer; Rights : integer): THandle;
  227. begin
  228. {$WARNING FIX ME! To do: FileCreate Access Modes}
  229. FileCreate:=FileCreate(FileName);
  230. end;
  231. function FileRead(Handle: THandle; out Buffer; Count: LongInt): LongInt;
  232. begin
  233. FileRead:=-1;
  234. if (Count<=0) or (Handle=0) or (Handle=-1) then exit;
  235. FileRead:=dosRead(Handle,@Buffer,Count);
  236. end;
  237. function FileWrite(Handle: THandle; const Buffer; Count: LongInt): LongInt;
  238. begin
  239. FileWrite:=-1;
  240. if (Count<=0) or (Handle=0) or (Handle=-1) then exit;
  241. FileWrite:=dosWrite(Handle,@Buffer,Count);
  242. end;
  243. function FileSeek(Handle: THandle; FOffset, Origin: LongInt) : LongInt;
  244. var
  245. seekMode: LongInt;
  246. begin
  247. FileSeek:=-1;
  248. if (Handle=0) or (Handle=-1) then exit;
  249. case Origin of
  250. fsFromBeginning: seekMode:=OFFSET_BEGINNING;
  251. fsFromCurrent : seekMode:=OFFSET_CURRENT;
  252. fsFromEnd : seekMode:=OFFSET_END;
  253. end;
  254. dosSeek(Handle, FOffset, seekMode);
  255. { get the current position when FileSeek ends, which should return
  256. the *NEW* position, while Amiga Seek() returns the old one }
  257. FileSeek:=dosSeek(Handle, 0, OFFSET_CURRENT);
  258. end;
  259. function FileSeek(Handle: THandle; FOffset: Int64; Origin: Longint): Int64;
  260. begin
  261. {$WARNING Need to add 64bit call }
  262. FileSeek:=FileSeek(Handle,LongInt(FOffset),LongInt(Origin));
  263. end;
  264. procedure FileClose(Handle: THandle);
  265. begin
  266. if (Handle=0) or (Handle=-1) then exit;
  267. dosClose(Handle);
  268. RemoveFromList(ASYS_fileList,Handle);
  269. end;
  270. function FileTruncate(Handle: THandle; Size: Int64): Boolean;
  271. var
  272. dosResult: LongInt;
  273. begin
  274. FileTruncate:=False;
  275. if Size > high (longint) then exit;
  276. {$WARNING Possible support for 64-bit FS to be checked!}
  277. if (Handle=0) or (Handle=-1) then exit;
  278. dosResult:=SetFileSize(Handle, Size, OFFSET_BEGINNING);
  279. if (dosResult<0) then exit;
  280. FileTruncate:=True;
  281. end;
  282. function DeleteFile(const FileName: RawByteString) : Boolean;
  283. var
  284. SystemFileName: RawByteString;
  285. begin
  286. SystemFileName:=PathConv(ToSingleByteFileSystemEncodedFileName(FileName));
  287. DeleteFile:=dosDeleteFile(PAnsiChar(SystemFileName));
  288. end;
  289. function RenameFile(const OldName, NewName: RawByteString): Boolean;
  290. var
  291. OldSystemFileName, NewSystemFileName: RawByteString;
  292. begin
  293. OldSystemFileName:=PathConv(ToSingleByteFileSystemEncodedFileName(OldName));
  294. NewSystemFileName:=PathConv(ToSingleByteFileSystemEncodedFileName(NewName));
  295. RenameFile:=dosRename(PAnsiChar(OldSystemFileName), PAnsiChar(NewSystemFileName)) <> 0;
  296. end;
  297. (****** end of non portable routines ******)
  298. function FileAge (const FileName : RawByteString): Int64;
  299. var
  300. tmpLock: BPTR;
  301. tmpFIB : PFileInfoBlock;
  302. tmpDateTime: TDateTime;
  303. validFile: boolean;
  304. SystemFileName: RawByteString;
  305. begin
  306. validFile:=false;
  307. SystemFileName := PathConv(ToSingleByteFileSystemEncodedFileName(FileName));
  308. tmpLock := Lock(PAnsiChar(SystemFileName), SHARED_LOCK);
  309. if (tmpLock <> 0) then begin
  310. new(tmpFIB);
  311. if Examine(tmpLock,tmpFIB) <> 0 then begin
  312. tmpDateTime:=AmigaFileDateToDateTime(tmpFIB^.fib_Date,validFile);
  313. end;
  314. Unlock(tmpLock);
  315. dispose(tmpFIB);
  316. end;
  317. if validFile then
  318. result:=DateTimeToFileDate(tmpDateTime)
  319. else
  320. result:=-1;
  321. end;
  322. function FileGetSymLinkTarget(const FileName: RawByteString; out SymLinkRec: TRawbyteSymLinkRec): Boolean;
  323. begin
  324. Result := False;
  325. end;
  326. function FileExists (const FileName : RawByteString; FollowLink : Boolean) : Boolean;
  327. var
  328. tmpLock: BPTR;
  329. tmpFIB : PFileInfoBlock;
  330. SystemFileName: RawByteString;
  331. begin
  332. result:=false;
  333. SystemFileName := PathConv(ToSingleByteFileSystemEncodedFileName(FileName));
  334. tmpLock := Lock(PAnsiChar(SystemFileName), SHARED_LOCK);
  335. if (tmpLock <> 0) then begin
  336. new(tmpFIB);
  337. if (Examine(tmpLock,tmpFIB) <> 0) and (tmpFIB^.fib_DirEntryType <= 0) then
  338. result:=true;
  339. Unlock(tmpLock);
  340. dispose(tmpFIB);
  341. end;
  342. end;
  343. Function InternalFindFirst (Const Path : RawByteString; Attr : Longint; out Rslt : TAbstractSearchRec; var Name: RawByteString) : Longint;
  344. var
  345. tmpStr: RawByteString;
  346. Anchor: PAnchorPath;
  347. tmpDateTime: TDateTime;
  348. validDate: boolean;
  349. begin
  350. result:=-1; { We emulate Linux/Unix behaviour, and return -1 on errors. }
  351. tmpStr:=PathConv(ToSingleByteFileSystemEncodedFileName(Path));
  352. { $1e = faHidden or faSysFile or faVolumeID or faDirectory }
  353. Rslt.ExcludeAttr := (not Attr) and ($1e);
  354. Rslt.FindHandle := nil;
  355. new(Anchor);
  356. FillChar(Anchor^,sizeof(TAnchorPath),#0);
  357. Rslt.FindHandle := Anchor;
  358. if MatchFirst(PAnsiChar(tmpStr),Anchor)<>0 then
  359. begin
  360. InternalFindClose(Rslt.FindHandle);
  361. exit;
  362. end;
  363. with Anchor^.ap_Info do begin
  364. Name := fib_FileName;
  365. SetCodePage(Name,DefaultFileSystemCodePage,false);
  366. Rslt.Size := fib_Size;
  367. Rslt.Time := DateTimeToFileDate(AmigaFileDateToDateTime(fib_Date,validDate));
  368. if not validDate then
  369. begin
  370. InternalFindClose(Rslt.FindHandle);
  371. exit;
  372. end;
  373. { "128" is Windows "NORMALFILE" attribute. Some buggy code depend on this... :( (KB) }
  374. Rslt.Attr := 128;
  375. if fib_DirEntryType > 0 then Rslt.Attr:=Rslt.Attr or faDirectory;
  376. if ((fib_Protection and FIBF_READ) <> 0) and
  377. ((fib_Protection and FIBF_WRITE) = 0) then Rslt.Attr:=Rslt.Attr or faReadOnly;
  378. result:=0; { Return zero if everything went OK }
  379. end;
  380. end;
  381. Function InternalFindNext (var Rslt : TAbstractSearchRec; var Name : RawByteString) : Longint;
  382. var
  383. Anchor: PAnchorPath;
  384. validDate: boolean;
  385. begin
  386. result:=-1;
  387. Anchor:=PAnchorPath(Rslt.FindHandle);
  388. if not assigned(Anchor) then exit;
  389. if MatchNext(Anchor) <> 0 then exit;
  390. with Anchor^.ap_Info do begin
  391. Name := fib_FileName;
  392. SetCodePage(Name,DefaultFileSystemCodePage,false);
  393. Rslt.Size := fib_Size;
  394. Rslt.Time := DateTimeToFileDate(AmigaFileDateToDateTime(fib_Date,validDate));
  395. if not validDate then exit;
  396. { "128" is Windows "NORMALFILE" attribute. Some buggy code depend on this... :( (KB) }
  397. Rslt.Attr := 128;
  398. if fib_DirEntryType > 0 then Rslt.Attr:=Rslt.Attr or faDirectory;
  399. if ((fib_Protection and FIBF_READ) <> 0) and
  400. ((fib_Protection and FIBF_WRITE) = 0) then Rslt.Attr:=Rslt.Attr or faReadOnly;
  401. result:=0; { Return zero if everything went OK }
  402. end;
  403. end;
  404. Procedure InternalFindClose(var Handle: Pointer);
  405. var
  406. Anchor: PAnchorPath absolute Handle;
  407. begin
  408. if not assigned(Anchor) then
  409. exit;
  410. MatchEnd(Anchor);
  411. Dispose(Anchor);
  412. Handle:=nil;
  413. end;
  414. (****** end of non portable routines ******)
  415. Function FileGetAttr (Const FileName : RawByteString) : Longint;
  416. var
  417. F: file;
  418. attr: word;
  419. begin
  420. Assign(F,FileName);
  421. dos.GetFAttr(F,attr);
  422. if DosError <> 0 then
  423. FileGetAttr := -1
  424. else
  425. FileGetAttr := Attr;
  426. end;
  427. Function FileSetAttr (Const Filename : RawByteString; Attr: longint) : Longint;
  428. var
  429. F: file;
  430. begin
  431. Assign(F, FileName);
  432. Dos.SetFAttr(F, Attr and $ffff);
  433. FileSetAttr := DosError;
  434. end;
  435. {****************************************************************************
  436. Disk Functions
  437. ****************************************************************************}
  438. {
  439. The Diskfree and Disksize functions need a file on the specified drive, since this
  440. is required for the statfs system call.
  441. These filenames are set in drivestr[0..26], and have been preset to :
  442. 0 - ':' (default drive - hence current dir is ok.)
  443. 1 - 'DF0:' (floppy drive 1 - should be adapted to local system )
  444. 2 - 'DF1:' (floppy drive 2 - should be adapted to local system )
  445. 3 - 'SYS:' (C: equivalent of dos is the SYS: partition)
  446. 4..26 (can be set by you're own applications)
  447. ! Use AddDisk() to Add new drives !
  448. They both return -1 when a failure occurs.
  449. }
  450. var
  451. DeviceList: array[0..26] of string[20];
  452. NumDevices: Integer = 0;
  453. const
  454. IllegalDevices: array[0..12] of string =(
  455. 'PED:',
  456. 'PRJ:',
  457. 'PIPE:', // Pipes
  458. 'XPIPE:', // Extented Pipe
  459. 'CON:', // Console
  460. 'RAW:', // RAW: Console
  461. 'KCON:', // KingCON Console
  462. 'KRAW:', // KingCON RAW
  463. 'SER:', // serial Ports
  464. 'SER0:',
  465. 'SER1:',
  466. 'PAR:', // Parallel Porty
  467. 'PRT:'); // Printer
  468. function IsIllegalDevice(DeviceName: string): Boolean;
  469. var
  470. i: Integer;
  471. Str: AnsiString;
  472. begin
  473. IsIllegalDevice := False;
  474. Str := UpperCase(DeviceName);
  475. for i := Low(IllegalDevices) to High(IllegalDevices) do
  476. begin
  477. if Str = IllegalDevices[i] then
  478. begin
  479. IsIllegalDevice := True;
  480. Exit;
  481. end;
  482. end;
  483. end;
  484. function DeviceByIdx(Idx: Integer): string;
  485. begin
  486. DeviceByIdx := '';
  487. if (Idx < 0) or (Idx >= NumDevices) then
  488. Exit;
  489. DeviceByIdx := DeviceList[Idx];
  490. end;
  491. function AddDisk(const Path: string): Integer;
  492. begin
  493. // if hit border, restart at 4
  494. if NumDevices > 26 then
  495. NumDevices := 4;
  496. // set the device
  497. DeviceList[NumDevices] := Copy(Path, 1, 20);
  498. // return the Index increment for next run
  499. AddDisk := NumDevices;
  500. Inc(NumDevices);
  501. end;
  502. function RefreshDeviceList: Integer;
  503. var
  504. List: PDosList;
  505. Temp: PAnsiChar;
  506. Str: string;
  507. begin
  508. NumDevices := 0;
  509. AddDisk(':'); // Index 0
  510. AddDisk('DF0:'); // Index 1
  511. AddDisk('DF1:'); // Index 2
  512. AddDisk('SYS:'); // Index 3
  513. // Lock the List
  514. List := LockDosList(LDF_DEVICES or LDF_READ);
  515. // Inspect the List
  516. repeat
  517. List := NextDosEntry(List, LDF_DEVICES);
  518. if List <> nil then
  519. begin
  520. Temp := BSTR2STRING(List^.dol_Name);
  521. Str := strpas(Temp) + ':';
  522. if not IsIllegalDevice(str) then
  523. AddDisk(Str);
  524. end;
  525. until List = nil;
  526. UnLockDosList(LDF_DEVICES or LDF_READ);
  527. RefreshDeviceList := NumDevices;
  528. end;
  529. // New easier DiskSize()
  530. //
  531. function DiskSize(Drive: AnsiString): Int64;
  532. var
  533. DirLock: BPTR;
  534. Inf: TInfoData;
  535. MyProc: PProcess;
  536. OldWinPtr: Pointer;
  537. begin
  538. DiskSize := -1;
  539. //
  540. MyProc := PProcess(FindTask(Nil));
  541. OldWinPtr := MyProc^.pr_WindowPtr;
  542. MyProc^.pr_WindowPtr := Pointer(-1);
  543. //
  544. DirLock := Lock(PAnsiChar(Drive), SHARED_LOCK);
  545. if DirLock <> 0 then
  546. begin
  547. if Info(DirLock, @Inf) <> 0 then
  548. DiskSize := Int64(Inf.id_NumBlocks) * Inf.id_BytesPerBlock;
  549. UnLock(DirLock);
  550. end;
  551. if OldWinPtr <> Pointer(-1) then
  552. MyProc^.pr_WindowPtr := OldWinPtr;
  553. end;
  554. function DiskSize(Drive: Byte): Int64;
  555. begin
  556. DiskSize := -1;
  557. if (Drive < 0) or (Drive >= NumDevices) then
  558. Exit;
  559. DiskSize := DiskSize(DeviceList[Drive]);
  560. end;
  561. // New easier DiskFree()
  562. //
  563. function DiskFree(Drive: AnsiString): Int64;
  564. var
  565. DirLock: BPTR;
  566. Inf: TInfoData;
  567. MyProc: PProcess;
  568. OldWinPtr: Pointer;
  569. begin
  570. DiskFree := -1;
  571. //
  572. MyProc := PProcess(FindTask(Nil));
  573. OldWinPtr := MyProc^.pr_WindowPtr;
  574. MyProc^.pr_WindowPtr := Pointer(-1);
  575. //
  576. DirLock := Lock(PAnsiChar(Drive), SHARED_LOCK);
  577. if DirLock <> 0 then
  578. begin
  579. if Info(DirLock, @Inf) <> 0 then
  580. DiskFree := Int64(Inf.id_NumBlocks - Inf.id_NumBlocksUsed) * Inf.id_BytesPerBlock;
  581. UnLock(DirLock);
  582. end;
  583. if OldWinPtr <> Pointer(-1) then
  584. MyProc^.pr_WindowPtr := OldWinPtr;
  585. end;
  586. function DiskFree(Drive: Byte): Int64;
  587. begin
  588. DiskFree := -1;
  589. if (Drive < 0) or (Drive >= NumDevices) then
  590. Exit;
  591. DiskFree := DiskFree(DeviceList[Drive]);
  592. end;
  593. function DirectoryExists(const Directory: RawByteString; FollowLink : Boolean): Boolean;
  594. var
  595. tmpLock: BPTR;
  596. FIB : PFileInfoBlock;
  597. SystemDirName: RawByteString;
  598. begin
  599. result:=false;
  600. if (Directory='') or (InOutRes<>0) then exit;
  601. SystemDirName:=PathConv(ToSingleByteFileSystemEncodedFileName(Directory));
  602. tmpLock:=Lock(PAnsiChar(SystemDirName),SHARED_LOCK);
  603. if tmpLock=0 then exit;
  604. FIB:=nil; new(FIB);
  605. if (Examine(tmpLock,FIB) <> 0) and (FIB^.fib_DirEntryType>0) then
  606. result:=True;
  607. if tmpLock<>0 then Unlock(tmpLock);
  608. if assigned(FIB) then dispose(FIB);
  609. end;
  610. {****************************************************************************
  611. Locale Functions
  612. ****************************************************************************}
  613. Procedure GetLocalTime(var SystemTime: TSystemTime);
  614. var
  615. dayOfWeek: word;
  616. Sec100: Word;
  617. begin
  618. dos.GetTime(SystemTime.Hour, SystemTime.Minute, SystemTime.Second, Sec100);
  619. SystemTime.Millisecond := Sec100 * 10;
  620. dos.GetDate(SystemTime.Year, SystemTime.Month, SystemTime.Day, DayOfWeek);
  621. end;
  622. Procedure InitAnsi;
  623. Var
  624. i : longint;
  625. begin
  626. { Fill table entries 0 to 127 }
  627. for i := 0 to 96 do
  628. UpperCaseTable[i] := chr(i);
  629. for i := 97 to 122 do
  630. UpperCaseTable[i] := chr(i - 32);
  631. for i := 123 to 191 do
  632. UpperCaseTable[i] := chr(i);
  633. Move (CPISO88591UCT,UpperCaseTable[192],SizeOf(CPISO88591UCT));
  634. for i := 0 to 64 do
  635. LowerCaseTable[i] := chr(i);
  636. for i := 65 to 90 do
  637. LowerCaseTable[i] := chr(i + 32);
  638. for i := 91 to 191 do
  639. LowerCaseTable[i] := chr(i);
  640. Move (CPISO88591LCT,UpperCaseTable[192],SizeOf(CPISO88591UCT));
  641. end;
  642. Procedure InitInternational;
  643. begin
  644. InitInternationalGeneric;
  645. InitAnsi;
  646. end;
  647. function SysErrorMessage(ErrorCode: Integer): String;
  648. begin
  649. Result:=Format(SUnknownErrorCode,[ErrorCode]);
  650. end;
  651. function GetLastOSError: Integer;
  652. begin
  653. result:=-1;
  654. end;
  655. {****************************************************************************
  656. OS utility functions
  657. ****************************************************************************}
  658. var
  659. StrOfPaths: String;
  660. function SystemTags(const command: PAnsiChar; const tags: array of PtrUInt): LongInt;
  661. begin
  662. SystemTags:=SystemTagList(command,@tags);
  663. end;
  664. function GetPathString: String;
  665. var
  666. f : text;
  667. s : string;
  668. begin
  669. s := '';
  670. result := '';
  671. { Alternatively, this could use PIPE: handler on systems which
  672. have this by default (not the case on classic Amiga), but then
  673. the child process should be started async, which for a simple
  674. Path command probably isn't worth the trouble. (KB) }
  675. assign(f,'T:'+HexStr(FindTask(nil))+'_path.tmp');
  676. rewrite(f);
  677. { This is a pretty ugly stunt, combining Pascal and Amiga system
  678. functions, but works... }
  679. SystemTags('C:Path',[SYS_Input, 0, SYS_Output, TextRec(f).Handle, TAG_END]);
  680. close(f);
  681. reset(f);
  682. { skip the first line, garbage }
  683. if not eof(f) then readln(f,s);
  684. while not eof(f) do begin
  685. readln(f,s);
  686. if result = '' then
  687. result := s
  688. else
  689. result := result + ';' + s;
  690. end;
  691. close(f);
  692. erase(f);
  693. end;
  694. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  695. begin
  696. if UpCase(envvar) = 'PATH' then begin
  697. if StrOfpaths = '' then StrOfPaths := GetPathString;
  698. Result:=StrOfPaths;
  699. end else
  700. Result:=Dos.Getenv(shortstring(EnvVar));
  701. end;
  702. Function GetEnvironmentVariableCount : Integer;
  703. begin
  704. // Result:=FPCCountEnvVar(EnvP);
  705. Result:=Dos.envCount;
  706. end;
  707. Function GetEnvironmentString(Index : Integer) : {$ifdef FPC_RTL_UNICODE}UnicodeString{$else}AnsiString{$endif};
  708. begin
  709. // Result:=FPCGetEnvStrFromP(Envp,Index);
  710. Result:=Dos.EnvStr(Index);
  711. end;
  712. function ExecuteProcess (const Path: RawByteString; const ComLine: RawByteString;Flags:TExecuteFlags=[]):
  713. integer;
  714. var
  715. tmpPath,
  716. convPath: RawByteString;
  717. CommandLine: AnsiString;
  718. tmpLock: BPTR;
  719. E: EOSError;
  720. begin
  721. DosError:= 0;
  722. convPath:=PathConv(ToSingleByteFileSystemEncodedFileName(Path));
  723. tmpPath:=convPath+' '+ToSingleByteFileSystemEncodedFileName(ComLine);
  724. { Here we must first check if the command we wish to execute }
  725. { actually exists, because this is NOT handled by the }
  726. { _SystemTagList call (program will abort!!) }
  727. { Try to open with shared lock }
  728. tmpLock:=Lock(PAnsiChar(convPath),SHARED_LOCK);
  729. if tmpLock<>0 then
  730. begin
  731. { File exists - therefore unlock it }
  732. Unlock(tmpLock);
  733. result:=SystemTagList(PAnsiChar(tmpPath),nil);
  734. { on return of -1 the shell could not be executed }
  735. { probably because there was not enough memory }
  736. if result = -1 then
  737. DosError:=8;
  738. end
  739. else
  740. DosError:=3;
  741. if DosError <> 0 then begin
  742. if ComLine = '' then
  743. CommandLine := Path
  744. else
  745. CommandLine := Path + ' ' + ComLine;
  746. E := EOSError.CreateFmt (SExecuteProcessFailed, [CommandLine, DosError]);
  747. E.ErrorCode := DosError;
  748. raise E;
  749. end;
  750. end;
  751. function ExecuteProcess (const Path: RawByteString;
  752. const ComLine: array of RawByteString;Flags:TExecuteFlags=[]): integer;
  753. var
  754. CommandLine: RawByteString;
  755. I: integer;
  756. begin
  757. Commandline := '';
  758. for I := 0 to High (ComLine) do
  759. if Pos (' ', ComLine [I]) <> 0 then
  760. CommandLine := CommandLine + ' ' + '"' + ToSingleByteFileSystemEncodedFileName(ComLine [I]) + '"'
  761. else
  762. CommandLine := CommandLine + ' ' + ToSingleByteFileSystemEncodedFileName(Comline [I]);
  763. ExecuteProcess := ExecuteProcess (Path, CommandLine);
  764. end;
  765. procedure Sleep(Milliseconds: cardinal);
  766. begin
  767. // Amiga dos.library Delay() has precision of 1/50 seconds
  768. DOSDelay(Milliseconds div 20);
  769. end;
  770. function GetTempDir(Global: Boolean): string;
  771. begin
  772. if Assigned(OnGetTempDir) then
  773. Result := OnGetTempDir(Global)
  774. else
  775. begin
  776. Result := GetEnvironmentVariable('TEMP');
  777. if Result = '' Then
  778. Result:=GetEnvironmentVariable('TMP');
  779. if Result = '' then
  780. Result := 'T:'; // fallback.
  781. end;
  782. if Result <> '' then
  783. Result := IncludeTrailingPathDelimiter(Result);
  784. end;
  785. {****************************************************************************
  786. Initialization code
  787. ****************************************************************************}
  788. Initialization
  789. InitExceptions;
  790. InitInternational; { Initialize internationalization settings }
  791. OnBeep:=Nil; { No SysBeep() on Amiga, for now. Figure out if we want
  792. to use intuition.library/DisplayBeep() for this (KB) }
  793. StrOfPaths:='';
  794. RefreshDeviceList;
  795. Finalization
  796. FreeTerminateProcs;
  797. DoneExceptions;
  798. end.