sysutils.pp 55 KB

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