sysutils.inc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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. { CPU Specific code }
  57. {$i sysutilp.inc}
  58. { OS utility code }
  59. {$i osutil.inc}
  60. procedure FreeAndNil(var obj);
  61. var
  62. temp: tobject;
  63. begin
  64. temp:=tobject(obj);
  65. pointer(obj):=nil;
  66. temp.free;
  67. end;
  68. {$ifdef HASINTF}
  69. { Interfaces support }
  70. {$i sysuintf.inc}
  71. {$endif HASINTF}
  72. constructor Exception.Create(const msg : string);
  73. begin
  74. inherited create;
  75. fmessage:=msg;
  76. end;
  77. constructor Exception.CreateFmt(const msg : string; const args : array of const);
  78. begin
  79. inherited create;
  80. fmessage:=Format(msg,args);
  81. end;
  82. constructor Exception.CreateRes(ResString: PString);
  83. begin
  84. inherited create;
  85. fmessage:=ResString^;
  86. end;
  87. constructor Exception.CreateResFmt(ResString: PString; const Args: array of const);
  88. begin
  89. inherited create;
  90. fmessage:=Format(ResString^,args);
  91. end;
  92. constructor Exception.CreateHelp(const Msg: string; AHelpContext: Integer);
  93. begin
  94. inherited create;
  95. fmessage:=Msg;
  96. fhelpcontext:=AHelpContext;
  97. end;
  98. constructor Exception.CreateFmtHelp(const Msg: string; const Args: array of const;
  99. AHelpContext: Integer);
  100. begin
  101. inherited create;
  102. fmessage:=Format(Msg,args);
  103. fhelpcontext:=AHelpContext;
  104. end;
  105. constructor Exception.CreateResHelp(ResString: PString; AHelpContext: Integer);
  106. begin
  107. inherited create;
  108. fmessage:=ResString^;
  109. fhelpcontext:=AHelpContext;
  110. end;
  111. constructor Exception.CreateResFmtHelp(ResString: PString; const Args: array of const;
  112. AHelpContext: Integer);
  113. begin
  114. inherited create;
  115. fmessage:=Format(ResString^,args);
  116. fhelpcontext:=AHelpContext;
  117. end;
  118. procedure EHeapMemoryError.FreeInstance;
  119. begin
  120. if AllowFree then
  121. inherited FreeInstance;
  122. end;
  123. {$ifopt S+}
  124. {$define STACKCHECK_WAS_ON}
  125. {$S-}
  126. {$endif OPT S }
  127. Procedure CatchUnhandledException (Obj : TObject; Addr: Pointer; FrameCount: Longint; Frames: PPointer);[public,alias:'FPC_BREAK_UNHANDLED_EXCEPTION'];
  128. Var
  129. Message : String;
  130. {$IFDEF VIRTUALPASCAL}
  131. stdout:text absolute output;
  132. {$ENDIF}
  133. i : longint;
  134. begin
  135. Writeln(stdout,'An unhandled exception occurred at $',HexStr(Ptrint(Addr),sizeof(PtrInt)*2),' :');
  136. if Obj is exception then
  137. begin
  138. Message:=Exception(Obj).ClassName+' : '+Exception(Obj).Message;
  139. Writeln(stdout,Message);
  140. end
  141. else
  142. Writeln(stdout,'Exception object ',Obj.ClassName,' is not of class Exception.');
  143. if (FrameCount>0) then
  144. begin
  145. Writeln(stdout,BackTraceStrFunc(Addr));
  146. for i:=0 to FrameCount-1 do
  147. Writeln(stdout,BackTraceStrFunc(Frames[i]));
  148. end;
  149. Halt(217);
  150. end;
  151. Var OutOfMemory : EOutOfMemory;
  152. InValidPointer : EInvalidPointer;
  153. Procedure RunErrorToExcept (ErrNo : Longint; Address,Frame : Pointer);
  154. Var E : Exception;
  155. S : String;
  156. begin
  157. Case Errno of
  158. 1,203 : E:=OutOfMemory;
  159. 204 : E:=InvalidPointer;
  160. 2,3,4,5,6,100,101,102,103,105,106 : { I/O errors }
  161. begin
  162. Case Errno of
  163. 2 : S:=SFileNotFound;
  164. 3 : S:=SInvalidFileName;
  165. 4 : S:=STooManyOpenFiles;
  166. 5 : S:=SAccessDenied;
  167. 6 : S:=SInvalidFileHandle;
  168. 15 : S:=SInvalidDrive;
  169. 100 : S:=SEndOfFile;
  170. 101 : S:=SDiskFull;
  171. 102 : S:=SFileNotAssigned;
  172. 103 : S:=SFileNotOpen;
  173. 104 : S:=SFileNotOpenForInput;
  174. 105 : S:=SFileNotOpenForOutput;
  175. 106 : S:=SInvalidInput;
  176. end;
  177. E:=EinOutError.Create (S);
  178. EInoutError(E).ErrorCode:=IOresult; // Clears InOutRes !!
  179. end;
  180. // We don't set abstracterrorhandler, but we do it here.
  181. // Unless the use sets another handler we'll get here anyway...
  182. 200 : E:=EDivByZero.Create(SDivByZero);
  183. 201 : E:=ERangeError.Create(SRangeError);
  184. 205 : E:=EOverflow.Create(SOverflow);
  185. 206 : E:=EOverflow.Create(SUnderflow);
  186. 207 : E:=EInvalidOp.Create(SInvalidOp);
  187. 211 : E:=EAbstractError.Create(SAbstractError);
  188. 215 : E:=EIntOverflow.Create(SIntOverflow);
  189. 216 : E:=EAccessViolation.Create(SAccessViolation);
  190. 217 : E:=EPrivilege.Create(SPrivilege);
  191. 218 : E:=EControlC.Create(SControlC);
  192. 219 : E:=EInvalidCast.Create(SInvalidCast);
  193. 220 : E:=EVariantError.Create(SInvalidVarCast);
  194. 221 : E:=EVariantError.Create(SInvalidVarOp);
  195. 222 : E:=EVariantError.Create(SDispatchError);
  196. 223 : E:=EVariantError.Create(SVarArrayCreate);
  197. 224 : E:=EVariantError.Create(SVarNotArray);
  198. 225 : E:=EVariantError.Create(SVarArrayBounds);
  199. 227 : E:=EAssertionFailed.Create(SAssertionFailed);
  200. 228 : E:=EExternalException.Create(SExternalException);
  201. 229 : E:=EIntfCastError.Create(SIntfCastError);
  202. 230 : E:=ESafecallException.Create(SSafecallException);
  203. 232 : E:=ENoThreadSupport.Create(SNoThreadSupport);
  204. else
  205. E:=Exception.CreateFmt (SUnKnownRunTimeError,[Errno]);
  206. end;
  207. {$ifdef VER1_0}
  208. Raise E at longint(Address){$ifdef ENHANCEDRAISE},longint(Frame){$endif};
  209. {$else VER1_0}
  210. Raise E at Address,Frame;
  211. {$endif VER1_0}
  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. {$ifdef VER1_0}
  331. Raise EAbort.Create(SAbortError) at Longint(Get_Caller_addr(Get_Frame));
  332. {$else VER1_0}
  333. Raise EAbort.Create(SAbortError)
  334. {$IFNDEF VIRTUALPASCAL}
  335. at Pointer(Get_Caller_addr(Get_Frame));
  336. {$ENDIF}
  337. {$endif VER1_0}
  338. end;
  339. procedure OutOfMemoryError;
  340. begin
  341. Raise OutOfMemory;
  342. end;
  343. { ---------------------------------------------------------------------
  344. Initialization/Finalization/exit code
  345. ---------------------------------------------------------------------}
  346. Type
  347. PPRecord = ^TPRecord;
  348. TPRecord = Record
  349. Func : TTerminateProc;
  350. NextFunc : PPRecord;
  351. end;
  352. Const
  353. TPList : PPRecord = Nil;
  354. procedure AddTerminateProc(TermProc: TTerminateProc);
  355. Var
  356. TPR : PPRecord;
  357. begin
  358. New(TPR);
  359. With TPR^ do
  360. begin
  361. NextFunc:=TPList;
  362. Func:=TermProc;
  363. end;
  364. TPList:=TPR;
  365. end;
  366. function CallTerminateProcs: Boolean;
  367. Var
  368. TPR : PPRecord;
  369. begin
  370. Result:=True;
  371. TPR:=TPList;
  372. While Result and (TPR<>Nil) do
  373. begin
  374. Result:=TPR^.Func();
  375. TPR:=TPR^.NextFunc;
  376. end;
  377. end;
  378. { ---------------------------------------------------------------------
  379. Diskh functions, OS independent.
  380. ---------------------------------------------------------------------}
  381. function ForceDirectories(Const Dir: string): Boolean;
  382. var
  383. E: EInOutError;
  384. ADir : String;
  385. begin
  386. Result:=True;
  387. ADir:=ExcludeTrailingPathDelimiter(Dir);
  388. if (ADir='') then
  389. begin
  390. E:=EInOutError.Create(SCannotCreateEmptyDir);
  391. E.ErrorCode:=3;
  392. Raise E;
  393. end;
  394. if Not DirectoryExists(ADir) then
  395. begin
  396. Result:=ForceDirectories(ExtractFilePath(ADir));
  397. If Result then
  398. CreateDir(ADir);
  399. end;
  400. end;
  401. {
  402. Revision 1.1 2003/10/06 21:01:06 peter
  403. * moved classes unit to rtl
  404. Revision 1.17 2003/09/06 20:46:07 marco
  405. * 3 small VP fixes from Noah Silva. One (OutOfMemory error) failed.
  406. Revision 1.16 2003/04/06 11:06:39 michael
  407. + Added exception classname to output of unhandled exception for better identification
  408. Revision 1.15 2003/03/18 08:28:23 michael
  409. Patch from peter for Abort routine
  410. Revision 1.14 2003/03/17 15:11:51 armin
  411. + someone AssertErrorHandler, BackTraceFunc and Dump_Stack so that pointer instead of longint is needed
  412. Revision 1.13 2003/01/01 20:58:07 florian
  413. + added invalid instruction exception
  414. Revision 1.12 2002/10/07 19:43:24 florian
  415. + empty prototypes for the AnsiStr* multi byte functions added
  416. Revision 1.11 2002/09/07 16:01:22 peter
  417. * old logs removed and tabs fixed
  418. Revision 1.10 2002/07/16 13:57:39 florian
  419. * raise takes now a void pointer as at and frame address
  420. instead of a longint, fixed
  421. Revision 1.9 2002/01/25 17:42:03 peter
  422. * interface helpers
  423. Revision 1.8 2002/01/25 16:23:03 peter
  424. * merged filesearch() fix
  425. }