sysutils.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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. 212 : E:=EExternalException.Create(SExternalException);
  237. 214 : E:=EBusError.Create(SBusError);
  238. 215 : E:=EIntOverflow.Create(SIntOverflow);
  239. 216 : E:=EAccessViolation.Create(SAccessViolation);
  240. 217 : E:=EControlC.Create(SControlC);
  241. 218 : E:=EPrivilege.Create(SPrivilege);
  242. 219 : E:=EInvalidCast.Create(SInvalidCast);
  243. 220 : E:=EVariantError.Create(SInvalidVarCast);
  244. 221 : E:=EVariantError.Create(SInvalidVarOp);
  245. 222 : E:=EVariantError.Create(SDispatchError);
  246. 223 : E:=EVariantError.Create(SVarArrayCreate);
  247. 224 : E:=EVariantError.Create(SVarNotArray);
  248. 225 : E:=EVariantError.Create(SVarArrayBounds);
  249. 227 : E:=EAssertionFailed.Create(SAssertionFailed);
  250. 228 : E:=EIntfCastError.Create(SIntfCastError);
  251. 229 : 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. ExceptionClass := Exception;
  300. ExceptProc:=@CatchUnhandledException;
  301. // Create objects that may have problems when there is no memory.
  302. OutOfMemory:=EOutOfMemory.Create(SOutOfMemory);
  303. OutOfMemory.AllowFree:=false;
  304. InvalidPointer:=EInvalidPointer.Create(SInvalidPointer);
  305. InvalidPointer.AllowFree:=false;
  306. AssertErrorProc:=@AssertErrorHandler;
  307. ErrorProc:=@RunErrorToExcept;
  308. OnShowException:=Nil;
  309. end;
  310. Procedure DoneExceptions;
  311. begin
  312. OutOfMemory.AllowFree:=true;
  313. OutOfMemory.Free;
  314. InValidPointer.AllowFree:=true;
  315. InValidPointer.Free;
  316. end;
  317. { Exception handling routines }
  318. function ExceptObject: TObject;
  319. begin
  320. If RaiseList=Nil then
  321. Result:=Nil
  322. else
  323. Result:=RaiseList^.FObject;
  324. end;
  325. function ExceptAddr: Pointer;
  326. begin
  327. If RaiseList=Nil then
  328. Result:=Nil
  329. else
  330. Result:=RaiseList^.Addr;
  331. end;
  332. function ExceptFrameCount: Longint;
  333. begin
  334. If RaiseList=Nil then
  335. Result:=0
  336. else
  337. Result:=RaiseList^.Framecount;
  338. end;
  339. function ExceptFrames: PPointer;
  340. begin
  341. If RaiseList=Nil then
  342. Result:=Nil
  343. else
  344. Result:=RaiseList^.Frames;
  345. end;
  346. function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
  347. Buffer: PChar; Size: Integer): Integer;
  348. Var
  349. S : AnsiString;
  350. Len : Integer;
  351. begin
  352. S:=Format(SExceptionErrorMessage,[ExceptAddr,ExceptObject.ClassName]);
  353. If ExceptObject is Exception then
  354. S:=Format('%s:'#10'%s',[S,Exception(ExceptObject).Message]);
  355. Len:=Length(S);
  356. If S[Len]<>'.' then
  357. begin
  358. S:=S+'.';
  359. Inc(len);
  360. end;
  361. If Len>Size then
  362. Len:=Size;
  363. if Len > 0 then
  364. Move(S[1],Buffer^,Len);
  365. Result:=Len;
  366. end;
  367. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  368. // use shortstring. On exception, the heap may be corrupt.
  369. Var
  370. Buf : ShortString;
  371. begin
  372. SetLength(Buf,ExceptionErrorMessage(ExceptObject,ExceptAddr,@Buf[1],255));
  373. If IsConsole Then
  374. writeln(Buf)
  375. else
  376. If Assigned(OnShowException) Then
  377. OnShowException (Buf);
  378. end;
  379. procedure Abort;
  380. begin
  381. Raise EAbort.Create(SAbortError) at Pointer(Get_Caller_addr(Get_Frame));
  382. end;
  383. procedure OutOfMemoryError;
  384. begin
  385. Raise OutOfMemory;
  386. end;
  387. { ---------------------------------------------------------------------
  388. Initialization/Finalization/exit code
  389. ---------------------------------------------------------------------}
  390. Type
  391. PPRecord = ^TPRecord;
  392. TPRecord = Record
  393. Func : TTerminateProc;
  394. NextFunc : PPRecord;
  395. end;
  396. Const
  397. TPList : PPRecord = Nil;
  398. procedure AddTerminateProc(TermProc: TTerminateProc);
  399. Var
  400. TPR : PPRecord;
  401. begin
  402. New(TPR);
  403. With TPR^ do
  404. begin
  405. NextFunc:=TPList;
  406. Func:=TermProc;
  407. end;
  408. TPList:=TPR;
  409. end;
  410. function CallTerminateProcs: Boolean;
  411. Var
  412. TPR : PPRecord;
  413. begin
  414. Result:=True;
  415. TPR:=TPList;
  416. While Result and (TPR<>Nil) do
  417. begin
  418. Result:=TPR^.Func();
  419. TPR:=TPR^.NextFunc;
  420. end;
  421. end;
  422. { ---------------------------------------------------------------------
  423. Diskh functions, OS independent.
  424. ---------------------------------------------------------------------}
  425. function ForceDirectories(Const Dir: string): Boolean;
  426. var
  427. E: EInOutError;
  428. ADrv : String;
  429. function DoForceDirectories(Const Dir: string): Boolean;
  430. var
  431. ADir : String;
  432. begin
  433. Result:=True;
  434. ADir:=ExcludeTrailingPathDelimiter(Dir);
  435. if (ADir='') then Exit;
  436. if Not DirectoryExists(ADir) then
  437. begin
  438. Result:=DoForceDirectories(ExtractFilePath(ADir));
  439. If Result then
  440. Result := CreateDir(ADir);
  441. end;
  442. end;
  443. begin
  444. Result := False;
  445. ADrv := ExtractFileDrive(Dir);
  446. if (ADrv<>'') and (not DirectoryExists(ADrv)) then Exit;
  447. if Dir='' then
  448. begin
  449. E:=EInOutError.Create(SCannotCreateEmptyDir);
  450. E.ErrorCode:=3;
  451. Raise E;
  452. end;
  453. Result := DoForceDirectories(Dir);
  454. end;
  455. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  456. Var
  457. I : Integer;
  458. P : PByte;
  459. begin
  460. P:=@Buf;
  461. Randomize;
  462. For I:=0 to NBytes-1 do
  463. P[i]:=Random(256);
  464. end;
  465. {$IFDEF HASCREATEGUID}
  466. Function SysCreateGUID(out GUID : TGUID) : Integer; forward;
  467. {$ENDIF}
  468. Function CreateGUID(out GUID : TGUID) : Integer;
  469. begin
  470. If Assigned(OnCreateGUID) then
  471. Result:=OnCreateGUID(GUID)
  472. else
  473. begin
  474. {$IFDEF HASCREATEGUID}
  475. Result:=SysCreateGUID(GUID);
  476. {$ELSE}
  477. GetRandomBytes(GUID,SizeOf(Guid));
  478. Result:=0;
  479. {$ENDIF}
  480. end;
  481. end;
  482. function SafeLoadLibrary(const FileName: AnsiString;
  483. ErrorMode: DWord = {$ifdef windows}SEM_NOOPENFILEERRORBOX{$else windows}0{$endif windows}): HMODULE;
  484. {$if defined(cpui386) or defined(cpux86_64)}
  485. var
  486. mode : DWord;
  487. fpucw : Word;
  488. ssecw : DWord;
  489. {$endif}
  490. begin
  491. {$if defined(win64) or defined(win32)}
  492. mode:=SetErrorMode(ErrorMode);
  493. {$endif}
  494. try
  495. {$if defined(cpui386) or defined(cpux86_64)}
  496. fpucw:=Get8087CW;
  497. {$ifdef cpui386}
  498. if has_sse_support then
  499. {$endif cpui386}
  500. ssecw:=GetSSECSR;
  501. {$endif}
  502. {$if defined(windows) or defined(win32)}
  503. Result:=LoadLibraryA(PChar(Filename));
  504. {$else}
  505. Result:=0;
  506. {$endif}
  507. finally
  508. {$if defined(cpui386) or defined(cpux86_64)}
  509. Set8087CW(fpucw);
  510. {$ifdef cpui386}
  511. if has_sse_support then
  512. {$endif cpui386}
  513. SetSSECSR(ssecw);
  514. {$endif}
  515. {$if defined(win64) or defined(win32)}
  516. SetErrorMode(mode);
  517. {$endif}
  518. end;
  519. end;