sysutils.inc 13 KB

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