sysutils.inc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. **********************************************************************}
  11. {$macro on}
  12. {$define PathStr:=UnicodeString}
  13. {$define PathPChar:=PWideChar}
  14. { Read filename handling functions implementation }
  15. {$i fina.inc}
  16. {$define PathStr:=AnsiString}
  17. {$define PathPChar:=PAnsiChar}
  18. { Read filename handling functions implementation }
  19. {$i fina.inc}
  20. {$undef PathStr}
  21. {$undef PathPChar}
  22. { Read file utility functions implementation }
  23. {$i filutil.inc}
  24. { variant error codes }
  25. {$i varerror.inc}
  26. Function FileSearch (Const Name, DirList : String; Options : TFileSearchoptions = [sfoImplicitCurrentDir]) : String;
  27. Var
  28. I : longint;
  29. Temp : String;
  30. begin
  31. Result:=Name;
  32. temp:=SetDirSeparators(DirList);
  33. // Start with checking the file in the current directory
  34. If (sfoImplicitCurrentDir in Options) and (Result <> '') and FileExists(Result) Then
  35. exit;
  36. while True do begin
  37. If Temp = '' then
  38. Break; // No more directories to search - fail
  39. I:=pos(PathSeparator,Temp);
  40. If I<>0 then
  41. begin
  42. Result:=Copy (Temp,1,i-1);
  43. system.Delete(Temp,1,I);
  44. end
  45. else
  46. begin
  47. Result:=Temp;
  48. Temp:='';
  49. end;
  50. If Result<>'' then
  51. begin
  52. If (sfoStripQuotes in Options) and (Result[1]='"') and (Result[Length(Result)]='"') then
  53. Result:=Copy(Result,2,Length(Result)-2);
  54. if (Result<>'') then
  55. Result:=IncludeTrailingPathDelimiter(Result)+name;
  56. end;
  57. If (Result <> '') and FileExists(Result) Then
  58. exit;
  59. end;
  60. result:='';
  61. end;
  62. Function FileSearch (Const Name, DirList : String; ImplicitCurrentDir : Boolean) : String;
  63. begin
  64. if ImplicitCurrentDir then
  65. Result:=FileSearch(Name,DirList,[sfoImplicitCurrentDir])
  66. else
  67. Result:=FileSearch(Name,DirList,[]);
  68. end;
  69. Function ExeSearch (Const Name : String; Const DirList : String ='' ) : String;
  70. Var
  71. D : String;
  72. O : TFileSearchOptions;
  73. begin
  74. D:=DirList;
  75. if (D='') then
  76. D:=GetEnvironmentVariable('PATH');
  77. {$ifdef unix}
  78. O:=[];
  79. {$else unix}
  80. O:=[sfoImplicitCurrentDir,sfoStripQuotes];
  81. {$endif unix}
  82. Result := FileSearch(Name, D, O);
  83. end;
  84. {$ifndef OS_FILEISREADONLY}
  85. Function FileIsReadOnly(const FileName: String): Boolean;
  86. begin
  87. Result := (FileGetAttr(FileName) and faReadOnly) <> 0;
  88. end;
  89. {$endif OS_FILEISREADONLY}
  90. {$ifndef OS_FILESETDATEBYNAME}
  91. Function FileSetDate (Const FileName : String;Age : Longint) : Longint;
  92. Var
  93. fd : THandle;
  94. begin
  95. { at least windows requires fmOpenWrite here }
  96. fd:=FileOpen(FileName,fmOpenWrite);
  97. If (Fd<>feInvalidHandle) then
  98. try
  99. Result:=FileSetDate(fd,Age);
  100. finally
  101. FileClose(fd);
  102. end
  103. else
  104. {$ifdef HAS_OSERROR}
  105. Result:=GetLastOSError;
  106. {$else}
  107. Result:=-1;
  108. {$endif}
  109. end;
  110. {$endif}
  111. { Read String Handling functions implementation }
  112. {$i sysstr.inc}
  113. { Read date & Time function implementations }
  114. {$ifndef FPUNONE}
  115. {$i dati.inc}
  116. {$endif}
  117. {$IFNDEF HAS_GETTICKCOUNT}
  118. function GetTickCount: LongWord;
  119. begin
  120. Result := LongWord(GetTickCount64);
  121. end;
  122. {$ENDIF}
  123. {$IFNDEF HAS_GETTICKCOUNT64}
  124. function GetTickCount64: QWord;
  125. begin
  126. {$IFDEF FPU_NONE}
  127. {$IFDEF HAS_SYSTIMERTICK}
  128. Result := SysTimerTick;
  129. {$ELSE}
  130. Result := 0;
  131. {$ENDIF}
  132. {$ELSE}
  133. Result := Trunc(Now * 24 * 60 * 60 * 1000);
  134. {$ENDIF}
  135. end;
  136. {$ENDIF}
  137. { Read pchar handling functions implementation }
  138. {$i syspch.inc}
  139. { generic internationalisation code }
  140. {$i sysint.inc}
  141. { MCBS functions }
  142. {$i sysansi.inc}
  143. {$i syscodepages.inc}
  144. { wide string functions }
  145. {$i syswide.inc}
  146. {$ifdef FPC_HAS_UNICODESTRING}
  147. { unicode string functions }
  148. {$i sysuni.inc}
  149. {$i sysencoding.inc}
  150. {$endif FPC_HAS_UNICODESTRING}
  151. { threading stuff }
  152. {$i sysuthrd.inc}
  153. { OS utility code }
  154. {$i osutil.inc}
  155. procedure FreeAndNil(var obj);
  156. var
  157. temp: tobject;
  158. begin
  159. temp:=tobject(obj);
  160. pointer(obj):=nil;
  161. temp.free;
  162. end;
  163. function FileAge(const FileName: string; out FileDateTime: TDateTime; FollowLink: Boolean = True): Boolean;
  164. Var
  165. Info : TSearchRec;
  166. A : Integer;
  167. begin
  168. for A:=1 to Length(FileName) do
  169. If (FileName[A] in ['?','*']) then
  170. Exit(False);
  171. A:=0;
  172. if Not FollowLink then
  173. A:=A or faSymLink;
  174. Result:=FindFirst(FileName,A,Info)=0;
  175. If Result then
  176. FileDateTime:=FileDatetoDateTime (Info.Time);
  177. FindClose(Info);
  178. end;
  179. { Interfaces support }
  180. {$i sysuintf.inc}
  181. constructor Exception.Create(const msg : string);
  182. begin
  183. inherited create;
  184. fmessage:=msg;
  185. end;
  186. constructor Exception.CreateFmt(const msg : string; const args : array of const);
  187. begin
  188. inherited create;
  189. fmessage:=Format(msg,args);
  190. end;
  191. constructor Exception.CreateRes(ResString: PString);
  192. begin
  193. inherited create;
  194. fmessage:=ResString^;
  195. end;
  196. constructor Exception.CreateResFmt(ResString: PString; const Args: array of const);
  197. begin
  198. inherited create;
  199. fmessage:=Format(ResString^,args);
  200. end;
  201. constructor Exception.CreateHelp(const Msg: string; AHelpContext: Integer);
  202. begin
  203. inherited create;
  204. fmessage:=Msg;
  205. fhelpcontext:=AHelpContext;
  206. end;
  207. constructor Exception.CreateFmtHelp(const Msg: string; const Args: array of const;
  208. AHelpContext: Integer);
  209. begin
  210. inherited create;
  211. fmessage:=Format(Msg,args);
  212. fhelpcontext:=AHelpContext;
  213. end;
  214. constructor Exception.CreateResHelp(ResString: PString; AHelpContext: Integer);
  215. begin
  216. inherited create;
  217. fmessage:=ResString^;
  218. fhelpcontext:=AHelpContext;
  219. end;
  220. constructor Exception.CreateResFmtHelp(ResString: PString; const Args: array of const;
  221. AHelpContext: Integer);
  222. begin
  223. inherited create;
  224. fmessage:=Format(ResString^,args);
  225. fhelpcontext:=AHelpContext;
  226. end;
  227. procedure EHeapMemoryError.FreeInstance;
  228. begin
  229. if AllowFree then
  230. inherited FreeInstance;
  231. end;
  232. Constructor EVariantError.CreateCode (Code : longint);
  233. begin
  234. case Code of
  235. VAR_OK:
  236. Create(SNoError);
  237. VAR_PARAMNOTFOUND:
  238. Create(SVarParamNotFound);
  239. VAR_TYPEMISMATCH:
  240. Create(SInvalidVarCast);
  241. VAR_BADVARTYPE:
  242. Create(SVarBadType);
  243. VAR_OVERFLOW:
  244. Create(SVarOverflow);
  245. VAR_BADINDEX:
  246. Create(SVarArrayBounds);
  247. VAR_ARRAYISLOCKED:
  248. Create(SVarArrayLocked);
  249. VAR_NOTIMPL:
  250. Create(SVarNotImplemented);
  251. VAR_OUTOFMEMORY:
  252. Create(SVarOutOfMemory);
  253. VAR_INVALIDARG:
  254. Create(SVarInvalid);
  255. VAR_UNEXPECTED,
  256. VAR_EXCEPTION:
  257. Create(SVarUnexpected);
  258. else
  259. CreateFmt(SUnknownErrorCode,[Code]);
  260. end;
  261. ErrCode:=Code;
  262. end;
  263. {$ifdef windows}
  264. function EExternal.GetExceptionRecord: PExceptionRecord;
  265. begin
  266. result:=@FExceptionRecord;
  267. end;
  268. {$endif windows}
  269. {$push}
  270. {$S-}
  271. Procedure CatchUnhandledException (Obj : TObject; Addr: Pointer; FrameCount: Longint; Frames: PPointer);[public,alias:'FPC_BREAK_UNHANDLED_EXCEPTION'];
  272. Var
  273. i : longint;
  274. hstdout : ^text;
  275. begin
  276. hstdout:=@stdout;
  277. Writeln(hstdout^,'An unhandled exception occurred at $',HexStr(Addr),':');
  278. if Obj is exception then
  279. Writeln(hstdout^,Obj.ClassName,': ',Exception(Obj).Message)
  280. else
  281. Writeln(hstdout^,'Exception object ',Obj.ClassName,' is not of class Exception.');
  282. Writeln(hstdout^,BackTraceStrFunc(Addr));
  283. if (FrameCount>0) then
  284. begin
  285. for i:=0 to FrameCount-1 do
  286. Writeln(hstdout^,BackTraceStrFunc(Frames[i]));
  287. end;
  288. Writeln(hstdout^,'');
  289. end;
  290. type
  291. PExceptMapEntry=^TExceptMapEntry;
  292. TExceptMapEntry=record
  293. code: byte;
  294. cls: ExceptClass;
  295. {$IFDEF FPC_HAS_FEATURE_RESOURCES} // This is necessary for 2.4.4, which does not have reasources as a separate feature
  296. msg: PResStringRec;
  297. {$else FPC_HAS_FEATURE_RESOURCES}
  298. msg: PString;
  299. {$endif FPC_HAS_FEATURE_RESOURCES}
  300. end;
  301. const
  302. exceptmap: array[0..28] of TExceptMapEntry = (
  303. (code: 200; cls: EDivByZero; msg: @SDivByZero),
  304. (code: 201; cls: ERangeError; msg: @SRangeError),
  305. (code: 202; cls: EStackOverflow; msg: @SStackOverflow),
  306. (code: 205; cls: EOverflow; msg: @SOverflow),
  307. (code: 206; cls: EUnderflow; msg: @SUnderflow),
  308. (code: 207; cls: EInvalidOp; msg: @SInvalidOp),
  309. { Delphi distinguishes reDivByZero from reZeroDivide, but maps both to code 200. }
  310. (code: 208; cls: EZeroDivide; msg: @SZeroDivide),
  311. (code: 210; cls: EObjectCheck; msg: @SObjectCheckError),
  312. (code: 211; cls: EAbstractError; msg: @SAbstractError),
  313. (code: 212; cls: EExternalException; msg: @SExternalException),
  314. (code: 214; cls: EBusError; msg: @SBusError),
  315. (code: 215; cls: EIntOverflow; msg: @SIntOverflow),
  316. (code: 216; cls: EAccessViolation; msg: @SAccessViolation),
  317. (code: 217; cls: EControlC; msg: @SControlC),
  318. (code: 218; cls: EPrivilege; msg: @SPrivilege),
  319. (code: 219; cls: EInvalidCast; msg: @SInvalidCast),
  320. (code: 220; cls: EVariantError; msg: @SInvalidVarCast),
  321. (code: 221; cls: EVariantError; msg: @SInvalidVarOp),
  322. (code: 222; cls: EVariantError; msg: @SDispatchError),
  323. (code: 223; cls: EVariantError; msg: @SVarArrayCreate),
  324. (code: 224; cls: EVariantError; msg: @SVarNotArray),
  325. (code: 225; cls: EVariantError; msg: @SVarArrayBounds),
  326. (code: 227; cls: EAssertionFailed; msg: @SAssertionFailed),
  327. (code: 228; cls: EIntfCastError; msg: @SIntfCastError),
  328. (code: 229; cls: ESafecallException; msg: @SSafecallException),
  329. (code: 231; cls: EConvertError; msg: @SiconvError),
  330. (code: 232; cls: ENoThreadSupport; msg: @SNoThreadSupport),
  331. (code: 233; cls: ENoWideStringSupport; msg: @SSigQuit),
  332. (code: 234; cls: ENoWideStringSupport; msg: @SMissingWStringManager)
  333. );
  334. function FindExceptMapEntry(err: longint): PExceptMapEntry;
  335. var
  336. i: longint;
  337. begin
  338. for i:=low(exceptmap) to high(exceptmap) do
  339. if err=exceptmap[i].code then
  340. begin
  341. result:=@exceptmap[i];
  342. exit;
  343. end;
  344. result:=nil;
  345. end;
  346. Var OutOfMemory : EOutOfMemory;
  347. InValidPointer : EInvalidPointer;
  348. Procedure RunErrorToExcept (ErrNo : Longint; Address,Frame : Pointer);
  349. var
  350. E: Exception;
  351. HS: PString;
  352. Entry: PExceptMapEntry;
  353. begin
  354. Case Errno of
  355. 1,203 : E:=OutOfMemory;
  356. 204 : E:=InvalidPointer;
  357. else
  358. Entry:=FindExceptMapEntry(ErrNo);
  359. if Assigned(Entry) then
  360. E:=Entry^.cls.CreateRes(Entry^.msg)
  361. else
  362. begin
  363. HS:=nil;
  364. Case Errno of
  365. 2 : HS:=@SFileNotFound;
  366. 3 : HS:=@SInvalidFileName;
  367. 4 : HS:=@STooManyOpenFiles;
  368. 5 : HS:=@SAccessDenied;
  369. 6 : HS:=@SInvalidFileHandle;
  370. 15 : HS:=@SInvalidDrive;
  371. 100 : HS:=@SEndOfFile;
  372. 101 : HS:=@SDiskFull;
  373. 102 : HS:=@SFileNotAssigned;
  374. 103 : HS:=@SFileNotOpen;
  375. 104 : HS:=@SFileNotOpenForInput;
  376. 105 : HS:=@SFileNotOpenForOutput;
  377. 106 : HS:=@SInvalidInput;
  378. end;
  379. if Assigned(HS) then
  380. E:=EInOutError.CreateRes(HS)
  381. else
  382. E:=EInOutError.CreateResFmt(@SUnknownRunTimeError,[errno]);
  383. // this routine can be called from FPC_IOCHECK,
  384. // which clears inoutres and then passes its
  385. // original value to HandleErrorFrame() (which calls
  386. // us). So use errno rather than IOResult, and clear
  387. // InOutRes explicitly in case we can also be called
  388. // from a place that does not clear InOutRes explicitly
  389. EInoutError(E).ErrorCode:=errno;
  390. inoutres:=0;
  391. end;
  392. end;
  393. Raise E at Address,Frame;
  394. end;
  395. {$IFDEF HAS_OSERROR}
  396. Procedure RaiseLastOSError;overload;
  397. begin
  398. RaiseLastOSError(GetLastOSError);
  399. end;
  400. Procedure RaiseLastOSError(LastError: Integer);overload;
  401. var
  402. E : EOSError;
  403. begin
  404. If (LastError<>0) then
  405. E:=EOSError.CreateFmt(SOSError, [LastError, SysErrorMessage(LastError)])
  406. else
  407. E:=EOSError.Create(SUnkOSError);
  408. E.ErrorCode:=LastError;
  409. Raise E;
  410. end;
  411. {$else}
  412. Procedure RaiseLastOSError;overload;
  413. begin
  414. Raise Exception.Create('RaiseLastOSError not implemented on this platform.');
  415. end;
  416. Procedure RaiseLastOSError(LastError: Integer);overload;
  417. begin
  418. RaiseLastOSError;
  419. end;
  420. {$endif}
  421. Procedure AssertErrorHandler (Const Msg,FN : ShortString;LineNo:longint; TheAddr : pointer);
  422. Var
  423. S : String;
  424. begin
  425. If Msg='' then
  426. S:=SAssertionFailed
  427. else
  428. S:=Msg;
  429. Raise EAssertionFailed.Createfmt(SAssertError,[S,Fn,LineNo]) at get_caller_addr(theAddr), get_caller_frame(theAddr);
  430. end;
  431. {$pop} //{$S-} for Error handling functions
  432. Procedure InitExceptions;
  433. {
  434. Must install uncaught exception handler (ExceptProc)
  435. and install exceptions for system exceptions or signals.
  436. (e.g: SIGSEGV -> ESegFault or so.)
  437. }
  438. begin
  439. ExceptionClass := Exception;
  440. ExceptProc:=@CatchUnhandledException;
  441. // Create objects that may have problems when there is no memory.
  442. OutOfMemory:=EOutOfMemory.Create(SOutOfMemory);
  443. OutOfMemory.AllowFree:=false;
  444. InvalidPointer:=EInvalidPointer.Create(SInvalidPointer);
  445. InvalidPointer.AllowFree:=false;
  446. AssertErrorProc:=@AssertErrorHandler;
  447. ErrorProc:=@RunErrorToExcept;
  448. OnShowException:=Nil;
  449. end;
  450. Procedure DoneExceptions;
  451. begin
  452. OutOfMemory.AllowFree:=true;
  453. OutOfMemory.Free;
  454. InValidPointer.AllowFree:=true;
  455. InValidPointer.Free;
  456. end;
  457. { Exception handling routines }
  458. function ExceptObject: TObject;
  459. begin
  460. If RaiseList=Nil then
  461. Result:=Nil
  462. else
  463. Result:=RaiseList^.FObject;
  464. end;
  465. function ExceptAddr: Pointer;
  466. begin
  467. If RaiseList=Nil then
  468. Result:=Nil
  469. else
  470. Result:=RaiseList^.Addr;
  471. end;
  472. function ExceptFrameCount: Longint;
  473. begin
  474. If RaiseList=Nil then
  475. Result:=0
  476. else
  477. Result:=RaiseList^.Framecount;
  478. end;
  479. function ExceptFrames: PPointer;
  480. begin
  481. If RaiseList=Nil then
  482. Result:=Nil
  483. else
  484. Result:=RaiseList^.Frames;
  485. end;
  486. function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
  487. Buffer: PChar; Size: Integer): Integer;
  488. Var
  489. S : AnsiString;
  490. Len : Integer;
  491. begin
  492. S:=Format(SExceptionErrorMessage,[ExceptAddr,ExceptObject.ClassName]);
  493. If ExceptObject is Exception then
  494. S:=Format('%s:'#10'%s',[S,Exception(ExceptObject).Message]);
  495. Len:=Length(S);
  496. If S[Len]<>'.' then
  497. begin
  498. S:=S+'.';
  499. Inc(len);
  500. end;
  501. If Len>Size then
  502. Len:=Size;
  503. if Len > 0 then
  504. Move(S[1],Buffer^,Len);
  505. Result:=Len;
  506. end;
  507. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  508. // use shortstring. On exception, the heap may be corrupt.
  509. Var
  510. Buf : ShortString;
  511. begin
  512. SetLength(Buf,ExceptionErrorMessage(ExceptObject,ExceptAddr,@Buf[1],255));
  513. If IsConsole Then
  514. writeln(Buf)
  515. else
  516. If Assigned(OnShowException) Then
  517. OnShowException (Buf);
  518. end;
  519. procedure Abort;
  520. begin
  521. Raise EAbort.Create(SAbortError) at Pointer(Get_Caller_addr(Get_Frame));
  522. end;
  523. procedure OutOfMemoryError;
  524. begin
  525. Raise OutOfMemory;
  526. end;
  527. { ---------------------------------------------------------------------
  528. Initialization/Finalization/exit code
  529. ---------------------------------------------------------------------}
  530. Type
  531. PPRecord = ^TPRecord;
  532. TPRecord = Record
  533. Func : TTerminateProc;
  534. NextFunc : PPRecord;
  535. end;
  536. Const
  537. TPList : PPRecord = Nil;
  538. procedure AddTerminateProc(TermProc: TTerminateProc);
  539. Var
  540. TPR : PPRecord;
  541. begin
  542. New(TPR);
  543. With TPR^ do
  544. begin
  545. NextFunc:=TPList;
  546. Func:=TermProc;
  547. end;
  548. TPList:=TPR;
  549. end;
  550. function CallTerminateProcs: Boolean;
  551. Var
  552. TPR : PPRecord;
  553. begin
  554. Result:=True;
  555. TPR:=TPList;
  556. While Result and (TPR<>Nil) do
  557. begin
  558. Result:=TPR^.Func();
  559. TPR:=TPR^.NextFunc;
  560. end;
  561. end;
  562. { ---------------------------------------------------------------------
  563. Diskh functions, OS independent.
  564. ---------------------------------------------------------------------}
  565. function ForceDirectories(Const Dir: string): Boolean;
  566. var
  567. E: EInOutError;
  568. ADrv : String;
  569. function DoForceDirectories(Const Dir: string): Boolean;
  570. var
  571. ADir : String;
  572. APath: String;
  573. begin
  574. Result:=True;
  575. ADir:=ExcludeTrailingPathDelimiter(Dir);
  576. if (ADir='') then Exit;
  577. if Not DirectoryExists(ADir) then
  578. begin
  579. APath := ExtractFilePath(ADir);
  580. //this can happen on Windows if user specifies Dir like \user\name/test/
  581. //and would, if not checked for, cause an infinite recusrsion and a stack overflow
  582. if (APath = ADir) then Result := False
  583. else Result:=DoForceDirectories(APath);
  584. If Result then
  585. Result := CreateDir(ADir);
  586. end;
  587. end;
  588. function IsUncDrive(const Drv: String): Boolean;
  589. begin
  590. Result := (Length(Drv) > 2) and (Drv[1] = PathDelim) and (Drv[2] = PathDelim);
  591. end;
  592. begin
  593. Result := False;
  594. ADrv := ExtractFileDrive(Dir);
  595. if (ADrv<>'') and (not DirectoryExists(ADrv))
  596. {$IFNDEF FORCEDIR_NO_UNC_SUPPORT} and (not IsUncDrive(ADrv)){$ENDIF} then Exit;
  597. if Dir='' then
  598. begin
  599. E:=EInOutError.Create(SCannotCreateEmptyDir);
  600. E.ErrorCode:=3;
  601. Raise E;
  602. end;
  603. Result := DoForceDirectories(SetDirSeparators(Dir));
  604. end;
  605. Var
  606. GUIDCalledRandomize : Boolean = False;
  607. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  608. Var
  609. I : Integer;
  610. P : PByte;
  611. begin
  612. P:=@Buf;
  613. If Not GUIDCalledRandomize then
  614. begin
  615. Randomize;
  616. GUIDCalledRandomize:=True;
  617. end;
  618. For I:=0 to NBytes-1 do
  619. P[i]:=Random(256);
  620. end;
  621. {$IFDEF HASCREATEGUID}
  622. Function SysCreateGUID(out GUID : TGUID) : Integer; forward;
  623. {$ENDIF}
  624. Function CreateGUID(out GUID : TGUID) : Integer;
  625. begin
  626. If Assigned(OnCreateGUID) then
  627. Result:=OnCreateGUID(GUID)
  628. else
  629. begin
  630. {$IFDEF HASCREATEGUID}
  631. Result:=SysCreateGUID(GUID);
  632. {$ELSE}
  633. GetRandomBytes(GUID,SizeOf(Guid));
  634. guid.clock_seq_hi_and_reserved:=(guid.clock_seq_hi_and_reserved and $3F) + 64;
  635. guid.time_hi_and_version :=(guid.time_hi_and_version and $0FFF)+ $4000;
  636. Result:=0;
  637. {$ENDIF}
  638. end;
  639. end;
  640. function SafeLoadLibrary(const FileName: AnsiString;
  641. ErrorMode: DWord = {$ifdef windows}SEM_NOOPENFILEERRORBOX{$else windows}0{$endif windows}): HMODULE;
  642. {$if defined(cpui386) or defined(cpux86_64)}
  643. var
  644. mode : DWord;
  645. fpucw : Word;
  646. ssecw : DWord;
  647. {$endif}
  648. begin
  649. {$if defined(win64) or defined(win32)}
  650. mode:=SetErrorMode(ErrorMode);
  651. {$endif}
  652. try
  653. {$if defined(cpui386) or defined(cpux86_64)}
  654. fpucw:=Get8087CW;
  655. {$ifdef cpui386}
  656. if has_sse_support then
  657. {$endif cpui386}
  658. ssecw:=GetSSECSR;
  659. {$endif}
  660. {$if defined(windows) or defined(win32)}
  661. Result:=LoadLibraryA(PChar(Filename));
  662. {$else}
  663. Result:=0;
  664. {$endif}
  665. finally
  666. {$if defined(cpui386) or defined(cpux86_64)}
  667. Set8087CW(fpucw);
  668. {$ifdef cpui386}
  669. if has_sse_support then
  670. {$endif cpui386}
  671. SetSSECSR(ssecw);
  672. {$endif}
  673. {$if defined(win64) or defined(win32)}
  674. SetErrorMode(mode);
  675. {$endif}
  676. end;
  677. end;
  678. function GetModuleName(Module: HMODULE): string;
  679. begin
  680. {$ifdef MSWINDOWS}
  681. SetLength(Result,MAX_PATH);
  682. SetLength(Result,GetModuleFileName(Module, Pchar(Result),Length(Result)));
  683. {$ELSE}
  684. Result:='';
  685. {$ENDIF}
  686. end;
  687. { Beep support }
  688. procedure Beep;
  689. begin
  690. If Assigned(OnBeep) then
  691. OnBeep;
  692. end;