2
0

sysutils.inc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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 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. Raise EAbort.Create(SAbortError) at Pointer(Get_Caller_addr(Get_Frame));
  331. end;
  332. procedure OutOfMemoryError;
  333. begin
  334. Raise OutOfMemory;
  335. end;
  336. { ---------------------------------------------------------------------
  337. Initialization/Finalization/exit code
  338. ---------------------------------------------------------------------}
  339. Type
  340. PPRecord = ^TPRecord;
  341. TPRecord = Record
  342. Func : TTerminateProc;
  343. NextFunc : PPRecord;
  344. end;
  345. Const
  346. TPList : PPRecord = Nil;
  347. procedure AddTerminateProc(TermProc: TTerminateProc);
  348. Var
  349. TPR : PPRecord;
  350. begin
  351. New(TPR);
  352. With TPR^ do
  353. begin
  354. NextFunc:=TPList;
  355. Func:=TermProc;
  356. end;
  357. TPList:=TPR;
  358. end;
  359. function CallTerminateProcs: Boolean;
  360. Var
  361. TPR : PPRecord;
  362. begin
  363. Result:=True;
  364. TPR:=TPList;
  365. While Result and (TPR<>Nil) do
  366. begin
  367. Result:=TPR^.Func();
  368. TPR:=TPR^.NextFunc;
  369. end;
  370. end;
  371. { ---------------------------------------------------------------------
  372. Diskh functions, OS independent.
  373. ---------------------------------------------------------------------}
  374. function ForceDirectories(Const Dir: string): Boolean;
  375. var
  376. E: EInOutError;
  377. ADir : String;
  378. begin
  379. Result:=True;
  380. ADir:=ExcludeTrailingPathDelimiter(Dir);
  381. if (ADir='') then
  382. begin
  383. E:=EInOutError.Create(SCannotCreateEmptyDir);
  384. E.ErrorCode:=3;
  385. Raise E;
  386. end;
  387. if Not DirectoryExists(ADir) then
  388. begin
  389. Result:=ForceDirectories(ExtractFilePath(ADir));
  390. If Result then
  391. CreateDir(ADir);
  392. end;
  393. end;
  394. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  395. Var
  396. I : Integer;
  397. P : PByte;
  398. begin
  399. P:=@Buf;
  400. Randomize;
  401. For I:=0 to NBytes-1 do
  402. P[i]:=Random(256);
  403. end;
  404. {$IFDEF HASCREATEGUID}
  405. Function SysCreateGUID(out GUID : TGUID) : Integer; forward;
  406. {$ENDIF}
  407. Function CreateGUID(out GUID : TGUID) : Integer;
  408. begin
  409. If Assigned(OnCreateGUID) then
  410. Result:=OnCreateGUID(GUID)
  411. else
  412. begin
  413. {$IFDEF HASCREATEGUID}
  414. Result:=SysCreateGUID(GUID);
  415. {$ELSE}
  416. GetRandomBytes(GUID,SizeOf(Guid));
  417. Result:=0;
  418. {$ENDIF}
  419. end;
  420. end;
  421. {
  422. Revision 1.1 2003/10/06 21:01:06 peter
  423. * moved classes unit to rtl
  424. Revision 1.17 2003/09/06 20:46:07 marco
  425. * 3 small VP fixes from Noah Silva. One (OutOfMemory error) failed.
  426. Revision 1.16 2003/04/06 11:06:39 michael
  427. + Added exception classname to output of unhandled exception for better identification
  428. Revision 1.15 2003/03/18 08:28:23 michael
  429. Patch from peter for Abort routine
  430. Revision 1.14 2003/03/17 15:11:51 armin
  431. + someone AssertErrorHandler, BackTraceFunc and Dump_Stack so that pointer instead of longint is needed
  432. Revision 1.13 2003/01/01 20:58:07 florian
  433. + added invalid instruction exception
  434. Revision 1.12 2002/10/07 19:43:24 florian
  435. + empty prototypes for the AnsiStr* multi byte functions added
  436. Revision 1.11 2002/09/07 16:01:22 peter
  437. * old logs removed and tabs fixed
  438. Revision 1.10 2002/07/16 13:57:39 florian
  439. * raise takes now a void pointer as at and frame address
  440. instead of a longint, fixed
  441. Revision 1.9 2002/01/25 17:42:03 peter
  442. * interface helpers
  443. Revision 1.8 2002/01/25 16:23:03 peter
  444. * merged filesearch() fix
  445. }