sysutils.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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. { Read filename handling functions implementation }
  12. {$i fina.inc}
  13. { variant error codes }
  14. {$i varerror.inc}
  15. Function FileSearch (Const Name, DirList : String) : String;
  16. Var
  17. I : longint;
  18. Temp : String;
  19. begin
  20. Result:='';
  21. temp:=Dirlist;
  22. repeat
  23. While (Length(Temp)>0) and (Temp[1]=PathSeparator) do
  24. Delete(Temp,1,1);
  25. I:=pos(PathSep,Temp);
  26. If I<>0 then
  27. begin
  28. Result:=Copy (Temp,1,i-1);
  29. system.Delete(Temp,1,I);
  30. end
  31. else
  32. begin
  33. Result:=Temp;
  34. Temp:='';
  35. end;
  36. If (Length(Result)>0) and (result[length(result)]<>DirectorySeparator) then
  37. Result:=Result+DirectorySeparator;
  38. Result:=Result+name;
  39. If not FileExists(Result) Then
  40. Result:='';
  41. until (length(temp)=0) or (length(result)<>0);
  42. end;
  43. {$ifndef OS_FILEISREADONLY}
  44. Function FileIsReadOnly(const FileName: String): Boolean;
  45. begin
  46. Result := (FileGetAttr(FileName) and faReadOnly) <> 0;
  47. end;
  48. {$endif OS_FILEISREADONLY}
  49. {$ifndef OS_FILESETDATEBYNAME}
  50. Function FileSetDate (Const FileName : String;Age : Longint) : Longint;
  51. Var
  52. fd : THandle;
  53. begin
  54. { at least windows requires fmOpenWrite here }
  55. fd:=FileOpen(FileName,fmOpenWrite);
  56. If (Fd<>feInvalidHandle) then
  57. try
  58. Result:=FileSetDate(fd,Age);
  59. finally
  60. FileClose(fd);
  61. end
  62. else
  63. Result:=fd;
  64. end;
  65. {$endif}
  66. { Read String Handling functions implementation }
  67. {$i sysstr.inc}
  68. { Read date & Time function implementations }
  69. {$i dati.inc}
  70. { Read pchar handling functions implementation }
  71. {$i syspch.inc}
  72. { generic internationalisation code }
  73. {$i sysint.inc}
  74. { MCBS functions }
  75. {$i sysansi.inc}
  76. { wide string functions }
  77. {$i syswide.inc}
  78. { threading stuff }
  79. {$i sysuthrd.inc}
  80. { OS utility code }
  81. {$i osutil.inc}
  82. procedure FreeAndNil(var obj);
  83. var
  84. temp: tobject;
  85. begin
  86. temp:=tobject(obj);
  87. pointer(obj):=nil;
  88. temp.free;
  89. end;
  90. { Interfaces support }
  91. {$i sysuintf.inc}
  92. constructor Exception.Create(const msg : string);
  93. begin
  94. inherited create;
  95. fmessage:=msg;
  96. end;
  97. constructor Exception.CreateFmt(const msg : string; const args : array of const);
  98. begin
  99. inherited create;
  100. fmessage:=Format(msg,args);
  101. end;
  102. constructor Exception.CreateRes(ResString: PString);
  103. begin
  104. inherited create;
  105. fmessage:=ResString^;
  106. end;
  107. constructor Exception.CreateResFmt(ResString: PString; const Args: array of const);
  108. begin
  109. inherited create;
  110. fmessage:=Format(ResString^,args);
  111. end;
  112. constructor Exception.CreateHelp(const Msg: string; AHelpContext: Integer);
  113. begin
  114. inherited create;
  115. fmessage:=Msg;
  116. fhelpcontext:=AHelpContext;
  117. end;
  118. constructor Exception.CreateFmtHelp(const Msg: string; const Args: array of const;
  119. AHelpContext: Integer);
  120. begin
  121. inherited create;
  122. fmessage:=Format(Msg,args);
  123. fhelpcontext:=AHelpContext;
  124. end;
  125. constructor Exception.CreateResHelp(ResString: PString; AHelpContext: Integer);
  126. begin
  127. inherited create;
  128. fmessage:=ResString^;
  129. fhelpcontext:=AHelpContext;
  130. end;
  131. constructor Exception.CreateResFmtHelp(ResString: PString; const Args: array of const;
  132. AHelpContext: Integer);
  133. begin
  134. inherited create;
  135. fmessage:=Format(ResString^,args);
  136. fhelpcontext:=AHelpContext;
  137. end;
  138. procedure EHeapMemoryError.FreeInstance;
  139. begin
  140. if AllowFree then
  141. inherited FreeInstance;
  142. end;
  143. Constructor EVariantError.CreateCode (Code : longint);
  144. begin
  145. case Code of
  146. VAR_OK:
  147. Create(SNoError);
  148. VAR_PARAMNOTFOUND:
  149. Create(SVarParamNotFound);
  150. VAR_TYPEMISMATCH:
  151. Create(SInvalidVarCast);
  152. VAR_BADVARTYPE:
  153. Create(SVarBadType);
  154. VAR_OVERFLOW:
  155. Create(SVarOverflow);
  156. VAR_BADINDEX:
  157. Create(SVarArrayBounds);
  158. VAR_ARRAYISLOCKED:
  159. Create(SVarArrayLocked);
  160. VAR_NOTIMPL:
  161. Create(SVarNotImplemented);
  162. VAR_OUTOFMEMORY:
  163. Create(SVarOutOfMemory);
  164. VAR_INVALIDARG:
  165. Create(SVarInvalid);
  166. VAR_UNEXPECTED,
  167. VAR_EXCEPTION:
  168. Create(SVarUnexpected);
  169. else
  170. CreateFmt(SUnknownErrorCode,[Code]);
  171. end;
  172. ErrCode:=Code;
  173. end;
  174. {$ifopt S+}
  175. {$define STACKCHECK_WAS_ON}
  176. {$S-}
  177. {$endif OPT S }
  178. Procedure CatchUnhandledException (Obj : TObject; Addr: Pointer; FrameCount: Longint; Frames: PPointer);[public,alias:'FPC_BREAK_UNHANDLED_EXCEPTION'];
  179. Var
  180. Message : String;
  181. i : longint;
  182. begin
  183. Writeln(stdout,'An unhandled exception occurred at $',HexStr(Ptrint(Addr),sizeof(PtrInt)*2),' :');
  184. if Obj is exception then
  185. begin
  186. Message:=Exception(Obj).ClassName+' : '+Exception(Obj).Message;
  187. Writeln(stdout,Message);
  188. end
  189. else
  190. Writeln(stdout,'Exception object ',Obj.ClassName,' is not of class Exception.');
  191. Writeln(stdout,BackTraceStrFunc(Addr));
  192. if (FrameCount>0) then
  193. begin
  194. for i:=0 to FrameCount-1 do
  195. Writeln(stdout,BackTraceStrFunc(Frames[i]));
  196. end;
  197. Writeln(stdout,'');
  198. end;
  199. Var OutOfMemory : EOutOfMemory;
  200. InValidPointer : EInvalidPointer;
  201. Procedure RunErrorToExcept (ErrNo : Longint; Address,Frame : Pointer);
  202. Var E : Exception;
  203. S : String;
  204. begin
  205. Case Errno of
  206. 1,203 : E:=OutOfMemory;
  207. 204 : E:=InvalidPointer;
  208. 2,3,4,5,6,100,101,102,103,105,106 : { I/O errors }
  209. begin
  210. Case Errno of
  211. 2 : S:=SFileNotFound;
  212. 3 : S:=SInvalidFileName;
  213. 4 : S:=STooManyOpenFiles;
  214. 5 : S:=SAccessDenied;
  215. 6 : S:=SInvalidFileHandle;
  216. 15 : S:=SInvalidDrive;
  217. 100 : S:=SEndOfFile;
  218. 101 : S:=SDiskFull;
  219. 102 : S:=SFileNotAssigned;
  220. 103 : S:=SFileNotOpen;
  221. 104 : S:=SFileNotOpenForInput;
  222. 105 : S:=SFileNotOpenForOutput;
  223. 106 : S:=SInvalidInput;
  224. end;
  225. E:=EinOutError.Create (S);
  226. EInoutError(E).ErrorCode:=IOresult; // Clears InOutRes !!
  227. end;
  228. // We don't set abstracterrorhandler, but we do it here.
  229. // Unless the use sets another handler we'll get here anyway...
  230. 200 : E:=EDivByZero.Create(SDivByZero);
  231. 201 : E:=ERangeError.Create(SRangeError);
  232. 205 : E:=EOverflow.Create(SOverflow);
  233. 206 : E:=EOverflow.Create(SUnderflow);
  234. 207 : E:=EInvalidOp.Create(SInvalidOp);
  235. 211 : E:=EAbstractError.Create(SAbstractError);
  236. 214 : E:=EBusError.Create(SBusError);
  237. 215 : E:=EIntOverflow.Create(SIntOverflow);
  238. 216 : E:=EAccessViolation.Create(SAccessViolation);
  239. 217 : E:=EControlC.Create(SControlC);
  240. 218 : E:=EPrivilege.Create(SPrivilege);
  241. 219 : E:=EInvalidCast.Create(SInvalidCast);
  242. 220 : E:=EVariantError.Create(SInvalidVarCast);
  243. 221 : E:=EVariantError.Create(SInvalidVarOp);
  244. 222 : E:=EVariantError.Create(SDispatchError);
  245. 223 : E:=EVariantError.Create(SVarArrayCreate);
  246. 224 : E:=EVariantError.Create(SVarNotArray);
  247. 225 : E:=EVariantError.Create(SVarArrayBounds);
  248. 227 : E:=EAssertionFailed.Create(SAssertionFailed);
  249. 228 : E:=EExternalException.Create(SExternalException);
  250. 229 : E:=EIntfCastError.Create(SIntfCastError);
  251. 230 : E:=ESafecallException.Create(SSafecallException);
  252. 231 : E:=EConvertError.Create(SiconvError);
  253. 232 : E:=ENoThreadSupport.Create(SNoThreadSupport);
  254. else
  255. E:=Exception.CreateFmt (SUnKnownRunTimeError,[Errno]);
  256. end;
  257. Raise E at Address,Frame;
  258. end;
  259. {$IFDEF HAS_OSERROR}
  260. Procedure RaiseLastOSError;
  261. var
  262. ECode: Cardinal;
  263. E : EOSError;
  264. begin
  265. ECode := GetLastOSError;
  266. If (ECode<>0) then
  267. E:=EOSError.CreateFmt(SOSError, [ECode, SysErrorMessage(ECode)])
  268. else
  269. E:=EOSError.Create(SUnkOSError);
  270. E.ErrorCode:=ECode;
  271. Raise E;
  272. end;
  273. {$else}
  274. Procedure RaiseLastOSError;
  275. begin
  276. Raise Exception.Create('RaiseLastOSError not implemented on this platform.');
  277. end;
  278. {$endif}
  279. Procedure AssertErrorHandler (Const Msg,FN : ShortString;LineNo:longint; TheAddr : pointer);
  280. Var
  281. S : String;
  282. begin
  283. If Msg='' then
  284. S:=SAssertionFailed
  285. else
  286. S:=Msg;
  287. Raise EAssertionFailed.Createfmt(SAssertError,[S,Fn,LineNo]); // at Pointer(theAddr);
  288. end;
  289. {$ifdef STACKCHECK_WAS_ON}
  290. {$S+}
  291. {$endif}
  292. Procedure InitExceptions;
  293. {
  294. Must install uncaught exception handler (ExceptProc)
  295. and install exceptions for system exceptions or signals.
  296. (e.g: SIGSEGV -> ESegFault or so.)
  297. }
  298. begin
  299. ExceptProc:=@CatchUnhandledException;
  300. // Create objects that may have problems when there is no memory.
  301. OutOfMemory:=EOutOfMemory.Create(SOutOfMemory);
  302. OutOfMemory.AllowFree:=false;
  303. InvalidPointer:=EInvalidPointer.Create(SInvalidPointer);
  304. InvalidPointer.AllowFree:=false;
  305. AssertErrorProc:=@AssertErrorHandler;
  306. ErrorProc:=@RunErrorToExcept;
  307. OnShowException:=Nil;
  308. end;
  309. Procedure DoneExceptions;
  310. begin
  311. OutOfMemory.AllowFree:=true;
  312. OutOfMemory.Free;
  313. InValidPointer.AllowFree:=true;
  314. InValidPointer.Free;
  315. end;
  316. { Exception handling routines }
  317. function ExceptObject: TObject;
  318. begin
  319. If RaiseList=Nil then
  320. Result:=Nil
  321. else
  322. Result:=RaiseList^.FObject;
  323. end;
  324. function ExceptAddr: Pointer;
  325. begin
  326. If RaiseList=Nil then
  327. Result:=Nil
  328. else
  329. Result:=RaiseList^.Addr;
  330. end;
  331. function ExceptFrameCount: Longint;
  332. begin
  333. If RaiseList=Nil then
  334. Result:=0
  335. else
  336. Result:=RaiseList^.Framecount;
  337. end;
  338. function ExceptFrames: PPointer;
  339. begin
  340. If RaiseList=Nil then
  341. Result:=Nil
  342. else
  343. Result:=RaiseList^.Frames;
  344. end;
  345. function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
  346. Buffer: PChar; Size: Integer): Integer;
  347. Var
  348. S : AnsiString;
  349. Len : Integer;
  350. begin
  351. S:=Format(SExceptionErrorMessage,[ExceptAddr,ExceptObject.ClassName]);
  352. If ExceptObject is Exception then
  353. S:=Format('%s:'#10'%s',[S,Exception(ExceptObject).Message]);
  354. Len:=Length(S);
  355. If S[Len]<>'.' then
  356. begin
  357. S:=S+'.';
  358. Inc(len);
  359. end;
  360. If Len>Size then
  361. Len:=Size;
  362. if Len > 0 then
  363. Move(S[1],Buffer^,Len);
  364. Result:=Len;
  365. end;
  366. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  367. // use shortstring. On exception, the heap may be corrupt.
  368. Var
  369. Buf : ShortString;
  370. begin
  371. SetLength(Buf,ExceptionErrorMessage(ExceptObject,ExceptAddr,@Buf[1],255));
  372. If IsConsole Then
  373. writeln(Buf)
  374. else
  375. If Assigned(OnShowException) Then
  376. OnShowException (Buf);
  377. end;
  378. procedure Abort;
  379. begin
  380. Raise EAbort.Create(SAbortError) at Pointer(Get_Caller_addr(Get_Frame));
  381. end;
  382. procedure OutOfMemoryError;
  383. begin
  384. Raise OutOfMemory;
  385. end;
  386. { ---------------------------------------------------------------------
  387. Initialization/Finalization/exit code
  388. ---------------------------------------------------------------------}
  389. Type
  390. PPRecord = ^TPRecord;
  391. TPRecord = Record
  392. Func : TTerminateProc;
  393. NextFunc : PPRecord;
  394. end;
  395. Const
  396. TPList : PPRecord = Nil;
  397. procedure AddTerminateProc(TermProc: TTerminateProc);
  398. Var
  399. TPR : PPRecord;
  400. begin
  401. New(TPR);
  402. With TPR^ do
  403. begin
  404. NextFunc:=TPList;
  405. Func:=TermProc;
  406. end;
  407. TPList:=TPR;
  408. end;
  409. function CallTerminateProcs: Boolean;
  410. Var
  411. TPR : PPRecord;
  412. begin
  413. Result:=True;
  414. TPR:=TPList;
  415. While Result and (TPR<>Nil) do
  416. begin
  417. Result:=TPR^.Func();
  418. TPR:=TPR^.NextFunc;
  419. end;
  420. end;
  421. { ---------------------------------------------------------------------
  422. Diskh functions, OS independent.
  423. ---------------------------------------------------------------------}
  424. function ForceDirectories(Const Dir: string): Boolean;
  425. var
  426. E: EInOutError;
  427. ADrv : String;
  428. function DoForceDirectories(Const Dir: string): Boolean;
  429. var
  430. ADir : String;
  431. begin
  432. Result:=True;
  433. ADir:=ExcludeTrailingPathDelimiter(Dir);
  434. if (ADir='') then Exit;
  435. if Not DirectoryExists(ADir) then
  436. begin
  437. Result:=DoForceDirectories(ExtractFilePath(ADir));
  438. If Result then
  439. Result := CreateDir(ADir);
  440. end;
  441. end;
  442. begin
  443. Result := False;
  444. ADrv := ExtractFileDrive(Dir);
  445. if (ADrv<>'') and (not DirectoryExists(ADrv)) then Exit;
  446. if Dir='' then
  447. begin
  448. E:=EInOutError.Create(SCannotCreateEmptyDir);
  449. E.ErrorCode:=3;
  450. Raise E;
  451. end;
  452. Result := DoForceDirectories(Dir);
  453. end;
  454. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  455. Var
  456. I : Integer;
  457. P : PByte;
  458. begin
  459. P:=@Buf;
  460. Randomize;
  461. For I:=0 to NBytes-1 do
  462. P[i]:=Random(256);
  463. end;
  464. {$IFDEF HASCREATEGUID}
  465. Function SysCreateGUID(out GUID : TGUID) : Integer; forward;
  466. {$ENDIF}
  467. Function CreateGUID(out GUID : TGUID) : Integer;
  468. begin
  469. If Assigned(OnCreateGUID) then
  470. Result:=OnCreateGUID(GUID)
  471. else
  472. begin
  473. {$IFDEF HASCREATEGUID}
  474. Result:=SysCreateGUID(GUID);
  475. {$ELSE}
  476. GetRandomBytes(GUID,SizeOf(Guid));
  477. Result:=0;
  478. {$ENDIF}
  479. end;
  480. end;
  481. function SafeLoadLibrary(const FileName: AnsiString;
  482. ErrorMode: DWord = {$ifdef windows}SEM_NOOPENFILEERRORBOX{$else windows}0{$endif windows}): HMODULE;
  483. {$if defined(cpui386) or defined(cpux86_64)}
  484. var
  485. mode : DWord;
  486. fpucw : Word;
  487. ssecw : DWord;
  488. {$endif}
  489. begin
  490. {$if defined(win64) or defined(win32)}
  491. mode:=SetErrorMode(ErrorMode);
  492. {$endif}
  493. try
  494. {$if defined(cpui386) or defined(cpux86_64)}
  495. fpucw:=Get8087CW;
  496. {$ifdef cpui386}
  497. if has_sse_support then
  498. {$endif cpui386}
  499. ssecw:=GetSSECSR;
  500. {$endif}
  501. {$if defined(windows) or defined(win32)}
  502. Result:=LoadLibraryA(PChar(Filename));
  503. {$else}
  504. Result:=0;
  505. {$endif}
  506. finally
  507. {$if defined(cpui386) or defined(cpux86_64)}
  508. Set8087CW(fpucw);
  509. {$ifdef cpui386}
  510. if has_sse_support then
  511. {$endif cpui386}
  512. SetSSECSR(ssecw);
  513. {$endif}
  514. {$if defined(win64) or defined(win32)}
  515. SetErrorMode(mode);
  516. {$endif}
  517. end;
  518. end;