sysutils.inc 12 KB

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