sysutils.pp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  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 win32
  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. uses
  21. windows;
  22. {$DEFINE HAS_SLEEP}
  23. {$DEFINE HAS_OSERROR}
  24. {$DEFINE HAS_OSCONFIG}
  25. {$DEFINE HAS_OSUSERDIR}
  26. {$DEFINE HAS_CREATEGUID}
  27. {$DEFINE HAS_LOCALTIMEZONEOFFSET}
  28. {$DEFINE HAS_GETTICKCOUNT}
  29. {$DEFINE HAS_GETTICKCOUNT64}
  30. {$DEFINE OS_FILESETDATEBYNAME}
  31. // this target has an fileflush implementation, don't include dummy
  32. {$DEFINE SYSUTILS_HAS_FILEFLUSH_IMPL}
  33. { used OS file system APIs use unicodestring }
  34. {$define SYSUTILS_HAS_UNICODESTR_FILEUTIL_IMPL}
  35. { OS has an ansistring/single byte environment variable API }
  36. {$define SYSUTILS_HAS_ANSISTR_ENVVAR_IMPL}
  37. { OS has a unicodestring/two byte environment variable API }
  38. {$define SYSUTILS_HAS_UNICODESTR_ENVVAR_IMPL}
  39. { Include platform independent interface part }
  40. {$i sysutilh.inc}
  41. type
  42. TSystemTime = Windows.TSystemTime;
  43. EWin32Error = class(Exception)
  44. public
  45. ErrorCode : DWORD;
  46. end;
  47. Var
  48. Win32Platform : Longint;
  49. Win32MajorVersion,
  50. Win32MinorVersion,
  51. Win32BuildNumber : dword;
  52. Win32CSDVersion : ShortString; // CSD record is 128 bytes only?
  53. const
  54. MaxEraCount = 7;
  55. var
  56. EraNames: array [1..MaxEraCount] of String;
  57. EraYearOffsets: array [1..MaxEraCount] of Integer;
  58. { Compatibility with Delphi }
  59. function Win32Check(res:boolean):boolean;inline;
  60. function WinCheck(res:boolean):boolean;
  61. function CheckWin32Version(Major,Minor : Integer ): Boolean;
  62. function CheckWin32Version(Major : Integer): Boolean;
  63. Procedure RaiseLastWin32Error;
  64. function GetFileVersion(const AFileName: string): Cardinal;
  65. function GetFileVersion(const AFileName: UnicodeString): Cardinal;
  66. procedure GetFormatSettings;
  67. procedure GetLocaleFormatSettings(LCID: Integer; var FormatSettings: TFormatSettings); platform;
  68. implementation
  69. uses
  70. sysconst,
  71. windirs;
  72. var
  73. FindExInfoDefaults : TFINDEX_INFO_LEVELS = FindExInfoStandard;
  74. FindFirstAdditionalFlags : DWord = 0;
  75. function WinCheck(res:boolean):boolean;
  76. begin
  77. if not res then
  78. RaiseLastOSError;
  79. result:=res;
  80. end;
  81. function Win32Check(res:boolean):boolean;inline;
  82. begin
  83. result:=WinCheck(res);
  84. end;
  85. procedure RaiseLastWin32Error;
  86. begin
  87. RaiseLastOSError;
  88. end;
  89. function CheckWin32Version(Major : Integer): Boolean;
  90. begin
  91. Result:=CheckWin32Version(Major,0)
  92. end;
  93. function CheckWin32Version(Major,Minor: Integer): Boolean;
  94. begin
  95. Result:=(Win32MajorVersion>dword(Major)) or
  96. ((Win32MajorVersion=dword(Major)) and (Win32MinorVersion>=dword(Minor)));
  97. end;
  98. function GetFileVersion(const AFileName:string):Cardinal;
  99. var
  100. { useful only as long as we don't need to touch different stack pages }
  101. buf : array[0..3071] of byte;
  102. bufp : pointer;
  103. fn : string;
  104. valsize,
  105. size : DWORD;
  106. h : DWORD;
  107. valrec : PVSFixedFileInfo;
  108. begin
  109. result:=$fffffff;
  110. fn:=AFileName;
  111. UniqueString(fn);
  112. size:=GetFileVersionInfoSizeA(pchar(fn),@h);
  113. if size>sizeof(buf) then
  114. begin
  115. getmem(bufp,size);
  116. try
  117. if GetFileVersionInfoA(pchar(fn),h,size,bufp) then
  118. if VerQueryValue(bufp,'\',valrec,valsize) then
  119. result:=valrec^.dwFileVersionMS;
  120. finally
  121. freemem(bufp);
  122. end;
  123. end
  124. else
  125. begin
  126. if GetFileVersionInfoA(pchar(fn),h,size,@buf) then
  127. if VerQueryValue(@buf,'\',valrec,valsize) then
  128. result:=valrec^.dwFileVersionMS;
  129. end;
  130. end;
  131. function GetFileVersion(const AFileName:UnicodeString):Cardinal;
  132. var
  133. { useful only as long as we don't need to touch different stack pages }
  134. buf : array[0..3071] of byte;
  135. bufp : pointer;
  136. fn : unicodestring;
  137. valsize,
  138. size : DWORD;
  139. h : DWORD;
  140. valrec : PVSFixedFileInfo;
  141. begin
  142. result:=$fffffff;
  143. fn:=AFileName;
  144. UniqueString(fn);
  145. size:=GetFileVersionInfoSizeW(pwidechar(fn),@h);
  146. if size>sizeof(buf) then
  147. begin
  148. getmem(bufp,size);
  149. try
  150. if GetFileVersionInfoW(pwidechar(fn),h,size,bufp) then
  151. if VerQueryValue(bufp,'\',valrec,valsize) then
  152. result:=valrec^.dwFileVersionMS;
  153. finally
  154. freemem(bufp);
  155. end;
  156. end
  157. else
  158. begin
  159. if GetFileVersionInfoW(pwidechar(fn),h,size,@buf) then
  160. if VerQueryValueW(@buf,'\',valrec,valsize) then
  161. result:=valrec^.dwFileVersionMS;
  162. end;
  163. end;
  164. {$define HASCREATEGUID}
  165. {$define HASEXPANDUNCFILENAME}
  166. {$DEFINE FPC_NOGENERICANSIROUTINES}
  167. {$DEFINE FPC_FEXPAND_UNC} (* UNC paths are supported *)
  168. {$DEFINE FPC_FEXPAND_DRIVES} (* Full paths begin with drive specification *)
  169. function ConvertEraYearString(Count ,Year,Month,Day : integer) : string; forward;
  170. function ConvertEraString(Count ,Year,Month,Day : integer) : string; forward;
  171. { Include platform independent implementation part }
  172. {$i sysutils.inc}
  173. function GetTempFileName(Dir,Prefix: PChar; uUnique: DWORD; TempFileName: PChar):DWORD;
  174. begin
  175. Result:= Windows.GetTempFileNameA(Dir,Prefix,uUnique,TempFileName);
  176. end;
  177. { UUID generation. }
  178. function CoCreateGuid(out guid: TGUID): HResult; stdcall; external 'ole32.dll' name 'CoCreateGuid';
  179. function SysCreateGUID(out Guid: TGUID): Integer;
  180. begin
  181. Result := Integer(CoCreateGuid(Guid));
  182. end;
  183. function ExpandUNCFileName (const filename:rawbytestring) : rawbytestring;
  184. { returns empty string on errors }
  185. var
  186. u: unicodestring;
  187. begin
  188. { prevent data loss due to unsupported characters in ansi code page }
  189. u:=ExpandUNCFileName(unicodestring(filename));
  190. widestringmanager.Unicode2AnsiMoveProc(punicodechar(u),result,DefaultRTLFileSystemCodePage,length(u));
  191. end;
  192. function ExpandUNCFileName (const filename:unicodestring) : unicodestring;
  193. { returns empty string on errors }
  194. var
  195. s : unicodestring;
  196. size : dword;
  197. rc : dword;
  198. buf : pwidechar;
  199. begin
  200. s := ExpandFileName (filename);
  201. s := s + #0;
  202. size := max_path;
  203. getmem(buf,size);
  204. try
  205. rc := WNetGetUniversalNameW (pwidechar(s), UNIVERSAL_NAME_INFO_LEVEL, buf, @size);
  206. if rc=ERROR_MORE_DATA then
  207. begin
  208. buf:=reallocmem(buf,size);
  209. rc := WNetGetUniversalNameW (pwidechar(s), UNIVERSAL_NAME_INFO_LEVEL, buf, @size);
  210. end;
  211. if rc = NO_ERROR then
  212. Result := PRemoteNameInfoW(buf)^.lpUniversalName
  213. else if rc = ERROR_NOT_CONNECTED then
  214. Result := filename
  215. else
  216. Result := '';
  217. finally
  218. freemem(buf);
  219. end;
  220. end;
  221. {****************************************************************************
  222. File Functions
  223. ****************************************************************************}
  224. const
  225. AccessMode: array[0..2] of Cardinal = (
  226. GENERIC_READ,
  227. GENERIC_WRITE,
  228. GENERIC_READ or GENERIC_WRITE or FILE_WRITE_ATTRIBUTES);
  229. ShareModes: array[0..4] of Integer = (
  230. 0,
  231. 0,
  232. FILE_SHARE_READ,
  233. FILE_SHARE_WRITE,
  234. FILE_SHARE_READ or FILE_SHARE_WRITE);
  235. function FileFlush(Handle: THandle): Boolean;
  236. begin
  237. Result:= FlushFileBuffers(Handle);
  238. end;
  239. Function FileOpen (Const FileName : unicodestring; Mode : Integer) : THandle;
  240. begin
  241. result := CreateFileW(PWideChar(FileName), dword(AccessMode[Mode and 3]),
  242. dword(ShareModes[(Mode and $F0) shr 4]), nil, OPEN_EXISTING,
  243. FILE_ATTRIBUTE_NORMAL, 0);
  244. //if fail api return feInvalidHandle (INVALIDE_HANDLE=feInvalidHandle=-1)
  245. end;
  246. Function FileCreate (Const FileName : UnicodeString) : THandle;
  247. begin
  248. FileCreate:=FileCreate(FileName, fmShareExclusive, 0);
  249. end;
  250. Function FileCreate (Const FileName : UnicodeString; Rights:longint) : THandle;
  251. begin
  252. FileCreate:=FileCreate(FileName, fmShareExclusive, Rights);
  253. end;
  254. Function FileCreate (Const FileName : UnicodeString; ShareMode : Integer; Rights : Integer) : THandle;
  255. begin
  256. Result := CreateFileW(PwideChar(FileName), GENERIC_READ or GENERIC_WRITE,
  257. dword(ShareModes[(ShareMode and $F0) shr 4]), nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  258. end;
  259. Function FileRead (Handle : THandle; out Buffer; Count : longint) : Longint;
  260. Var
  261. res : dword;
  262. begin
  263. if ReadFile(Handle, Buffer, Count, res, nil) then
  264. FileRead:=Res
  265. else
  266. FileRead:=-1;
  267. end;
  268. Function FileWrite (Handle : THandle; const Buffer; Count : Longint) : Longint;
  269. Var
  270. Res : dword;
  271. begin
  272. if WriteFile(Handle, Buffer, Count, Res, nil) then
  273. FileWrite:=Res
  274. else
  275. FileWrite:=-1;
  276. end;
  277. Function FileSeek (Handle : THandle;FOffset,Origin : Longint) : Longint;
  278. begin
  279. Result := longint(SetFilePointer(Handle, FOffset, nil, Origin));
  280. end;
  281. Function FileSeek (Handle : THandle; FOffset: Int64; Origin: Longint) : Int64;
  282. var
  283. rslt: Int64Rec;
  284. begin
  285. rslt := Int64Rec(FOffset);
  286. rslt.lo := SetFilePointer(Handle, rslt.lo, @rslt.hi, Origin);
  287. if (rslt.lo = $FFFFFFFF) and (GetLastError <> 0) then
  288. rslt.hi := $FFFFFFFF;
  289. Result := Int64(rslt);
  290. end;
  291. Procedure FileClose (Handle : THandle);
  292. begin
  293. CloseHandle(Handle);
  294. end;
  295. Function FileTruncate (Handle : THandle;Size: Int64) : boolean;
  296. begin
  297. {
  298. Result:=longint(SetFilePointer(handle,Size,nil,FILE_BEGIN))<>-1;
  299. }
  300. if FileSeek (Handle, Size, FILE_BEGIN) = Size then
  301. Result:=SetEndOfFile(handle)
  302. else
  303. Result := false;
  304. end;
  305. Function DosToWinTime (DTime:longint;Var Wtime : TFileTime):longbool;
  306. var
  307. lft : TFileTime;
  308. begin
  309. DosToWinTime:=DosDateTimeToFileTime(longrec(dtime).hi,longrec(dtime).lo,@lft) and
  310. LocalFileTimeToFileTime(lft,Wtime);
  311. end;
  312. Function WinToDosTime (Var Wtime : TFileTime;var DTime:longint):longbool;
  313. var
  314. lft : TFileTime;
  315. begin
  316. WinToDosTime:=FileTimeToLocalFileTime(WTime,lft) and
  317. FileTimeToDosDateTime(lft,Longrec(Dtime).Hi,LongRec(DTIME).lo);
  318. end;
  319. Function FileAge (Const FileName : UnicodeString): Longint;
  320. var
  321. Handle: THandle;
  322. FindData: TWin32FindDataW;
  323. begin
  324. Handle := FindFirstFileW(Pwidechar(FileName), FindData);
  325. if Handle <> INVALID_HANDLE_VALUE then
  326. begin
  327. Windows.FindClose(Handle);
  328. if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
  329. If WinToDosTime(FindData.ftLastWriteTime,Result) then
  330. exit;
  331. end;
  332. Result := -1;
  333. end;
  334. function FileGetSymLinkTarget(const FileName: UnicodeString; out SymLinkRec: TUnicodeSymLinkRec): Boolean;
  335. { reparse point specific declarations from Windows headers }
  336. const
  337. IO_REPARSE_TAG_MOUNT_POINT = $A0000003;
  338. IO_REPARSE_TAG_SYMLINK = $A000000C;
  339. ERROR_REPARSE_TAG_INVALID = 4393;
  340. FSCTL_GET_REPARSE_POINT = $900A8;
  341. MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16 * 1024;
  342. SYMLINK_FLAG_RELATIVE = 1;
  343. FILE_FLAG_OPEN_REPARSE_POINT = $200000;
  344. FILE_READ_EA = $8;
  345. type
  346. TReparseDataBuffer = record
  347. ReparseTag: ULONG;
  348. ReparseDataLength: Word;
  349. Reserved: Word;
  350. SubstituteNameOffset: Word;
  351. SubstituteNameLength: Word;
  352. PrintNameOffset: Word;
  353. PrintNameLength: Word;
  354. case ULONG of
  355. IO_REPARSE_TAG_MOUNT_POINT: (
  356. PathBufferMount: array[0..4095] of WCHAR);
  357. IO_REPARSE_TAG_SYMLINK: (
  358. Flags: ULONG;
  359. PathBufferSym: array[0..4095] of WCHAR);
  360. end;
  361. const
  362. CShareAny = FILE_SHARE_READ or FILE_SHARE_WRITE or FILE_SHARE_DELETE;
  363. COpenReparse = FILE_FLAG_OPEN_REPARSE_POINT or FILE_FLAG_BACKUP_SEMANTICS;
  364. var
  365. HFile, Handle: THandle;
  366. PBuffer: ^TReparseDataBuffer;
  367. BytesReturned: DWORD;
  368. begin
  369. SymLinkRec := Default(TUnicodeSymLinkRec);
  370. HFile := CreateFileW(PUnicodeChar(FileName), FILE_READ_EA, CShareAny, Nil, OPEN_EXISTING, COpenReparse, 0);
  371. if HFile <> INVALID_HANDLE_VALUE then
  372. try
  373. GetMem(PBuffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
  374. try
  375. if DeviceIoControl(HFile, FSCTL_GET_REPARSE_POINT, Nil, 0,
  376. PBuffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, @BytesReturned, Nil) then begin
  377. case PBuffer^.ReparseTag of
  378. IO_REPARSE_TAG_MOUNT_POINT: begin
  379. SymLinkRec.TargetName := WideCharLenToString(
  380. @PBuffer^.PathBufferMount[4 { skip start '\??\' } +
  381. PBuffer^.SubstituteNameOffset div SizeOf(WCHAR)],
  382. PBuffer^.SubstituteNameLength div SizeOf(WCHAR) - 4);
  383. end;
  384. IO_REPARSE_TAG_SYMLINK: begin
  385. SymLinkRec.TargetName := WideCharLenToString(
  386. @PBuffer^.PathBufferSym[PBuffer^.PrintNameOffset div SizeOf(WCHAR)],
  387. PBuffer^.PrintNameLength div SizeOf(WCHAR));
  388. if (PBuffer^.Flags and SYMLINK_FLAG_RELATIVE) <> 0 then
  389. SymLinkRec.TargetName := ExpandFileName(ExtractFilePath(FileName) + SymLinkRec.TargetName);
  390. end;
  391. end;
  392. Handle := FindFirstFileExW(PUnicodeChar(FileName), FindExInfoDefaults , @SymLinkRec.FindData,
  393. FindExSearchNameMatch, Nil, 0);
  394. if Handle <> INVALID_HANDLE_VALUE then begin
  395. Windows.FindClose(Handle);
  396. SymLinkRec.Attr := SymLinkRec.FindData.dwFileAttributes;
  397. SymLinkRec.Size := QWord(SymLinkRec.FindData.nFileSizeHigh) shl 32 + QWord(SymLinkRec.FindData.nFileSizeLow);
  398. end else
  399. SymLinkRec.TargetName := '';
  400. end else
  401. SetLastError(ERROR_REPARSE_TAG_INVALID);
  402. finally
  403. FreeMem(PBuffer);
  404. end;
  405. finally
  406. CloseHandle(HFile);
  407. end;
  408. Result := SymLinkRec.TargetName <> '';
  409. end;
  410. function FileOrDirExists(const FileOrDirName: UnicodeString; CheckDir: Boolean; FollowLink: Boolean): Boolean;
  411. const
  412. CDirAttributes: array[Boolean] of DWORD = (0, FILE_ATTRIBUTE_DIRECTORY);
  413. function FoundByEnum: Boolean;
  414. var
  415. FindData: TWin32FindDataW;
  416. Handle: THandle;
  417. begin
  418. { FindFirstFileEx is faster than FindFirstFile }
  419. Handle := FindFirstFileExW(PUnicodeChar(FileOrDirName), FindExInfoDefaults , @FindData,
  420. FindExSearchNameMatch, Nil, 0);
  421. Result := Handle <> INVALID_HANDLE_VALUE;
  422. if Result then begin
  423. Windows.FindClose(Handle);
  424. Result := (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = CDirAttributes[CheckDir];
  425. end;
  426. end;
  427. function LinkFileExists: Boolean;
  428. var
  429. LinkTargetName: UnicodeString;
  430. begin
  431. Result := FileGetSymLinkTarget(FileOrDirName, LinkTargetName) and
  432. FileOrDirExists(LinkTargetName, CheckDir, False);
  433. end;
  434. const
  435. CNotExistsErrors = [
  436. ERROR_FILE_NOT_FOUND,
  437. ERROR_PATH_NOT_FOUND,
  438. ERROR_INVALID_NAME, // protects from names in the form of masks like '*'
  439. ERROR_INVALID_DRIVE,
  440. ERROR_NOT_READY,
  441. ERROR_INVALID_PARAMETER,
  442. ERROR_BAD_PATHNAME,
  443. ERROR_BAD_NETPATH,
  444. ERROR_BAD_NET_NAME
  445. ];
  446. var
  447. Attr : DWord;
  448. begin
  449. Attr := GetFileAttributesW(PUnicodeChar(FileOrDirName));
  450. if Attr = INVALID_FILE_ATTRIBUTES then
  451. Result := not (GetLastError in CNotExistsErrors) and FoundByEnum
  452. else begin
  453. Result := (Attr and FILE_ATTRIBUTE_DIRECTORY) = CDirAttributes[CheckDir];
  454. if Result and FollowLink and ((Attr and FILE_ATTRIBUTE_REPARSE_POINT) <> 0) then
  455. Result := LinkFileExists;
  456. end;
  457. end;
  458. Function FileExists (Const FileName : UnicodeString; FollowLink : Boolean) : Boolean;
  459. begin
  460. Result := FileOrDirExists(FileName, False, FollowLink);
  461. end;
  462. Function DirectoryExists (Const Directory : UnicodeString; FollowLink : Boolean) : Boolean;
  463. begin
  464. Result := FileOrDirExists(Directory, True, FollowLink);
  465. end;
  466. Function FindMatch(var f: TAbstractSearchRec; var Name: UnicodeString) : Longint;
  467. begin
  468. { Find file with correct attribute }
  469. While (F.FindData.dwFileAttributes and cardinal(F.ExcludeAttr))<>0 do
  470. begin
  471. if not FindNextFileW (F.FindHandle,F.FindData) then
  472. begin
  473. Result:=GetLastError;
  474. exit;
  475. end;
  476. end;
  477. { Convert some attributes back }
  478. WinToDosTime(F.FindData.ftLastWriteTime,F.Time);
  479. f.size:=F.FindData.NFileSizeLow+(qword(maxdword)+1)*F.FindData.NFileSizeHigh;
  480. f.attr:=F.FindData.dwFileAttributes;
  481. Name:=F.FindData.cFileName;
  482. Result:=0;
  483. end;
  484. Procedure InternalFindClose (var Handle: THandle; var FindData: TFindData);
  485. begin
  486. if Handle <> INVALID_HANDLE_VALUE then
  487. begin
  488. Windows.FindClose(Handle);
  489. Handle:=INVALID_HANDLE_VALUE;
  490. end;
  491. end;
  492. Function InternalFindFirst (Const Path : UnicodeString; Attr : Longint; out Rslt : TAbstractSearchRec; var Name : UnicodeString) : Longint;
  493. begin
  494. Name:=Path;
  495. Rslt.Attr:=attr;
  496. Rslt.ExcludeAttr:=(not Attr) and ($1e);
  497. { $1e = faHidden or faSysFile or faVolumeID or faDirectory }
  498. { FindFirstFile is a Win32 Call }
  499. Rslt.FindHandle:=FindFirstFileExW(PUnicodeChar(Path), FindExInfoDefaults , @Rslt.FindData,
  500. FindExSearchNameMatch, Nil, FindFirstAdditionalFlags);
  501. If Rslt.FindHandle=Invalid_Handle_value then
  502. begin
  503. Result:=GetLastError;
  504. exit;
  505. end;
  506. { Find file with correct attribute }
  507. Result:=FindMatch(Rslt,Name);
  508. if (Result<>0) then
  509. InternalFindClose(Rslt.FindHandle,Rslt.FindData);
  510. end;
  511. Function InternalFindNext (Var Rslt : TAbstractSearchRec; var Name: UnicodeString) : Longint;
  512. begin
  513. if FindNextFileW(Rslt.FindHandle, Rslt.FindData) then
  514. Result := FindMatch(Rslt, Name)
  515. else
  516. Result := GetLastError;
  517. end;
  518. Function FileGetDate (Handle : THandle) : Longint;
  519. Var
  520. FT : TFileTime;
  521. begin
  522. If GetFileTime(Handle,nil,nil,@ft) and
  523. WinToDosTime(FT,Result) then
  524. exit;
  525. Result:=-1;
  526. end;
  527. Function FileSetDate (Handle : THandle;Age : Longint) : Longint;
  528. Var
  529. FT: TFileTime;
  530. begin
  531. Result := 0;
  532. if DosToWinTime(Age,FT) and
  533. SetFileTime(Handle, nil, nil, @FT) then
  534. Exit;
  535. Result := GetLastError;
  536. end;
  537. {$IFDEF OS_FILESETDATEBYNAME}
  538. Function FileSetDate (Const FileName : UnicodeString;Age : Longint) : Longint;
  539. Var
  540. fd : THandle;
  541. begin
  542. FD := CreateFileW (PWideChar (FileName), GENERIC_READ or GENERIC_WRITE,
  543. FILE_SHARE_WRITE, nil, OPEN_EXISTING,
  544. FILE_FLAG_BACKUP_SEMANTICS, 0);
  545. If (Fd<>feInvalidHandle) then
  546. try
  547. Result:=FileSetDate(fd,Age);
  548. finally
  549. FileClose(fd);
  550. end
  551. else
  552. Result:=GetLastOSError;
  553. end;
  554. {$ENDIF}
  555. Function FileGetAttr (Const FileName : UnicodeString) : Longint;
  556. begin
  557. Result:=Longint(GetFileAttributesW(PWideChar(FileName)));
  558. end;
  559. Function FileSetAttr (Const Filename : UnicodeString; Attr: longint) : Longint;
  560. begin
  561. if SetFileAttributesW(PWideChar(FileName), Attr) then
  562. Result:=0
  563. else
  564. Result := GetLastError;
  565. end;
  566. Function DeleteFile (Const FileName : UnicodeString) : Boolean;
  567. begin
  568. Result:=Windows.DeleteFileW(PWidechar(FileName));
  569. end;
  570. Function RenameFile (Const OldName, NewName : UnicodeString) : Boolean;
  571. begin
  572. Result := MoveFileW(PWideChar(OldName), PWideChar(NewName));
  573. end;
  574. {****************************************************************************
  575. Disk Functions
  576. ****************************************************************************}
  577. type
  578. TGetDiskFreeSpaceEx = function(drive:pchar;var availableforcaller,total,free):longbool;stdcall;
  579. var
  580. GetDiskFreeSpaceEx : TGetDiskFreeSpaceEx;
  581. function diskfree(drive : byte) : int64;
  582. var
  583. disk : array[1..4] of char;
  584. secs,bytes,
  585. free,total : dword;
  586. qwtotal,qwfree,qwcaller : int64;
  587. begin
  588. if drive=0 then
  589. begin
  590. disk[1]:='\';
  591. disk[2]:=#0;
  592. end
  593. else
  594. begin
  595. disk[1]:=chr(drive+64);
  596. disk[2]:=':';
  597. disk[3]:='\';
  598. disk[4]:=#0;
  599. end;
  600. if assigned(GetDiskFreeSpaceEx) then
  601. begin
  602. if GetDiskFreeSpaceEx(@disk[1],qwcaller,qwtotal,qwfree) then
  603. diskfree:=qwfree
  604. else
  605. diskfree:=-1;
  606. end
  607. else
  608. begin
  609. if GetDiskFreeSpace(@disk[1],secs,bytes,free,total) then
  610. diskfree:=int64(free)*secs*bytes
  611. else
  612. diskfree:=-1;
  613. end;
  614. end;
  615. function disksize(drive : byte) : int64;
  616. var
  617. disk : array[1..4] of char;
  618. secs,bytes,
  619. free,total : dword;
  620. qwtotal,qwfree,qwcaller : int64;
  621. begin
  622. if drive=0 then
  623. begin
  624. disk[1]:='\';
  625. disk[2]:=#0;
  626. end
  627. else
  628. begin
  629. disk[1]:=chr(drive+64);
  630. disk[2]:=':';
  631. disk[3]:='\';
  632. disk[4]:=#0;
  633. end;
  634. if assigned(GetDiskFreeSpaceEx) then
  635. begin
  636. if GetDiskFreeSpaceEx(@disk[1],qwcaller,qwtotal,qwfree) then
  637. disksize:=qwtotal
  638. else
  639. disksize:=-1;
  640. end
  641. else
  642. begin
  643. if GetDiskFreeSpace(@disk[1],secs,bytes,free,total) then
  644. disksize:=int64(total)*secs*bytes
  645. else
  646. disksize:=-1;
  647. end;
  648. end;
  649. {****************************************************************************
  650. Time Functions
  651. ****************************************************************************}
  652. Procedure GetLocalTime(var SystemTime: TSystemTime);
  653. begin
  654. windows.Getlocaltime(SystemTime);
  655. end;
  656. function GetLocalTimeOffset: Integer;
  657. var
  658. TZInfo: TTimeZoneInformation;
  659. begin
  660. case GetTimeZoneInformation(TZInfo) of
  661. TIME_ZONE_ID_UNKNOWN:
  662. Result := TZInfo.Bias;
  663. TIME_ZONE_ID_STANDARD:
  664. Result := TZInfo.Bias + TZInfo.StandardBias;
  665. TIME_ZONE_ID_DAYLIGHT:
  666. Result := TZInfo.Bias + TZInfo.DaylightBias;
  667. else
  668. Result := 0;
  669. end;
  670. end;
  671. function GetTickCount: LongWord;
  672. begin
  673. Result := Windows.GetTickCount;
  674. end;
  675. {$IFNDEF WINCE}
  676. type
  677. TGetTickCount64 = function : QWord; stdcall;
  678. var
  679. WinGetTickCount64: TGetTickCount64 = Nil;
  680. {$ENDIF}
  681. function GetTickCount64: QWord;
  682. {$IFNDEF WINCE}
  683. var
  684. lib: THandle;
  685. {$ENDIF}
  686. begin
  687. {$IFNDEF WINCE}
  688. { on Vista and newer there is a GetTickCount64 implementation }
  689. if Win32MajorVersion >= 6 then begin
  690. if not Assigned(WinGetTickCount64) then begin
  691. lib := LoadLibrary('kernel32.dll');
  692. WinGetTickCount64 := TGetTickCount64(
  693. GetProcAddress(lib, 'GetTickCount64'));
  694. end;
  695. Result := WinGetTickCount64();
  696. end else
  697. {$ENDIF}
  698. Result := Windows.GetTickCount;
  699. end;
  700. {****************************************************************************
  701. Misc Functions
  702. ****************************************************************************}
  703. procedure sysbeep;
  704. begin
  705. MessageBeep(0);
  706. end;
  707. {****************************************************************************
  708. Locale Functions
  709. ****************************************************************************}
  710. function GetLocaleStr(LID, LT: Longint; const Def: string): ShortString;
  711. var
  712. L: Integer;
  713. Buf: array[0..255] of Char;
  714. begin
  715. L := GetLocaleInfoA(LID, LT, Buf, SizeOf(Buf));
  716. if L > 0 then
  717. SetString(Result, @Buf[0], L - 1)
  718. else
  719. Result := Def;
  720. end;
  721. function GetLocaleChar(LID, LT: Longint; Def: Char): Char;
  722. var
  723. Buf: array[0..3] of Char; // sdate allows 4 chars.
  724. begin
  725. if GetLocaleInfoA(LID, LT, Buf, sizeof(buf)) > 0 then
  726. Result := Buf[0]
  727. else
  728. Result := Def;
  729. end;
  730. function ConvertEraString(Count ,Year,Month,Day : integer) : string;
  731. var
  732. ASystemTime: TSystemTime;
  733. wbuf: array[0..100] of WideChar;
  734. ALCID : LCID;
  735. begin
  736. Result := ''; if (Count<=0) then exit;
  737. DateTimeToSystemTime(EncodeDate(Year,Month,Day),ASystemTime);
  738. ALCID := GetThreadLocale;
  739. // ALCID := SysLocale.DefaultLCID;
  740. if GetDateFormatW(ALCID , DATE_USE_ALT_CALENDAR
  741. , @ASystemTime, PWChar('gg')
  742. , @wbuf, SizeOf(wbuf)) > 0 then
  743. begin
  744. if Count = 1 then
  745. wbuf[1] := #0;
  746. Result := string(WideString(wbuf));
  747. end;
  748. end;
  749. function ConvertEraYearString(Count ,Year,Month,Day : integer) : string;
  750. var
  751. ALCID : LCID;
  752. ASystemTime : TSystemTime;
  753. AFormatText : string;
  754. buf : array[0..100] of Char;
  755. begin
  756. Result := '';
  757. DateTimeToSystemTime(EncodeDate(Year,Month,Day),ASystemTime);
  758. if Count <= 2 then
  759. AFormatText := 'yy'
  760. else
  761. AFormatText := 'yyyy';
  762. ALCID := GetThreadLocale;
  763. // ALCID := SysLocale.DefaultLCID;
  764. if GetDateFormatA(ALCID, DATE_USE_ALT_CALENDAR
  765. , @ASystemTime, PChar(AFormatText)
  766. , @buf, SizeOf(buf)) > 0 then
  767. begin
  768. Result := buf;
  769. if (Count = 1) and (Result[1] = '0') then
  770. Result := Copy(Result, 2, Length(Result)-1);
  771. end;
  772. end;
  773. Function GetLocaleInt(LID,TP,Def: LongInt): LongInt;
  774. Var
  775. S: String;
  776. C: Integer;
  777. Begin
  778. S:=GetLocaleStr(LID,TP,'0');
  779. Val(S,Result,C);
  780. If C<>0 Then
  781. Result:=Def;
  782. End;
  783. function EnumEraNames(Names: PChar): WINBOOL; stdcall;
  784. var
  785. i : integer;
  786. begin
  787. Result := False;
  788. for i := Low(EraNames) to High(EraNames) do
  789. if (EraNames[i] = '') then
  790. begin
  791. EraNames[i] := Names;
  792. Result := True;
  793. break;
  794. end;
  795. end;
  796. function EnumEraYearOffsets(YearOffsets: PChar): WINBOOL; stdcall;
  797. var
  798. i : integer;
  799. begin
  800. Result := False;
  801. for i := Low(EraYearOffsets) to High(EraYearOffsets) do
  802. if (EraYearOffsets[i] = -1) then
  803. begin
  804. EraYearOffsets[i] := StrToIntDef(YearOffsets, 0);
  805. Result := True;
  806. break;
  807. end;
  808. end;
  809. procedure GetEraNamesAndYearOffsets;
  810. var
  811. ACALID : CALID;
  812. ALCID : LCID;
  813. buf : array[0..10] of char;
  814. i : integer;
  815. begin
  816. for i:= 1 to MaxEraCount do
  817. begin
  818. EraNames[i] := ''; EraYearOffsets[i] := -1;
  819. end;
  820. ALCID := GetThreadLocale;
  821. if GetLocaleInfoA(ALCID , LOCALE_IOPTIONALCALENDAR, buf, sizeof(buf)) <= 0 then exit;
  822. ACALID := StrToIntDef(buf,1);
  823. if ACALID in [3..5] then
  824. begin
  825. EnumCalendarInfoA(@EnumEraNames, ALCID, ACALID , CAL_SERASTRING);
  826. EnumCalendarInfoA(@EnumEraYearOffsets, ALCID, ACALID, CAL_IYEAROFFSETRANGE);
  827. end;
  828. (*
  829. 1 CAL_GREGORIAN Gregorian (localized)
  830. 2 CAL_GREGORIAN_US Gregorian (English strings always)
  831. 3 CAL_JAPAN Japanese Emperor Era
  832. 4 CAL_TAIWAN Taiwan Calendar
  833. 5 CAL_KOREA Korean Tangun Era
  834. 6 CAL_HIJRI Hijri (Arabic Lunar)
  835. 7 CAL_THAI Thai
  836. 8 CAL_HEBREW Hebrew (Lunar)
  837. 9 CAL_GREGORIAN_ME_FRENCH Gregorian Middle East French
  838. 10 CAL_GREGORIAN_ARABIC Gregorian Arabic
  839. 11 CAL_GREGORIAN_XLIT_ENGLISH Gregorian transliterated English
  840. 12 CAL_GREGORIAN_XLIT_FRENCH Gregorian transliterated French
  841. 23 CAL_UMALQURA Windows Vista or later: Um Al Qura (Arabic lunar) calendar
  842. *)
  843. end;
  844. procedure GetLocaleFormatSettings(LCID: Integer; var FormatSettings: TFormatSettings);
  845. var
  846. HF : Shortstring;
  847. LID : Windows.LCID;
  848. I,Day : longint;
  849. begin
  850. LID := LCID;
  851. with FormatSettings do
  852. begin
  853. { Date stuff }
  854. for I := 1 to 12 do
  855. begin
  856. ShortMonthNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVMONTHNAME1+I-1,ShortMonthNames[i]);
  857. LongMonthNames[I]:=GetLocaleStr(LID,LOCALE_SMONTHNAME1+I-1,LongMonthNames[i]);
  858. end;
  859. for I := 1 to 7 do
  860. begin
  861. Day := (I + 5) mod 7;
  862. ShortDayNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVDAYNAME1+Day,ShortDayNames[i]);
  863. LongDayNames[I]:=GetLocaleStr(LID,LOCALE_SDAYNAME1+Day,LongDayNames[i]);
  864. end;
  865. DateSeparator := GetLocaleChar(LID, LOCALE_SDATE, '/');
  866. ShortDateFormat := GetLocaleStr(LID, LOCALE_SSHORTDATE, 'm/d/yy');
  867. LongDateFormat := GetLocaleStr(LID, LOCALE_SLONGDATE, 'mmmm d, yyyy');
  868. { Time stuff }
  869. TimeSeparator := GetLocaleChar(LID, LOCALE_STIME, ':');
  870. TimeAMString := GetLocaleStr(LID, LOCALE_S1159, 'AM');
  871. TimePMString := GetLocaleStr(LID, LOCALE_S2359, 'PM');
  872. if StrToIntDef(GetLocaleStr(LID, LOCALE_ITLZERO, '0'), 0) = 0 then
  873. HF:='h'
  874. else
  875. HF:='hh';
  876. // No support for 12 hour stuff at the moment...
  877. ShortTimeFormat := HF+':nn';
  878. LongTimeFormat := HF + ':nn:ss';
  879. { Currency stuff }
  880. CurrencyString:=GetLocaleStr(LID, LOCALE_SCURRENCY, '');
  881. CurrencyFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRENCY, '0'), 0);
  882. NegCurrFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_INEGCURR, '0'), 0);
  883. { Number stuff }
  884. ThousandSeparator:=GetLocaleChar(LID, LOCALE_STHOUSAND, ',');
  885. DecimalSeparator:=GetLocaleChar(LID, LOCALE_SDECIMAL, '.');
  886. CurrencyDecimals:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRDIGITS, '0'), 0);
  887. ListSeparator := GetLocaleChar(LID, LOCALE_SLIST, ',');
  888. end;
  889. end;
  890. procedure GetFormatSettings;
  891. begin
  892. GetlocaleFormatSettings(GetThreadLocale, DefaultFormatSettings);
  893. end;
  894. Procedure InitLeadBytes;
  895. var
  896. I,B,C,E: Byte;
  897. Info: TCPInfo;
  898. begin
  899. GetCPInfo(CP_ACP,Info);
  900. I:=0;
  901. With Info do
  902. begin
  903. B:=LeadByte[i];
  904. E:=LeadByte[i+1];
  905. while (I<MAX_LEADBYTES) and (B<>0) and (E<>0) do
  906. begin
  907. for C:=B to E do
  908. Include(LeadBytes,AnsiChar(C));
  909. Inc(I,2);
  910. if (I<MAX_LEADBYTES) then
  911. begin
  912. B:=LeadByte[i];
  913. E:=LeadByte[i+1];
  914. end;
  915. end;
  916. end;
  917. end;
  918. Procedure InitInternational;
  919. var
  920. { A call to GetSystemMetrics changes the value of the 8087 Control Word on
  921. Pentium4 with WinXP SP2 }
  922. old8087CW: word;
  923. DefaultCustomLocaleID : LCID; // typedef DWORD LCID;
  924. DefaultCustomLanguageID : Word; // typedef WORD LANGID;
  925. begin
  926. /// workaround for Windows 7 bug, see bug report #18574
  927. SetThreadLocale(GetUserDefaultLCID);
  928. InitInternationalGeneric;
  929. old8087CW:=Get8087CW;
  930. SysLocale.MBCS:=GetSystemMetrics(SM_DBCSENABLED)<>0;
  931. SysLocale.RightToLeft:=GetSystemMetrics(SM_MIDEASTENABLED)<>0;
  932. SysLocale.DefaultLCID := $0409;
  933. SysLocale.PriLangID := LANG_ENGLISH;
  934. SysLocale.SubLangID := SUBLANG_ENGLISH_US;
  935. // probably needs update with getthreadlocale. post 2.0.2
  936. DefaultCustomLocaleID := GetThreadLocale;
  937. if DefaultCustomLocaleID <> 0 then
  938. begin
  939. { Locale Identifiers
  940. +-------------+---------+-------------------------+
  941. | Reserved | Sort ID | Language ID |
  942. +-------------+---------+-------------------------+
  943. 31 20 19 16 15 0 bit }
  944. DefaultCustomLanguageID := DefaultCustomLocaleID and $FFFF; // 2^16
  945. if DefaultCustomLanguageID <> 0 then
  946. begin
  947. SysLocale.DefaultLCID := DefaultCustomLocaleID;
  948. { Language Identifiers
  949. +-------------------------+-------------------------+
  950. | SubLanguage ID | Primary Language ID |
  951. +-------------------------+-------------------------+
  952. 15 10 9 0 bit }
  953. SysLocale.PriLangID := DefaultCustomLanguageID and $3ff; // 2^10
  954. SysLocale.SubLangID := DefaultCustomLanguageID shr 10;
  955. end;
  956. end;
  957. Set8087CW(old8087CW);
  958. GetFormatSettings;
  959. if SysLocale.FarEast then GetEraNamesAndYearOffsets;
  960. end;
  961. {****************************************************************************
  962. Target Dependent
  963. ****************************************************************************}
  964. function SysErrorMessage(ErrorCode: Integer): String;
  965. const
  966. MaxMsgSize = Format_Message_Max_Width_Mask;
  967. var
  968. MsgBuffer: unicodestring;
  969. len: longint;
  970. begin
  971. SetLength(MsgBuffer, MaxMsgSize);
  972. len := FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
  973. nil,
  974. ErrorCode,
  975. MakeLangId(LANG_NEUTRAL, SUBLANG_DEFAULT),
  976. PUnicodeChar(MsgBuffer),
  977. MaxMsgSize,
  978. nil);
  979. // Remove trailing #13#10
  980. if (len > 1) and (MsgBuffer[len - 1] = #13) and (MsgBuffer[len] = #10) then
  981. Dec(len, 2);
  982. SetLength(MsgBuffer, len);
  983. Result := MsgBuffer;
  984. end;
  985. {****************************************************************************
  986. Initialization code
  987. ****************************************************************************}
  988. {$push}
  989. { GetEnvironmentStrings cannot be checked by CheckPointer function }
  990. {$checkpointer off}
  991. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  992. var
  993. oemenvvar, oemstr : RawByteString;
  994. i, hplen : longint;
  995. hp,p : pchar;
  996. begin
  997. oemenvvar:=uppercase(envvar);
  998. SetCodePage(oemenvvar,CP_OEMCP);
  999. Result:='';
  1000. p:=GetEnvironmentStringsA;
  1001. hp:=p;
  1002. while hp^<>#0 do
  1003. begin
  1004. oemstr:=hp;
  1005. { cache length, may change after uppercasing depending on code page }
  1006. hplen:=length(oemstr);
  1007. { all environment variables are encoded in the oem code page }
  1008. SetCodePage(oemstr,CP_OEMCP,false);
  1009. i:=pos('=',oemstr);
  1010. if uppercase(copy(oemstr,1,i-1))=oemenvvar then
  1011. begin
  1012. Result:=copy(oemstr,i+1,length(oemstr)-i);
  1013. break;
  1014. end;
  1015. { next string entry}
  1016. hp:=hp+hplen+1;
  1017. end;
  1018. FreeEnvironmentStringsA(p);
  1019. end;
  1020. Function GetEnvironmentVariable(Const EnvVar : UnicodeString) : UnicodeString;
  1021. var
  1022. s, upperenv : Unicodestring;
  1023. i : longint;
  1024. hp,p : pwidechar;
  1025. begin
  1026. Result:='';
  1027. p:=GetEnvironmentStringsW;
  1028. hp:=p;
  1029. upperenv:=uppercase(envvar);
  1030. while hp^<>#0 do
  1031. begin
  1032. s:=hp;
  1033. i:=pos('=',s);
  1034. if uppercase(copy(s,1,i-1))=upperenv then
  1035. begin
  1036. Result:=copy(s,i+1,length(s)-i);
  1037. break;
  1038. end;
  1039. { next string entry}
  1040. hp:=hp+strlen(hp)+1;
  1041. end;
  1042. FreeEnvironmentStringsW(p);
  1043. end;
  1044. Function GetEnvironmentVariableCount : Integer;
  1045. var
  1046. hp,p : pchar;
  1047. begin
  1048. Result:=0;
  1049. p:=GetEnvironmentStringsA;
  1050. hp:=p;
  1051. If (Hp<>Nil) then
  1052. while hp^<>#0 do
  1053. begin
  1054. Inc(Result);
  1055. hp:=hp+strlen(hp)+1;
  1056. end;
  1057. FreeEnvironmentStringsA(p);
  1058. end;
  1059. Function GetEnvironmentString(Index : Integer) : {$ifdef FPC_RTL_UNICODE}UnicodeString{$else}AnsiString{$endif};
  1060. var
  1061. hp,p : pchar;
  1062. {$ifdef FPC_RTL_UNICODE}
  1063. tmpstr : RawByteString;
  1064. {$endif}
  1065. begin
  1066. Result:='';
  1067. p:=GetEnvironmentStringsA;
  1068. hp:=p;
  1069. If (Hp<>Nil) then
  1070. begin
  1071. while (hp^<>#0) and (Index>1) do
  1072. begin
  1073. Dec(Index);
  1074. hp:=hp+strlen(hp)+1;
  1075. end;
  1076. If (hp^<>#0) then
  1077. begin
  1078. {$ifdef FPC_RTL_UNICODE}
  1079. tmpstr:=hp;
  1080. SetCodePage(tmpstr,CP_OEMCP,false);
  1081. Result:=tmpstr;
  1082. {$else}
  1083. Result:=hp;
  1084. SetCodePage(RawByteString(Result),CP_OEMCP,false);
  1085. {$endif}
  1086. end;
  1087. end;
  1088. FreeEnvironmentStringsA(p);
  1089. end;
  1090. {$pop}
  1091. function ExecuteProcess(Const Path: RawByteString; Const ComLine: RawByteString;Flags:TExecuteFlags=[]):integer;
  1092. begin
  1093. result:=ExecuteProcess(Unicodestring(Path),UnicodeString(ComLine),Flags);
  1094. end;
  1095. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: UnicodeString;Flags:TExecuteFlags=[]):integer;
  1096. // win specific function
  1097. var
  1098. SI: TStartupInfoW;
  1099. PI: TProcessInformation;
  1100. Proc : THandle;
  1101. l : DWord;
  1102. CommandLine : unicodestring;
  1103. e : EOSError;
  1104. ExecInherits : longbool;
  1105. begin
  1106. FillChar(SI, SizeOf(SI), 0);
  1107. SI.cb:=SizeOf(SI);
  1108. SI.wShowWindow:=1;
  1109. { always surround the name of the application by quotes
  1110. so that long filenames will always be accepted. But don't
  1111. do it if there are already double quotes, since Win32 does not
  1112. like double quotes which are duplicated!
  1113. }
  1114. if pos('"',path)=0 then
  1115. CommandLine:='"'+path+'"'
  1116. else
  1117. CommandLine:=path;
  1118. if ComLine <> '' then
  1119. CommandLine:=Commandline+' '+ComLine+#0
  1120. else
  1121. CommandLine := CommandLine + #0;
  1122. ExecInherits:=ExecInheritsHandles in Flags;
  1123. if not CreateProcessW(nil, pwidechar(CommandLine),
  1124. Nil, Nil, ExecInherits,$20, Nil, Nil, SI, PI) then
  1125. begin
  1126. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  1127. e.ErrorCode:=GetLastError;
  1128. raise e;
  1129. end;
  1130. Proc:=PI.hProcess;
  1131. if WaitForSingleObject(Proc, dword($ffffffff)) <> $ffffffff then
  1132. begin
  1133. GetExitCodeProcess(Proc,l);
  1134. CloseHandle(Proc);
  1135. CloseHandle(PI.hThread);
  1136. result:=l;
  1137. end
  1138. else
  1139. begin
  1140. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  1141. e.ErrorCode:=GetLastError;
  1142. CloseHandle(Proc);
  1143. CloseHandle(PI.hThread);
  1144. raise e;
  1145. end;
  1146. end;
  1147. function ExecuteProcess(Const Path: RawByteString; Const ComLine: Array of RawByteString;Flags:TExecuteFlags=[]):integer;
  1148. var
  1149. CommandLine: UnicodeString;
  1150. I: integer;
  1151. begin
  1152. Commandline := '';
  1153. for I := 0 to High (ComLine) do
  1154. if Pos (' ', ComLine [I]) <> 0 then
  1155. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  1156. else
  1157. CommandLine := CommandLine + ' ' + Comline [I];
  1158. ExecuteProcess := ExecuteProcess (UnicodeString(Path), CommandLine,Flags);
  1159. end;
  1160. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: Array of UnicodeString;Flags:TExecuteFlags=[]):integer;
  1161. var
  1162. CommandLine: UnicodeString;
  1163. I: integer;
  1164. begin
  1165. Commandline := '';
  1166. for I := 0 to High (ComLine) do
  1167. if Pos (' ', ComLine [I]) <> 0 then
  1168. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  1169. else
  1170. CommandLine := CommandLine + ' ' + Comline [I];
  1171. ExecuteProcess := ExecuteProcess (Path,CommandLine,Flags);
  1172. end;
  1173. Procedure Sleep(Milliseconds : Cardinal);
  1174. begin
  1175. Windows.Sleep(MilliSeconds)
  1176. end;
  1177. Function GetLastOSError : Integer;
  1178. begin
  1179. Result:=GetLastError;
  1180. end;
  1181. {****************************************************************************
  1182. Initialization code
  1183. ****************************************************************************}
  1184. var
  1185. kernel32dll : THandle;
  1186. Procedure LoadVersionInfo;
  1187. // and getfreespaceex
  1188. Var
  1189. versioninfo : TOSVERSIONINFO;
  1190. begin
  1191. GetDiskFreeSpaceEx:=nil;
  1192. versioninfo.dwOSVersionInfoSize:=sizeof(versioninfo);
  1193. GetVersionEx(versioninfo);
  1194. Win32Platform:=versionInfo.dwPlatformId;
  1195. Win32MajorVersion:=versionInfo.dwMajorVersion;
  1196. Win32MinorVersion:=versionInfo.dwMinorVersion;
  1197. Win32BuildNumber:=versionInfo.dwBuildNumber;
  1198. Move (versioninfo.szCSDVersion ,Win32CSDVersion[1],128);
  1199. win32CSDVersion[0]:=chr(strlen(pchar(@versioninfo.szCSDVersion)));
  1200. kernel32dll:=GetModuleHandle('kernel32');
  1201. if kernel32dll<>0 then
  1202. GetDiskFreeSpaceEx:=TGetDiskFreeSpaceEx(GetProcAddress(kernel32dll,'GetDiskFreeSpaceExA'));
  1203. if Win32MajorVersion<6 then
  1204. FindExInfoDefaults := FindExInfoStandard; // also searches SFNs. XP only.
  1205. if (Win32MajorVersion>=6) and (Win32MinorVersion>=1) then
  1206. FindFirstAdditionalFlags := FIND_FIRST_EX_LARGE_FETCH; // win7 and 2008R2+
  1207. end;
  1208. Function GetAppConfigDir(Global : Boolean) : String;
  1209. begin
  1210. If Global then
  1211. Result:=GetWindowsSpecialDir(CSIDL_COMMON_APPDATA)
  1212. else
  1213. Result:=GetWindowsSpecialDir(CSIDL_LOCAL_APPDATA);
  1214. If (Result<>'') then
  1215. begin
  1216. if VendorName<>'' then
  1217. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1218. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1219. end
  1220. else
  1221. Result:=IncludeTrailingPathDelimiter(DGetAppConfigDir(Global));
  1222. end;
  1223. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  1224. begin
  1225. result:=DGetAppConfigFile(Global,SubDir);
  1226. end;
  1227. Function GetUserDir : String;
  1228. begin
  1229. Result:=GetWindowsSpecialDir(CSIDL_PROFILE);
  1230. end;
  1231. Procedure InitSysConfigDir;
  1232. begin
  1233. SetLength(SysConfigDir, MAX_PATH);
  1234. SetLength(SysConfigDir, GetWindowsDirectoryA(PChar(SysConfigDir), MAX_PATH));
  1235. end;
  1236. {****************************************************************************
  1237. Target Dependent WideString stuff
  1238. ****************************************************************************}
  1239. { This is the case of Win9x. Limited to current locale of course, but it's better
  1240. than not working at all. }
  1241. function DoCompareStringA(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1242. var
  1243. a1, a2: AnsiString;
  1244. begin
  1245. if L1>0 then
  1246. widestringmanager.Wide2AnsiMoveProc(P1,a1,DefaultSystemCodePage,L1);
  1247. if L2>0 then
  1248. widestringmanager.Wide2AnsiMoveProc(P2,a2,DefaultSystemCodePage,L2);
  1249. SetLastError(0);
  1250. Result:=CompareStringA(LOCALE_USER_DEFAULT,Flags,pchar(a1),
  1251. length(a1),pchar(a2),length(a2))-2;
  1252. end;
  1253. function DoCompareStringW(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1254. begin
  1255. SetLastError(0);
  1256. Result:=CompareStringW(LOCALE_USER_DEFAULT,Flags,P1,L1,P2,L2)-2;
  1257. if GetLastError=0 then
  1258. Exit;
  1259. if GetLastError=ERROR_CALL_NOT_IMPLEMENTED then // Win9x case
  1260. Result:=DoCompareStringA(P1, P2, L1, L2, Flags);
  1261. if GetLastError<>0 then
  1262. RaiseLastOSError;
  1263. end;
  1264. const
  1265. WinAPICompareFlags : array [TCompareOption] of LongWord
  1266. = ({LINGUISTIC_IGNORECASE, LINGUISTIC_IGNOREDIACRITIC, }NORM_IGNORECASE{,
  1267. NORM_IGNOREKANATYPE, NORM_IGNORENONSPACE, NORM_IGNORESYMBOLS, NORM_IGNOREWIDTH,
  1268. NORM_LINGUISTIC_CASING, SORT_DIGITSASNUMBERS, SORT_STRINGSORT});
  1269. function Win32CompareWideString(const s1, s2 : WideString; Options : TCompareOptions) : PtrInt;
  1270. Var
  1271. O : LongWord;
  1272. CO : TCompareOption;
  1273. begin
  1274. O:=0;
  1275. for CO in TCompareOption do
  1276. if CO in Options then
  1277. O:=O or WinAPICompareFlags[CO];
  1278. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), O);
  1279. end;
  1280. function Win32CompareTextWideString(const s1, s2 : WideString) : PtrInt;
  1281. begin
  1282. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1283. end;
  1284. function Win32AnsiUpperCase(const s: string): string;
  1285. begin
  1286. if length(s)>0 then
  1287. begin
  1288. result:=s;
  1289. UniqueString(result);
  1290. CharUpperBuffA(pchar(result),length(result));
  1291. end
  1292. else
  1293. result:='';
  1294. end;
  1295. function Win32AnsiLowerCase(const s: string): string;
  1296. begin
  1297. if length(s)>0 then
  1298. begin
  1299. result:=s;
  1300. UniqueString(result);
  1301. CharLowerBuffA(pchar(result),length(result));
  1302. end
  1303. else
  1304. result:='';
  1305. end;
  1306. function Win32AnsiCompareStr(const S1, S2: string): PtrInt;
  1307. begin
  1308. result:=CompareStringA(LOCALE_USER_DEFAULT,0,pchar(s1),length(s1),
  1309. pchar(s2),length(s2))-2;
  1310. end;
  1311. function Win32AnsiCompareText(const S1, S2: string): PtrInt;
  1312. begin
  1313. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,pchar(s1),length(s1),
  1314. pchar(s2),length(s2))-2;
  1315. end;
  1316. function Win32AnsiStrComp(S1, S2: PChar): PtrInt;
  1317. begin
  1318. result:=CompareStringA(LOCALE_USER_DEFAULT,0,s1,-1,s2,-1)-2;
  1319. end;
  1320. function Win32AnsiStrIComp(S1, S2: PChar): PtrInt;
  1321. begin
  1322. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,-1,s2,-1)-2;
  1323. end;
  1324. function Win32AnsiStrLComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1325. begin
  1326. result:=CompareStringA(LOCALE_USER_DEFAULT,0,s1,maxlen,s2,maxlen)-2;
  1327. end;
  1328. function Win32AnsiStrLIComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1329. begin
  1330. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,maxlen,s2,maxlen)-2;
  1331. end;
  1332. function Win32AnsiStrLower(Str: PChar): PChar;
  1333. begin
  1334. CharLowerA(str);
  1335. result:=str;
  1336. end;
  1337. function Win32AnsiStrUpper(Str: PChar): PChar;
  1338. begin
  1339. CharUpperA(str);
  1340. result:=str;
  1341. end;
  1342. function Win32CompareUnicodeString(const s1, s2 : UnicodeString; Options : TCompareOptions) : PtrInt;
  1343. Var
  1344. O : LongWord;
  1345. CO : TCompareOption;
  1346. begin
  1347. O:=0;
  1348. for CO in TCompareOption do
  1349. if CO in Options then
  1350. O:=O or WinAPICompareFlags[CO];
  1351. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), O);
  1352. end;
  1353. function Win32CompareTextUnicodeString(const s1, s2 : UnicodeString) : PtrInt;
  1354. begin
  1355. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1356. end;
  1357. { there is a similiar procedure in the system unit which inits the fields which
  1358. are relevant already for the system unit }
  1359. procedure InitWin32Widestrings;
  1360. begin
  1361. { return value: number of code points in the string. Whenever an invalid
  1362. code point is encountered, all characters part of this invalid code point
  1363. are considered to form one "character" and the next character is
  1364. considered to be the start of a new (possibly also invalid) code point }
  1365. //!!! CharLengthPCharProc : function(const Str: PChar): PtrInt;
  1366. { return value:
  1367. -1 if incomplete or invalid code point
  1368. 0 if NULL character,
  1369. > 0 if that's the length in bytes of the code point }
  1370. //!!!! CodePointLengthProc : function(const Str: PChar; MaxLookAead: PtrInt): Ptrint;
  1371. widestringmanager.CompareWideStringProc:=@Win32CompareWideString;
  1372. widestringmanager.UpperAnsiStringProc:=@Win32AnsiUpperCase;
  1373. widestringmanager.LowerAnsiStringProc:=@Win32AnsiLowerCase;
  1374. widestringmanager.CompareStrAnsiStringProc:=@Win32AnsiCompareStr;
  1375. widestringmanager.CompareTextAnsiStringProc:=@Win32AnsiCompareText;
  1376. widestringmanager.StrCompAnsiStringProc:=@Win32AnsiStrComp;
  1377. widestringmanager.StrICompAnsiStringProc:=@Win32AnsiStrIComp;
  1378. widestringmanager.StrLCompAnsiStringProc:=@Win32AnsiStrLComp;
  1379. widestringmanager.StrLICompAnsiStringProc:=@Win32AnsiStrLIComp;
  1380. widestringmanager.StrLowerAnsiStringProc:=@Win32AnsiStrLower;
  1381. widestringmanager.StrUpperAnsiStringProc:=@Win32AnsiStrUpper;
  1382. widestringmanager.CompareUnicodeStringProc:=@Win32CompareUnicodeString;
  1383. end;
  1384. { Platform-specific exception support }
  1385. function WinExceptionObject(code: Longint; const rec: TExceptionRecord): Exception;
  1386. var
  1387. entry: PExceptMapEntry;
  1388. begin
  1389. entry := FindExceptMapEntry(code);
  1390. if assigned(entry) then
  1391. result:=entry^.cls.CreateRes(entry^.msg)
  1392. else
  1393. result:=EExternalException.CreateResFmt(@SExternalException,[rec.ExceptionCode]);
  1394. if result is EExternal then
  1395. EExternal(result).FExceptionRecord:=rec;
  1396. end;
  1397. function WinExceptionClass(code: longint): ExceptClass;
  1398. var
  1399. entry: PExceptMapEntry;
  1400. begin
  1401. entry := FindExceptMapEntry(code);
  1402. if assigned(entry) then
  1403. result:=entry^.cls
  1404. else
  1405. result:=EExternalException;
  1406. end;
  1407. Initialization
  1408. InitWin32Widestrings;
  1409. InitExceptions; { Initialize exceptions. OS independent }
  1410. {$ifdef mswindows} { Keeps exe size down for systems that do not use SEH }
  1411. ExceptObjProc:=@WinExceptionObject;
  1412. ExceptClsProc:=@WinExceptionClass;
  1413. {$endif mswindows}
  1414. InitLeadBytes;
  1415. InitInternational; { Initialize internationalization settings }
  1416. LoadVersionInfo;
  1417. InitSysConfigDir;
  1418. OnBeep:=@SysBeep;
  1419. Finalization
  1420. DoneExceptions;
  1421. FreeTerminateProcs;
  1422. end.