sysutils.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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<>feInvalidHandle) 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. { 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. Constructor EVariantError.CreateCode (Code : longint);
  143. begin
  144. case Code of
  145. VAR_OK:
  146. Create(SNoError);
  147. VAR_PARAMNOTFOUND:
  148. Create(SVarParamNotFound);
  149. VAR_TYPEMISMATCH:
  150. Create(SInvalidVarCast);
  151. VAR_BADVARTYPE:
  152. Create(SVarBadType);
  153. VAR_OVERFLOW:
  154. Create(SVarOverflow);
  155. VAR_BADINDEX:
  156. Create(SVarArrayBounds);
  157. VAR_ARRAYISLOCKED:
  158. Create(SVarArrayLocked);
  159. VAR_NOTIMPL:
  160. Create(SVarNotImplemented);
  161. VAR_OUTOFMEMORY:
  162. Create(SVarOutOfMemory);
  163. VAR_INVALIDARG:
  164. Create(SVarInvalid);
  165. VAR_UNEXPECTED,
  166. VAR_EXCEPTION:
  167. Create(SVarUnexpected);
  168. else
  169. CreateFmt(SUnknownErrorCode,[Code]);
  170. end;
  171. ErrCode:=Code;
  172. end;
  173. {$ifopt S+}
  174. {$define STACKCHECK_WAS_ON}
  175. {$S-}
  176. {$endif OPT S }
  177. Procedure CatchUnhandledException (Obj : TObject; Addr: Pointer; FrameCount: Longint; Frames: PPointer);[public,alias:'FPC_BREAK_UNHANDLED_EXCEPTION'];
  178. Var
  179. Message : String;
  180. i : longint;
  181. begin
  182. Writeln(stdout,'An unhandled exception occurred at $',HexStr(Ptrint(Addr),sizeof(PtrInt)*2),' :');
  183. if Obj is exception then
  184. begin
  185. Message:=Exception(Obj).ClassName+' : '+Exception(Obj).Message;
  186. Writeln(stdout,Message);
  187. end
  188. else
  189. Writeln(stdout,'Exception object ',Obj.ClassName,' is not of class Exception.');
  190. Writeln(stdout,BackTraceStrFunc(Addr));
  191. if (FrameCount>0) then
  192. begin
  193. for i:=0 to FrameCount-1 do
  194. Writeln(stdout,BackTraceStrFunc(Frames[i]));
  195. end;
  196. Writeln(stdout,'');
  197. Halt(217);
  198. end;
  199. Var OutOfMemory : EOutOfMemory;
  200. InValidPointer : EInvalidPointer;
  201. Procedure RunErrorToExcept (ErrNo : Longint; Address,Frame : Pointer);
  202. Var E : Exception;
  203. S : String;
  204. begin
  205. Case Errno of
  206. 1,203 : E:=OutOfMemory;
  207. 204 : E:=InvalidPointer;
  208. 2,3,4,5,6,100,101,102,103,105,106 : { I/O errors }
  209. begin
  210. Case Errno of
  211. 2 : S:=SFileNotFound;
  212. 3 : S:=SInvalidFileName;
  213. 4 : S:=STooManyOpenFiles;
  214. 5 : S:=SAccessDenied;
  215. 6 : S:=SInvalidFileHandle;
  216. 15 : S:=SInvalidDrive;
  217. 100 : S:=SEndOfFile;
  218. 101 : S:=SDiskFull;
  219. 102 : S:=SFileNotAssigned;
  220. 103 : S:=SFileNotOpen;
  221. 104 : S:=SFileNotOpenForInput;
  222. 105 : S:=SFileNotOpenForOutput;
  223. 106 : S:=SInvalidInput;
  224. end;
  225. E:=EinOutError.Create (S);
  226. EInoutError(E).ErrorCode:=IOresult; // Clears InOutRes !!
  227. end;
  228. // We don't set abstracterrorhandler, but we do it here.
  229. // Unless the use sets another handler we'll get here anyway...
  230. 200 : E:=EDivByZero.Create(SDivByZero);
  231. 201 : E:=ERangeError.Create(SRangeError);
  232. 205 : E:=EOverflow.Create(SOverflow);
  233. 206 : E:=EOverflow.Create(SUnderflow);
  234. 207 : E:=EInvalidOp.Create(SInvalidOp);
  235. 211 : E:=EAbstractError.Create(SAbstractError);
  236. 214 : E:=EBusError.Create(SBusError);
  237. 215 : E:=EIntOverflow.Create(SIntOverflow);
  238. 216 : E:=EAccessViolation.Create(SAccessViolation);
  239. 217 : E:=EPrivilege.Create(SPrivilege);
  240. 218 : E:=EControlC.Create(SControlC);
  241. 219 : E:=EInvalidCast.Create(SInvalidCast);
  242. 220 : E:=EVariantError.Create(SInvalidVarCast);
  243. 221 : E:=EVariantError.Create(SInvalidVarOp);
  244. 222 : E:=EVariantError.Create(SDispatchError);
  245. 223 : E:=EVariantError.Create(SVarArrayCreate);
  246. 224 : E:=EVariantError.Create(SVarNotArray);
  247. 225 : E:=EVariantError.Create(SVarArrayBounds);
  248. 227 : E:=EAssertionFailed.Create(SAssertionFailed);
  249. 228 : E:=EExternalException.Create(SExternalException);
  250. 229 : E:=EIntfCastError.Create(SIntfCastError);
  251. 230 : E:=ESafecallException.Create(SSafecallException);
  252. 232 : E:=ENoThreadSupport.Create(SNoThreadSupport);
  253. else
  254. E:=Exception.CreateFmt (SUnKnownRunTimeError,[Errno]);
  255. end;
  256. Raise E at Address,Frame;
  257. end;
  258. {$IFDEF HAS_OSERROR}
  259. Procedure RaiseLastOSError;
  260. var
  261. ECode: Cardinal;
  262. E : EOSError;
  263. begin
  264. ECode := GetLastOSError;
  265. If (ECode<>0) then
  266. E:=EOSError.CreateFmt(SOSError, [ECode, SysErrorMessage(ECode)])
  267. else
  268. E:=EOSError.Create(SUnkOSError);
  269. E.ErrorCode:=ECode;
  270. Raise E;
  271. end;
  272. {$else}
  273. Procedure RaiseLastOSError;
  274. begin
  275. Raise Exception.Create('RaiseLastOSError not implemented on this platform.');
  276. end;
  277. {$endif}
  278. Procedure AssertErrorHandler (Const Msg,FN : ShortString;LineNo:longint; TheAddr : pointer);
  279. Var
  280. S : String;
  281. begin
  282. If Msg='' then
  283. S:=SAssertionFailed
  284. else
  285. S:=Msg;
  286. Raise EAssertionFailed.Createfmt(SAssertError,[S,Fn,LineNo]); // at Pointer(theAddr);
  287. end;
  288. {$ifdef STACKCHECK_WAS_ON}
  289. {$S+}
  290. {$endif}
  291. Procedure InitExceptions;
  292. {
  293. Must install uncaught exception handler (ExceptProc)
  294. and install exceptions for system exceptions or signals.
  295. (e.g: SIGSEGV -> ESegFault or so.)
  296. }
  297. begin
  298. ExceptProc:=@CatchUnhandledException;
  299. // Create objects that may have problems when there is no memory.
  300. OutOfMemory:=EOutOfMemory.Create(SOutOfMemory);
  301. OutOfMemory.AllowFree:=false;
  302. InvalidPointer:=EInvalidPointer.Create(SInvalidPointer);
  303. InvalidPointer.AllowFree:=false;
  304. AssertErrorProc:=@AssertErrorHandler;
  305. ErrorProc:=@RunErrorToExcept;
  306. OnShowException:=Nil;
  307. end;
  308. Procedure DoneExceptions;
  309. begin
  310. OutOfMemory.AllowFree:=true;
  311. OutOfMemory.Free;
  312. InValidPointer.AllowFree:=true;
  313. InValidPointer.Free;
  314. end;
  315. { Exception handling routines }
  316. function ExceptObject: TObject;
  317. begin
  318. If RaiseList=Nil then
  319. Result:=Nil
  320. else
  321. Result:=RaiseList^.FObject;
  322. end;
  323. function ExceptAddr: Pointer;
  324. begin
  325. If RaiseList=Nil then
  326. Result:=Nil
  327. else
  328. Result:=RaiseList^.Addr;
  329. end;
  330. function ExceptFrameCount: Longint;
  331. begin
  332. If RaiseList=Nil then
  333. Result:=0
  334. else
  335. Result:=RaiseList^.Framecount;
  336. end;
  337. function ExceptFrames: PPointer;
  338. begin
  339. If RaiseList=Nil then
  340. Result:=Nil
  341. else
  342. Result:=RaiseList^.Frames;
  343. end;
  344. function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
  345. Buffer: PChar; Size: Integer): Integer;
  346. Var
  347. S : AnsiString;
  348. Len : Integer;
  349. begin
  350. S:=Format(SExceptionErrorMessage,[ExceptAddr,ExceptObject.ClassName]);
  351. If ExceptObject is Exception then
  352. S:=Format('%s:'#10'%s',[S,Exception(ExceptObject).Message]);
  353. Len:=Length(S);
  354. If S[Len]<>'.' then
  355. begin
  356. S:=S+'.';
  357. Inc(len);
  358. end;
  359. If Len>Size then
  360. Len:=Size;
  361. if Len > 0 then
  362. Move(S[1],Buffer^,Len);
  363. Result:=Len;
  364. end;
  365. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  366. // use shortstring. On exception, the heap may be corrupt.
  367. Var
  368. Buf : ShortString;
  369. begin
  370. SetLength(Buf,ExceptionErrorMessage(ExceptObject,ExceptAddr,@Buf[1],255));
  371. If IsConsole Then
  372. writeln(Buf)
  373. else
  374. If Assigned(OnShowException) Then
  375. OnShowException (Buf);
  376. end;
  377. procedure Abort;
  378. begin
  379. Raise EAbort.Create(SAbortError) at Pointer(Get_Caller_addr(Get_Frame));
  380. end;
  381. procedure OutOfMemoryError;
  382. begin
  383. Raise OutOfMemory;
  384. end;
  385. { ---------------------------------------------------------------------
  386. Initialization/Finalization/exit code
  387. ---------------------------------------------------------------------}
  388. Type
  389. PPRecord = ^TPRecord;
  390. TPRecord = Record
  391. Func : TTerminateProc;
  392. NextFunc : PPRecord;
  393. end;
  394. Const
  395. TPList : PPRecord = Nil;
  396. procedure AddTerminateProc(TermProc: TTerminateProc);
  397. Var
  398. TPR : PPRecord;
  399. begin
  400. New(TPR);
  401. With TPR^ do
  402. begin
  403. NextFunc:=TPList;
  404. Func:=TermProc;
  405. end;
  406. TPList:=TPR;
  407. end;
  408. function CallTerminateProcs: Boolean;
  409. Var
  410. TPR : PPRecord;
  411. begin
  412. Result:=True;
  413. TPR:=TPList;
  414. While Result and (TPR<>Nil) do
  415. begin
  416. Result:=TPR^.Func();
  417. TPR:=TPR^.NextFunc;
  418. end;
  419. end;
  420. { ---------------------------------------------------------------------
  421. Diskh functions, OS independent.
  422. ---------------------------------------------------------------------}
  423. function ForceDirectories(Const Dir: string): Boolean;
  424. var
  425. E: EInOutError;
  426. ADir : String;
  427. begin
  428. Result:=True;
  429. ADir:=ExcludeTrailingPathDelimiter(Dir);
  430. if (ADir='') then
  431. begin
  432. E:=EInOutError.Create(SCannotCreateEmptyDir);
  433. E.ErrorCode:=3;
  434. Raise E;
  435. end;
  436. if Not DirectoryExists(ADir) then
  437. begin
  438. Result:=ForceDirectories(ExtractFilePath(ADir));
  439. If Result then
  440. CreateDir(ADir);
  441. end;
  442. end;
  443. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  444. Var
  445. I : Integer;
  446. P : PByte;
  447. begin
  448. P:=@Buf;
  449. Randomize;
  450. For I:=0 to NBytes-1 do
  451. P[i]:=Random(256);
  452. end;
  453. {$IFDEF HASCREATEGUID}
  454. Function SysCreateGUID(out GUID : TGUID) : Integer; forward;
  455. {$ENDIF}
  456. Function CreateGUID(out GUID : TGUID) : Integer;
  457. begin
  458. If Assigned(OnCreateGUID) then
  459. Result:=OnCreateGUID(GUID)
  460. else
  461. begin
  462. {$IFDEF HASCREATEGUID}
  463. Result:=SysCreateGUID(GUID);
  464. {$ELSE}
  465. GetRandomBytes(GUID,SizeOf(Guid));
  466. Result:=0;
  467. {$ENDIF}
  468. end;
  469. end;
  470. function SafeLoadLibrary(const FileName: AnsiString;
  471. ErrorMode: DWord = {$ifdef windows}SEM_NOOPENFILEERRORBOX{$else windows}0{$endif windows}): HMODULE;
  472. {$if defined(cpui386) or defined(cpux86_64)}
  473. var
  474. mode : DWord;
  475. fpucw : Word;
  476. ssecw : DWord;
  477. {$endif}
  478. begin
  479. {$if defined(win64) or defined(win32)}
  480. mode:=SetErrorMode(ErrorMode);
  481. {$endif}
  482. try
  483. {$if defined(cpui386) or defined(cpux86_64)}
  484. fpucw:=Get8087CW;
  485. {$ifdef cpui386}
  486. if has_sse_support then
  487. {$endif cpui386}
  488. ssecw:=GetSSECSR;
  489. {$endif}
  490. {$if defined(windows) or defined(win32)}
  491. Result:=LoadLibraryA(PChar(Filename));
  492. {$else}
  493. Result:=0;
  494. {$endif}
  495. finally
  496. {$if defined(cpui386) or defined(cpux86_64)}
  497. Set8087CW(fpucw);
  498. {$ifdef cpui386}
  499. if has_sse_support then
  500. {$endif cpui386}
  501. SetSSECSR(ssecw);
  502. {$endif}
  503. {$if defined(win64) or defined(win32)}
  504. SetErrorMode(mode);
  505. {$endif}
  506. end;
  507. end;