sysutils.inc 13 KB

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