sysutils.inc 13 KB

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