sysutils.inc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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. { MCBS functions }
  55. {$i sysansi.inc}
  56. {$ifndef VER1_0}
  57. { wide string functions }
  58. {$i syswide.inc}
  59. {$endif VER1_0}
  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. {$ifdef VER1_0}
  212. Raise E at longint(Address){$ifdef ENHANCEDRAISE},longint(Frame){$endif};
  213. {$else VER1_0}
  214. Raise E at Address,Frame;
  215. {$endif VER1_0}
  216. end;
  217. {$IFDEF HAS_OSERROR}
  218. Procedure RaiseLastOSError;
  219. var
  220. ECode: Cardinal;
  221. E : EOSError;
  222. begin
  223. ECode := GetLastOSError;
  224. If (ECode<>0) then
  225. E:=EOSError.CreateFmt(SOSError, [ECode, SysErrorMessage(ECode)])
  226. else
  227. E:=EOSError.Create(SUnkOSError);
  228. E.ErrorCode:=ECode;
  229. Raise E;
  230. end;
  231. {$else}
  232. Procedure RaiseLastOSError;
  233. begin
  234. Raise Exception.Create('RaiseLastOSError not implemented on this platform.');
  235. end;
  236. {$endif}
  237. Procedure AssertErrorHandler (Const Msg,FN : ShortString;LineNo:longint; TheAddr : pointer);
  238. Var
  239. S : String;
  240. begin
  241. If Msg='' then
  242. S:=SAssertionFailed
  243. else
  244. S:=Msg;
  245. Raise EAssertionFailed.Createfmt(SAssertError,[S,Fn,LineNo]); // at Pointer(theAddr);
  246. end;
  247. {$ifdef STACKCHECK_WAS_ON}
  248. {$S+}
  249. {$endif}
  250. Procedure InitExceptions;
  251. {
  252. Must install uncaught exception handler (ExceptProc)
  253. and install exceptions for system exceptions or signals.
  254. (e.g: SIGSEGV -> ESegFault or so.)
  255. }
  256. begin
  257. ExceptProc:=@CatchUnhandledException;
  258. // Create objects that may have problems when there is no memory.
  259. OutOfMemory:=EOutOfMemory.Create(SOutOfMemory);
  260. OutOfMemory.AllowFree:=false;
  261. InvalidPointer:=EInvalidPointer.Create(SInvalidPointer);
  262. InvalidPointer.AllowFree:=false;
  263. AssertErrorProc:=@AssertErrorHandler;
  264. ErrorProc:=@RunErrorToExcept;
  265. OnShowException:=Nil;
  266. end;
  267. Procedure DoneExceptions;
  268. begin
  269. OutOfMemory.AllowFree:=true;
  270. OutOfMemory.Free;
  271. InValidPointer.AllowFree:=true;
  272. InValidPointer.Free;
  273. end;
  274. { Exception handling routines }
  275. function ExceptObject: TObject;
  276. begin
  277. {$IFDEF VIRTUALPASCAL}
  278. // vpascal does exceptions more the delphi way...
  279. // this needs to be written from scratch.
  280. {$ELSE}
  281. If RaiseList=Nil then
  282. Result:=Nil
  283. else
  284. Result:=RaiseList^.FObject;
  285. {$ENDIF}
  286. end;
  287. function ExceptAddr: Pointer;
  288. begin
  289. {$IFDEF VIRTUALPASCAL}
  290. // vpascal does exceptions more the delphi way...
  291. // this needs to be written from scratch.
  292. {$ELSE}
  293. If RaiseList=Nil then
  294. Result:=Nil
  295. else
  296. Result:=RaiseList^.Addr;
  297. {$ENDIF}
  298. end;
  299. function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
  300. Buffer: PChar; Size: Integer): Integer;
  301. Var
  302. S : AnsiString;
  303. Len : Integer;
  304. begin
  305. S:=Format(SExceptionErrorMessage,[ExceptAddr,ExceptObject.ClassName]);
  306. If ExceptObject is Exception then
  307. S:=Format('%s:'#10'%s',[S,Exception(ExceptObject).Message]);
  308. Len:=Length(S);
  309. If S[Len]<>'.' then
  310. begin
  311. S:=S+'.';
  312. Inc(len);
  313. end;
  314. If Len>Size then
  315. Len:=Size;
  316. if Len > 0 then
  317. Move(S[1],Buffer^,Len);
  318. Result:=Len;
  319. end;
  320. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  321. // use shortstring. On exception, the heap may be corrupt.
  322. Var
  323. Buf : ShortString;
  324. begin
  325. SetLength(Buf,ExceptionErrorMessage(ExceptObject,ExceptAddr,@Buf[1],255));
  326. If IsConsole Then
  327. writeln(Buf)
  328. else
  329. If Assigned(OnShowException) Then
  330. OnShowException (Buf);
  331. end;
  332. procedure Abort;
  333. begin
  334. {$ifdef VER1_0}
  335. Raise EAbort.Create(SAbortError) at Longint(Get_Caller_addr(Get_Frame));
  336. {$else VER1_0}
  337. Raise EAbort.Create(SAbortError)
  338. {$IFNDEF VIRTUALPASCAL}
  339. at Pointer(Get_Caller_addr(Get_Frame));
  340. {$ENDIF}
  341. {$endif VER1_0}
  342. end;
  343. procedure OutOfMemoryError;
  344. begin
  345. Raise OutOfMemory;
  346. end;
  347. { ---------------------------------------------------------------------
  348. Initialization/Finalization/exit code
  349. ---------------------------------------------------------------------}
  350. Type
  351. PPRecord = ^TPRecord;
  352. TPRecord = Record
  353. Func : TTerminateProc;
  354. NextFunc : PPRecord;
  355. end;
  356. Const
  357. TPList : PPRecord = Nil;
  358. procedure AddTerminateProc(TermProc: TTerminateProc);
  359. Var
  360. TPR : PPRecord;
  361. begin
  362. New(TPR);
  363. With TPR^ do
  364. begin
  365. NextFunc:=TPList;
  366. Func:=TermProc;
  367. end;
  368. TPList:=TPR;
  369. end;
  370. function CallTerminateProcs: Boolean;
  371. Var
  372. TPR : PPRecord;
  373. begin
  374. Result:=True;
  375. TPR:=TPList;
  376. While Result and (TPR<>Nil) do
  377. begin
  378. Result:=TPR^.Func();
  379. TPR:=TPR^.NextFunc;
  380. end;
  381. end;
  382. { ---------------------------------------------------------------------
  383. Diskh functions, OS independent.
  384. ---------------------------------------------------------------------}
  385. function ForceDirectories(Const Dir: string): Boolean;
  386. var
  387. E: EInOutError;
  388. ADir : String;
  389. begin
  390. Result:=True;
  391. ADir:=ExcludeTrailingPathDelimiter(Dir);
  392. if (ADir='') then
  393. begin
  394. E:=EInOutError.Create(SCannotCreateEmptyDir);
  395. E.ErrorCode:=3;
  396. Raise E;
  397. end;
  398. if Not DirectoryExists(ADir) then
  399. begin
  400. Result:=ForceDirectories(ExtractFilePath(ADir));
  401. If Result then
  402. CreateDir(ADir);
  403. end;
  404. end;
  405. {
  406. Revision 1.1 2003/10/06 21:01:06 peter
  407. * moved classes unit to rtl
  408. Revision 1.17 2003/09/06 20:46:07 marco
  409. * 3 small VP fixes from Noah Silva. One (OutOfMemory error) failed.
  410. Revision 1.16 2003/04/06 11:06:39 michael
  411. + Added exception classname to output of unhandled exception for better identification
  412. Revision 1.15 2003/03/18 08:28:23 michael
  413. Patch from peter for Abort routine
  414. Revision 1.14 2003/03/17 15:11:51 armin
  415. + someone AssertErrorHandler, BackTraceFunc and Dump_Stack so that pointer instead of longint is needed
  416. Revision 1.13 2003/01/01 20:58:07 florian
  417. + added invalid instruction exception
  418. Revision 1.12 2002/10/07 19:43:24 florian
  419. + empty prototypes for the AnsiStr* multi byte functions added
  420. Revision 1.11 2002/09/07 16:01:22 peter
  421. * old logs removed and tabs fixed
  422. Revision 1.10 2002/07/16 13:57:39 florian
  423. * raise takes now a void pointer as at and frame address
  424. instead of a longint, fixed
  425. Revision 1.9 2002/01/25 17:42:03 peter
  426. * interface helpers
  427. Revision 1.8 2002/01/25 16:23:03 peter
  428. * merged filesearch() fix
  429. }