sysutils.inc 13 KB

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