sysutils.inc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. {
  2. $Id: sysutils.inc,v 1.20 2005/02/26 14:38:14 florian Exp $
  3. This file is part of the Free Pascal run time library.
  4. Copyright (c) 1999-2000 by Florian Klaempfl
  5. member of the Free Pascal development team
  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. { Read filename handling functions implementation }
  13. {$i fina.inc}
  14. Function FileSearch (Const Name, DirList : String) : String;
  15. Var
  16. I : longint;
  17. Temp : String;
  18. begin
  19. Result:='';
  20. temp:=Dirlist;
  21. repeat
  22. While (Length(Temp)>0) and (Temp[1]=PathSeparator) do
  23. Delete(Temp,1,1);
  24. I:=pos(PathSep,Temp);
  25. If I<>0 then
  26. begin
  27. Result:=Copy (Temp,1,i-1);
  28. system.Delete(Temp,1,I);
  29. end
  30. else
  31. begin
  32. Result:=Temp;
  33. Temp:='';
  34. end;
  35. If (Length(Result)>0) and (result[length(result)]<>DirectorySeparator) then
  36. Result:=Result+DirectorySeparator;
  37. Result:=Result+name;
  38. If not FileExists(Result) Then
  39. Result:='';
  40. until (length(temp)=0) or (length(result)<>0);
  41. end;
  42. {$ifndef OS_FILEISREADONLY}
  43. Function FileIsReadOnly(const FileName: String): Boolean;
  44. begin
  45. Result := (FileGetAttr(FileName) and faReadOnly) <> 0;
  46. end;
  47. {$endif OS_FILEISREADONLY}
  48. { Read String Handling functions implementation }
  49. {$i sysstr.inc}
  50. { Read date & Time function implementations }
  51. {$i dati.inc}
  52. { Read pchar handling functions implementation }
  53. {$i syspch.inc}
  54. { generic internationalisation code }
  55. {$i sysint.inc}
  56. { MCBS functions }
  57. {$i sysansi.inc}
  58. { wide string functions }
  59. {$i syswide.inc}
  60. { CPU Specific code }
  61. {$i sysutilp.inc}
  62. { OS utility code }
  63. {$i osutil.inc}
  64. procedure FreeAndNil(var obj);
  65. var
  66. temp: tobject;
  67. begin
  68. temp:=tobject(obj);
  69. pointer(obj):=nil;
  70. temp.free;
  71. end;
  72. {$ifdef HASINTF}
  73. { Interfaces support }
  74. {$i sysuintf.inc}
  75. {$endif HASINTF}
  76. constructor Exception.Create(const msg : string);
  77. begin
  78. inherited create;
  79. fmessage:=msg;
  80. end;
  81. constructor Exception.CreateFmt(const msg : string; const args : array of const);
  82. begin
  83. inherited create;
  84. fmessage:=Format(msg,args);
  85. end;
  86. constructor Exception.CreateRes(ResString: PString);
  87. begin
  88. inherited create;
  89. fmessage:=ResString^;
  90. end;
  91. constructor Exception.CreateResFmt(ResString: PString; const Args: array of const);
  92. begin
  93. inherited create;
  94. fmessage:=Format(ResString^,args);
  95. end;
  96. constructor Exception.CreateHelp(const Msg: string; AHelpContext: Integer);
  97. begin
  98. inherited create;
  99. fmessage:=Msg;
  100. fhelpcontext:=AHelpContext;
  101. end;
  102. constructor Exception.CreateFmtHelp(const Msg: string; const Args: array of const;
  103. AHelpContext: Integer);
  104. begin
  105. inherited create;
  106. fmessage:=Format(Msg,args);
  107. fhelpcontext:=AHelpContext;
  108. end;
  109. constructor Exception.CreateResHelp(ResString: PString; AHelpContext: Integer);
  110. begin
  111. inherited create;
  112. fmessage:=ResString^;
  113. fhelpcontext:=AHelpContext;
  114. end;
  115. constructor Exception.CreateResFmtHelp(ResString: PString; const Args: array of const;
  116. AHelpContext: Integer);
  117. begin
  118. inherited create;
  119. fmessage:=Format(ResString^,args);
  120. fhelpcontext:=AHelpContext;
  121. end;
  122. procedure EHeapMemoryError.FreeInstance;
  123. begin
  124. if AllowFree then
  125. inherited FreeInstance;
  126. end;
  127. {$ifopt S+}
  128. {$define STACKCHECK_WAS_ON}
  129. {$S-}
  130. {$endif OPT S }
  131. Procedure CatchUnhandledException (Obj : TObject; Addr: Pointer; FrameCount: Longint; Frames: PPointer);[public,alias:'FPC_BREAK_UNHANDLED_EXCEPTION'];
  132. Var
  133. Message : String;
  134. {$IFDEF VIRTUALPASCAL}
  135. stdout:text absolute output;
  136. {$ENDIF}
  137. i : longint;
  138. begin
  139. Writeln(stdout,'An unhandled exception occurred at $',HexStr(Ptrint(Addr),sizeof(PtrInt)*2),' :');
  140. if Obj is exception then
  141. begin
  142. Message:=Exception(Obj).ClassName+' : '+Exception(Obj).Message;
  143. Writeln(stdout,Message);
  144. end
  145. else
  146. Writeln(stdout,'Exception object ',Obj.ClassName,' is not of class Exception.');
  147. if (FrameCount>0) then
  148. begin
  149. Writeln(stdout,BackTraceStrFunc(Addr));
  150. for i:=0 to FrameCount-1 do
  151. Writeln(stdout,BackTraceStrFunc(Frames[i]));
  152. end;
  153. Halt(217);
  154. end;
  155. Var OutOfMemory : EOutOfMemory;
  156. InValidPointer : EInvalidPointer;
  157. Procedure RunErrorToExcept (ErrNo : Longint; Address,Frame : Pointer);
  158. Var E : Exception;
  159. S : String;
  160. begin
  161. Case Errno of
  162. 1,203 : E:=OutOfMemory;
  163. 204 : E:=InvalidPointer;
  164. 2,3,4,5,6,100,101,102,103,105,106 : { I/O errors }
  165. begin
  166. Case Errno of
  167. 2 : S:=SFileNotFound;
  168. 3 : S:=SInvalidFileName;
  169. 4 : S:=STooManyOpenFiles;
  170. 5 : S:=SAccessDenied;
  171. 6 : S:=SInvalidFileHandle;
  172. 15 : S:=SInvalidDrive;
  173. 100 : S:=SEndOfFile;
  174. 101 : S:=SDiskFull;
  175. 102 : S:=SFileNotAssigned;
  176. 103 : S:=SFileNotOpen;
  177. 104 : S:=SFileNotOpenForInput;
  178. 105 : S:=SFileNotOpenForOutput;
  179. 106 : S:=SInvalidInput;
  180. end;
  181. E:=EinOutError.Create (S);
  182. EInoutError(E).ErrorCode:=IOresult; // Clears InOutRes !!
  183. end;
  184. // We don't set abstracterrorhandler, but we do it here.
  185. // Unless the use sets another handler we'll get here anyway...
  186. 200 : E:=EDivByZero.Create(SDivByZero);
  187. 201 : E:=ERangeError.Create(SRangeError);
  188. 205 : E:=EOverflow.Create(SOverflow);
  189. 206 : E:=EOverflow.Create(SUnderflow);
  190. 207 : E:=EInvalidOp.Create(SInvalidOp);
  191. 211 : E:=EAbstractError.Create(SAbstractError);
  192. 215 : E:=EIntOverflow.Create(SIntOverflow);
  193. 216 : E:=EAccessViolation.Create(SAccessViolation);
  194. 217 : E:=EPrivilege.Create(SPrivilege);
  195. 218 : E:=EControlC.Create(SControlC);
  196. 219 : E:=EInvalidCast.Create(SInvalidCast);
  197. 220 : E:=EVariantError.Create(SInvalidVarCast);
  198. 221 : E:=EVariantError.Create(SInvalidVarOp);
  199. 222 : E:=EVariantError.Create(SDispatchError);
  200. 223 : E:=EVariantError.Create(SVarArrayCreate);
  201. 224 : E:=EVariantError.Create(SVarNotArray);
  202. 225 : E:=EVariantError.Create(SVarArrayBounds);
  203. 227 : E:=EAssertionFailed.Create(SAssertionFailed);
  204. 228 : E:=EExternalException.Create(SExternalException);
  205. 229 : E:=EIntfCastError.Create(SIntfCastError);
  206. 230 : E:=ESafecallException.Create(SSafecallException);
  207. 232 : E:=ENoThreadSupport.Create(SNoThreadSupport);
  208. else
  209. E:=Exception.CreateFmt (SUnKnownRunTimeError,[Errno]);
  210. end;
  211. Raise E at Address,Frame;
  212. end;
  213. {$IFDEF HAS_OSERROR}
  214. Procedure RaiseLastOSError;
  215. var
  216. ECode: Cardinal;
  217. E : EOSError;
  218. begin
  219. ECode := GetLastOSError;
  220. If (ECode<>0) then
  221. E:=EOSError.CreateFmt(SOSError, [ECode, SysErrorMessage(ECode)])
  222. else
  223. E:=EOSError.Create(SUnkOSError);
  224. E.ErrorCode:=ECode;
  225. Raise E;
  226. end;
  227. {$else}
  228. Procedure RaiseLastOSError;
  229. begin
  230. Raise Exception.Create('RaiseLastOSError not implemented on this platform.');
  231. end;
  232. {$endif}
  233. Procedure AssertErrorHandler (Const Msg,FN : ShortString;LineNo:longint; TheAddr : pointer);
  234. Var
  235. S : String;
  236. begin
  237. If Msg='' then
  238. S:=SAssertionFailed
  239. else
  240. S:=Msg;
  241. Raise EAssertionFailed.Createfmt(SAssertError,[S,Fn,LineNo]); // at Pointer(theAddr);
  242. end;
  243. {$ifdef STACKCHECK_WAS_ON}
  244. {$S+}
  245. {$endif}
  246. Procedure InitExceptions;
  247. {
  248. Must install uncaught exception handler (ExceptProc)
  249. and install exceptions for system exceptions or signals.
  250. (e.g: SIGSEGV -> ESegFault or so.)
  251. }
  252. begin
  253. ExceptProc:=@CatchUnhandledException;
  254. // Create objects that may have problems when there is no memory.
  255. OutOfMemory:=EOutOfMemory.Create(SOutOfMemory);
  256. OutOfMemory.AllowFree:=false;
  257. InvalidPointer:=EInvalidPointer.Create(SInvalidPointer);
  258. InvalidPointer.AllowFree:=false;
  259. AssertErrorProc:=@AssertErrorHandler;
  260. ErrorProc:=@RunErrorToExcept;
  261. OnShowException:=Nil;
  262. end;
  263. Procedure DoneExceptions;
  264. begin
  265. OutOfMemory.AllowFree:=true;
  266. OutOfMemory.Free;
  267. InValidPointer.AllowFree:=true;
  268. InValidPointer.Free;
  269. end;
  270. { Exception handling routines }
  271. function ExceptObject: TObject;
  272. begin
  273. {$IFDEF VIRTUALPASCAL}
  274. // vpascal does exceptions more the delphi way...
  275. // this needs to be written from scratch.
  276. {$ELSE}
  277. If RaiseList=Nil then
  278. Result:=Nil
  279. else
  280. Result:=RaiseList^.FObject;
  281. {$ENDIF}
  282. end;
  283. function ExceptAddr: Pointer;
  284. begin
  285. {$IFDEF VIRTUALPASCAL}
  286. // vpascal does exceptions more the delphi way...
  287. // this needs to be written from scratch.
  288. {$ELSE}
  289. If RaiseList=Nil then
  290. Result:=Nil
  291. else
  292. Result:=RaiseList^.Addr;
  293. {$ENDIF}
  294. end;
  295. function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
  296. Buffer: PChar; Size: Integer): Integer;
  297. Var
  298. S : AnsiString;
  299. Len : Integer;
  300. begin
  301. S:=Format(SExceptionErrorMessage,[ExceptAddr,ExceptObject.ClassName]);
  302. If ExceptObject is Exception then
  303. S:=Format('%s:'#10'%s',[S,Exception(ExceptObject).Message]);
  304. Len:=Length(S);
  305. If S[Len]<>'.' then
  306. begin
  307. S:=S+'.';
  308. Inc(len);
  309. end;
  310. If Len>Size then
  311. Len:=Size;
  312. if Len > 0 then
  313. Move(S[1],Buffer^,Len);
  314. Result:=Len;
  315. end;
  316. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  317. // use shortstring. On exception, the heap may be corrupt.
  318. Var
  319. Buf : ShortString;
  320. begin
  321. SetLength(Buf,ExceptionErrorMessage(ExceptObject,ExceptAddr,@Buf[1],255));
  322. If IsConsole Then
  323. writeln(Buf)
  324. else
  325. If Assigned(OnShowException) Then
  326. OnShowException (Buf);
  327. end;
  328. procedure Abort;
  329. begin
  330. Raise EAbort.Create(SAbortError) at Pointer(Get_Caller_addr(Get_Frame));
  331. end;
  332. procedure OutOfMemoryError;
  333. begin
  334. Raise OutOfMemory;
  335. end;
  336. { ---------------------------------------------------------------------
  337. Initialization/Finalization/exit code
  338. ---------------------------------------------------------------------}
  339. Type
  340. PPRecord = ^TPRecord;
  341. TPRecord = Record
  342. Func : TTerminateProc;
  343. NextFunc : PPRecord;
  344. end;
  345. Const
  346. TPList : PPRecord = Nil;
  347. procedure AddTerminateProc(TermProc: TTerminateProc);
  348. Var
  349. TPR : PPRecord;
  350. begin
  351. New(TPR);
  352. With TPR^ do
  353. begin
  354. NextFunc:=TPList;
  355. Func:=TermProc;
  356. end;
  357. TPList:=TPR;
  358. end;
  359. function CallTerminateProcs: Boolean;
  360. Var
  361. TPR : PPRecord;
  362. begin
  363. Result:=True;
  364. TPR:=TPList;
  365. While Result and (TPR<>Nil) do
  366. begin
  367. Result:=TPR^.Func();
  368. TPR:=TPR^.NextFunc;
  369. end;
  370. end;
  371. { ---------------------------------------------------------------------
  372. Diskh functions, OS independent.
  373. ---------------------------------------------------------------------}
  374. function ForceDirectories(Const Dir: string): Boolean;
  375. var
  376. E: EInOutError;
  377. ADir : String;
  378. begin
  379. Result:=True;
  380. ADir:=ExcludeTrailingPathDelimiter(Dir);
  381. if (ADir='') then
  382. begin
  383. E:=EInOutError.Create(SCannotCreateEmptyDir);
  384. E.ErrorCode:=3;
  385. Raise E;
  386. end;
  387. if Not DirectoryExists(ADir) then
  388. begin
  389. Result:=ForceDirectories(ExtractFilePath(ADir));
  390. If Result then
  391. CreateDir(ADir);
  392. end;
  393. end;
  394. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  395. Var
  396. I : Integer;
  397. P : PByte;
  398. begin
  399. P:=@Buf;
  400. Randomize;
  401. For I:=0 to NBytes-1 do
  402. P[i]:=Random(256);
  403. end;
  404. {$IFNDEF HASCREATEGUID}
  405. Function CreateGUID(out GUID : TGUID) : Integer;
  406. begin
  407. Result:=0;
  408. GetRandomBytes(GUID,SizeOf(Guid));
  409. end;
  410. {$ENDIF}
  411. {
  412. Revision 1.1 2003/10/06 21:01:06 peter
  413. * moved classes unit to rtl
  414. Revision 1.17 2003/09/06 20:46:07 marco
  415. * 3 small VP fixes from Noah Silva. One (OutOfMemory error) failed.
  416. Revision 1.16 2003/04/06 11:06:39 michael
  417. + Added exception classname to output of unhandled exception for better identification
  418. Revision 1.15 2003/03/18 08:28:23 michael
  419. Patch from peter for Abort routine
  420. Revision 1.14 2003/03/17 15:11:51 armin
  421. + someone AssertErrorHandler, BackTraceFunc and Dump_Stack so that pointer instead of longint is needed
  422. Revision 1.13 2003/01/01 20:58:07 florian
  423. + added invalid instruction exception
  424. Revision 1.12 2002/10/07 19:43:24 florian
  425. + empty prototypes for the AnsiStr* multi byte functions added
  426. Revision 1.11 2002/09/07 16:01:22 peter
  427. * old logs removed and tabs fixed
  428. Revision 1.10 2002/07/16 13:57:39 florian
  429. * raise takes now a void pointer as at and frame address
  430. instead of a longint, fixed
  431. Revision 1.9 2002/01/25 17:42:03 peter
  432. * interface helpers
  433. Revision 1.8 2002/01/25 16:23:03 peter
  434. * merged filesearch() fix
  435. }