system.pp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 1999-2005 by Florian Klaempfl and Pavel Ozerski
  4. and Yury Sidorov member of the Free Pascal development team.
  5. FPC Pascal system unit for the WinCE.
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. **********************************************************************}
  12. unit System;
  13. interface
  14. {$define FPC_IS_SYSTEM}
  15. {$ifdef SYSTEMDEBUG}
  16. {$define SYSTEMEXCEPTIONDEBUG}
  17. {$endif SYSTEMDEBUG}
  18. {$define WINCE_EXCEPTION_HANDLING}
  19. {$define DISABLE_NO_THREAD_MANAGER}
  20. {$define HAS_CMDLINE}
  21. {$define HAS_MEMORYMANAGER} // comment this line to switch from wincemm to fpcmm
  22. {$define HAS_WIDESTRINGMANAGER}
  23. {$define DISABLE_NO_DYNLIBS_MANAGER}
  24. {$define FPC_SYSTEM_HAS_SYSDLH}
  25. { include system-independent routine headers }
  26. {$I systemh.inc}
  27. const
  28. LineEnding = #13#10;
  29. LFNSupport = true;
  30. DirectorySeparator = '\';
  31. DriveSeparator = ':';
  32. ExtensionSeparator = '.';
  33. PathSeparator = ';';
  34. AllowDirectorySeparators : set of char = ['\','/'];
  35. AllowDriveSeparators : set of char = [':'];
  36. { FileNameCaseSensitive and FileNameCasePreserving are defined separately below!!! }
  37. maxExitCode = 65535;
  38. MaxPathLen = 260;
  39. AllFilesMask = '*';
  40. const
  41. { Default filehandles }
  42. UnusedHandle : THandle = THandle(-1);
  43. StdInputHandle : THandle = 0;
  44. StdOutputHandle : THandle = 0;
  45. StdErrorHandle : THandle = 0;
  46. FileNameCaseSensitive : boolean = false;
  47. FileNameCasePreserving: boolean = true;
  48. CtrlZMarksEOF: boolean = true; (* #26 is considered as end of file *)
  49. sLineBreak = LineEnding;
  50. DefaultTextLineBreakStyle : TTextLineBreakStyle = tlbsCRLF;
  51. var
  52. { WinCE Info }
  53. hprevinst,
  54. MainInstance,
  55. DLLreason,DLLparam:DWord;
  56. type
  57. TDLL_Entry_Hook = procedure (dllparam : longint);
  58. const
  59. Dll_Process_Detach_Hook : TDLL_Entry_Hook = nil;
  60. Dll_Thread_Attach_Hook : TDLL_Entry_Hook = nil;
  61. Dll_Thread_Detach_Hook : TDLL_Entry_Hook = nil;
  62. { ANSI <-> Wide }
  63. function AnsiToWideBuf(AnsiBuf: PChar; AnsiBufLen: longint; WideBuf: PWideChar; WideBufLen: longint): longint;
  64. function WideToAnsiBuf(WideBuf: PWideChar; WideCharsLen: longint; AnsiBuf: PChar; AnsiBufLen: longint): longint;
  65. function PCharToPWideChar(str: PChar; strlen: longint = -1; outlen: PLongInt = nil): PWideChar;
  66. function StringToPWideChar(const s: AnsiString; outlen: PLongInt = nil): PWideChar;
  67. { Wrappers for some WinAPI calls }
  68. function CreateEvent(lpEventAttributes:pointer;bManualReset:longbool;bInitialState:longbool;lpName:pchar): THandle;
  69. function ResetEvent(h: THandle): LONGBOOL;
  70. function SetEvent(h: THandle): LONGBOOL;
  71. function GetCurrentProcessId:DWORD;
  72. function Win32GetCurrentThreadId:DWORD;
  73. function TlsAlloc : DWord;
  74. function TlsFree(dwTlsIndex : DWord) : LongBool;
  75. function GetFileAttributesW(p : pwidechar) : dword;
  76. cdecl; external KernelDLL name 'GetFileAttributesW';
  77. function DeleteFileW(p : pwidechar) : longint;
  78. cdecl; external KernelDLL name 'DeleteFileW';
  79. function MoveFileW(old,_new : pwidechar) : longint;
  80. cdecl; external KernelDLL name 'MoveFileW';
  81. function CreateFileW(lpFileName:pwidechar; dwDesiredAccess:DWORD; dwShareMode:DWORD;
  82. lpSecurityAttributes:pointer; dwCreationDisposition:DWORD;
  83. dwFlagsAndAttributes:DWORD; hTemplateFile:DWORD):longint;
  84. cdecl; external KernelDLL name 'CreateFileW';
  85. {$ifdef CPUARM}
  86. { the external directive isn't really necessary here because it is overridden by external (FK) }
  87. function addd(d1,d2 : double) : double; compilerproc;
  88. cdecl;external 'coredll' name '__addd';
  89. function subd(d1,d2 : double) : double; compilerproc;
  90. cdecl;external 'coredll' name '__subd';
  91. function muld(d1,d2 : double) : double; compilerproc;
  92. cdecl;external 'coredll' name '__muld';
  93. function divd(d1,d2 : double) : double; compilerproc;
  94. cdecl;external 'coredll' name '__divd';
  95. function eqd(d1,d2 : double) : boolean; compilerproc;
  96. cdecl;external 'coredll' name '__eqd';
  97. function ned(d1,d2 : double) : boolean; compilerproc;
  98. cdecl;external 'coredll' name '__ned';
  99. function ltd(d1,d2 : double) : boolean; compilerproc;
  100. cdecl;external 'coredll' name '__ltd';
  101. function gtd(d1,d2 : double) : boolean; compilerproc;
  102. cdecl;external 'coredll' name '__gtd';
  103. function ged(d1,d2 : double) : boolean; compilerproc;
  104. cdecl;external 'coredll' name '__ged';
  105. function led(d1,d2 : double) : boolean; compilerproc;
  106. cdecl;external 'coredll' name '__led';
  107. { ***************** single ******************** }
  108. function eqs(d1,d2 : single) : boolean; compilerproc;
  109. cdecl;external 'coredll' name '__eqs';
  110. function nes(d1,d2 : single) : boolean; compilerproc;
  111. cdecl;external 'coredll' name '__nes';
  112. function lts(d1,d2 : single) : boolean; compilerproc;
  113. cdecl;external 'coredll' name '__lts';
  114. function gts(d1,d2 : single) : boolean; compilerproc;
  115. cdecl;external 'coredll' name '__gts';
  116. function ges(d1,d2 : single) : boolean; compilerproc;
  117. cdecl;external 'coredll' name '__ges';
  118. function les(d1,d2 : single) : boolean; compilerproc;
  119. cdecl;external 'coredll' name '__les';
  120. function dtos(d : double) : single; compilerproc;
  121. cdecl;external 'coredll' name '__dtos';
  122. function stod(d : single) : double; compilerproc;
  123. cdecl;external 'coredll' name '__stod';
  124. function negs(d : single) : single; compilerproc;
  125. cdecl;external 'coredll' name '__negs';
  126. function negd(d : double) : double; compilerproc;
  127. cdecl;external 'coredll' name '__negd';
  128. function utod(i : dword) : double; compilerproc;
  129. cdecl;external 'coredll' name '__utod';
  130. function itod(i : longint) : double; compilerproc;
  131. cdecl;external 'coredll' name '__itod';
  132. function ui64tod(i : qword) : double; compilerproc;
  133. cdecl;external 'coredll' name '__u64tod';
  134. function i64tod(i : int64) : double; compilerproc;
  135. cdecl;external 'coredll' name '__i64tod';
  136. function utos(i : dword) : single; compilerproc;
  137. cdecl;external 'coredll' name '__utos';
  138. function itos(i : longint) : single; compilerproc;
  139. cdecl;external 'coredll' name '__itos';
  140. function ui64tos(i : qword) : single; compilerproc;
  141. cdecl;external 'coredll' name '__u64tos';
  142. function i64tos(i : int64) : single; compilerproc;
  143. cdecl;external 'coredll' name '__i64tos';
  144. function adds(s1,s2 : single) : single; compilerproc;
  145. function subs(s1,s2 : single) : single; compilerproc;
  146. function muls(s1,s2 : single) : single; compilerproc;
  147. function divs(s1,s2 : single) : single; compilerproc;
  148. {$endif CPUARM}
  149. function CmdLine: PChar;
  150. { C compatible arguments }
  151. function argc: longint;
  152. function argv: ppchar;
  153. implementation
  154. var
  155. SysInstance : Longint;public name '_FPC_SysInstance';
  156. function MessageBox(w1:longint;l1,l2:PWideChar;w2:longint):longint;
  157. cdecl; external 'coredll' name 'MessageBoxW';
  158. function CreateDirectoryW(name : pwidechar;sec : pointer) : longbool;
  159. cdecl; external KernelDLL name 'CreateDirectoryW';
  160. function RemoveDirectoryW(name:pwidechar):longbool;
  161. cdecl; external KernelDLL name 'RemoveDirectoryW';
  162. {*****************************************************************************}
  163. {$define FPC_SYSTEM_HAS_MOVE}
  164. procedure memmove(dest, src: pointer; count: longint);
  165. cdecl; external 'coredll' name 'memmove';
  166. procedure Move(const source;var dest;count:SizeInt);[public, alias: 'FPC_MOVE'];
  167. begin
  168. if count > 0 then
  169. memmove(@dest, @source, count);
  170. end;
  171. {$define FPC_SYSTEM_HAS_COMPAREBYTE}
  172. function memcmp(buf1, buf2: pointer; count: longint): longint;
  173. cdecl; external 'coredll' name 'memcmp';
  174. function CompareByte(Const buf1,buf2;len:SizeInt):SizeInt;
  175. begin
  176. CompareByte := memcmp(@buf1, @buf2, len);
  177. end;
  178. {$ifdef CPUARM}
  179. {$define FPC_SYSTEM_HAS_INT}
  180. function floor(d : double) : double;
  181. cdecl;external 'coredll' name 'floor';
  182. function ceil(d : double) : double;
  183. cdecl;external 'coredll' name 'ceil';
  184. function fpc_int_real(d: ValReal): ValReal;compilerproc;
  185. begin
  186. if d > 0 then
  187. fpc_int_real:=floor(d)
  188. else
  189. fpc_int_real:=ceil(d);
  190. end;
  191. {$define FPC_SYSTEM_HAS_TRUNC}
  192. function __dtoi64(d: double) : int64; cdecl; external 'coredll';
  193. function fpc_trunc_real(d : ValReal) : int64; assembler; nostackframe; compilerproc;
  194. asm
  195. b __dtoi64
  196. end;
  197. {$define FPC_SYSTEM_HAS_ABS}
  198. function fabs(d: double): double; cdecl; external 'coredll';
  199. function fpc_abs_real(d : ValReal) : ValReal; assembler; nostackframe; compilerproc;
  200. asm
  201. b fabs
  202. end;
  203. {$define FPC_SYSTEM_HAS_SQRT}
  204. function coresqrt(d: double): double; cdecl; external 'coredll' name 'sqrt';
  205. function fpc_sqrt_real(d : ValReal) : ValReal; assembler; nostackframe; compilerproc;
  206. asm
  207. b coresqrt
  208. end;
  209. function adds(s1,s2 : single) : single;
  210. begin
  211. adds := addd(s1, s2);
  212. end;
  213. function subs(s1,s2 : single) : single;
  214. begin
  215. subs := subd(s1, s2);
  216. end;
  217. function muls(s1,s2 : single) : single;
  218. begin
  219. muls := muld(s1, s2);
  220. end;
  221. function divs(s1,s2 : single) : single;
  222. begin
  223. divs := divd(s1, s2);
  224. end;
  225. {$endif CPUARM}
  226. {*****************************************************************************}
  227. { include system independent routines }
  228. {$I system.inc}
  229. {*****************************************************************************
  230. ANSI <-> Wide
  231. *****************************************************************************}
  232. const
  233. { MultiByteToWideChar }
  234. MB_PRECOMPOSED = 1;
  235. MB_COMPOSITE = 2;
  236. MB_ERR_INVALID_CHARS = 8;
  237. MB_USEGLYPHCHARS = 4;
  238. function MultiByteToWideChar(CodePage:UINT; dwFlags:DWORD; lpMultiByteStr:PChar; cchMultiByte:longint; lpWideCharStr:PWideChar;cchWideChar:longint):longint;
  239. cdecl; external 'coredll' name 'MultiByteToWideChar';
  240. function WideCharToMultiByte(CodePage:UINT; dwFlags:DWORD; lpWideCharStr:PWideChar; cchWideChar:longint; lpMultiByteStr:PChar;cchMultiByte:longint; lpDefaultChar:PChar; lpUsedDefaultChar:pointer):longint;
  241. cdecl; external 'coredll' name 'WideCharToMultiByte';
  242. function GetACP:UINT; cdecl; external 'coredll' name 'GetACP';
  243. { Returns number of characters stored to WideBuf, including null-terminator. }
  244. function AnsiToWideBuf(AnsiBuf: PChar; AnsiBufLen: longint; WideBuf: PWideChar; WideBufLen: longint): longint;
  245. begin
  246. Result := MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, AnsiBuf, AnsiBufLen, WideBuf, WideBufLen div SizeOf(WideChar));
  247. if ((AnsiBufLen <> -1) or (Result = 0)) and (WideBuf <> nil) then
  248. begin
  249. if (Result + 1)*SizeOf(WideChar) > WideBufLen then
  250. begin
  251. Result := 0;
  252. if WideBufLen < SizeOf(WideChar) then
  253. exit;
  254. end;
  255. WideBuf[Result] := #0;
  256. end;
  257. if (AnsiBufLen <> -1) and ((Result <> 0) or (AnsiBufLen = 0)) then
  258. Inc(Result);
  259. end;
  260. { Returns number of characters stored to AnsiBuf, including null-terminator. }
  261. function WideToAnsiBuf(WideBuf: PWideChar; WideCharsLen: longint; AnsiBuf: PChar; AnsiBufLen: longint): longint;
  262. begin
  263. Result := WideCharToMultiByte(CP_ACP, 0, WideBuf, WideCharsLen, AnsiBuf, AnsiBufLen, nil, nil);
  264. if ((WideCharsLen <> -1) or (Result = 0)) and (AnsiBuf <> nil) then
  265. begin
  266. if Result + 1 > AnsiBufLen then
  267. begin
  268. Result := 0;
  269. if AnsiBufLen < 1 then
  270. exit;
  271. end;
  272. AnsiBuf[Result] := #0;
  273. end;
  274. if (WideCharsLen <> -1) and ((Result <> 0) or (WideCharsLen = 0)) then
  275. Inc(Result);
  276. end;
  277. { Returns dynamic memory block, which contains wide string. This memory should be freed using FreeMem. }
  278. { outlen will contain number of wide characters stored to result buffer, including null-terminator. }
  279. function PCharToPWideChar(str: PChar; strlen: longint = -1; outlen: PLongInt = nil): PWideChar;
  280. var
  281. len: longint;
  282. begin
  283. while True do begin
  284. if strlen <> -1 then
  285. len:=strlen + 1
  286. else
  287. len:=AnsiToWideBuf(str, -1, nil, 0);
  288. if len > 0 then
  289. begin
  290. len:=len*SizeOf(WideChar);
  291. GetMem(Result, len);
  292. len:=AnsiToWideBuf(str, strlen, Result, len);
  293. if (len = 0) and (strlen <> -1) then
  294. begin
  295. FreeMem(Result);
  296. strlen:=-1;
  297. continue;
  298. end;
  299. end
  300. else begin
  301. GetMem(Result, SizeOf(WideChar));
  302. len:=1;
  303. Result^:=#0;
  304. end;
  305. break;
  306. end;
  307. if outlen <> nil then
  308. outlen^:=len;
  309. end;
  310. { Returns dynamic memory block, which contains wide string. This memory should be freed using FreeMem. }
  311. { outlen will contain number of wide characters stored to result buffer, including null-terminator. }
  312. function StringToPWideChar(const s: AnsiString; outlen: PLongInt = nil): PWideChar;
  313. var
  314. len, wlen: longint;
  315. begin
  316. len:=Length(s);
  317. wlen:=(len + 1)*SizeOf(WideChar);
  318. GetMem(Result, wlen);
  319. wlen:=AnsiToWideBuf(PChar(s), len, Result, wlen)*SizeOf(WideChar);
  320. if wlen = 0 then
  321. begin
  322. wlen:=AnsiToWideBuf(PChar(s), len, nil, 0)*SizeOf(WideChar);
  323. if wlen > 0 then
  324. begin
  325. ReAllocMem(Result, wlen);
  326. wlen:=AnsiToWideBuf(PChar(s), len, Result, wlen)*SizeOf(WideChar);
  327. end
  328. else
  329. begin
  330. Result^:=#0;
  331. wlen:=SizeOf(WideChar);
  332. end;
  333. end;
  334. if outlen <> nil then
  335. outlen^:=wlen div SizeOf(WideChar);
  336. end;
  337. {*****************************************************************************
  338. WinAPI wrappers implementation
  339. *****************************************************************************}
  340. const
  341. {$ifdef CPUARM}
  342. UserKData = $FFFFC800;
  343. {$else CPUARM}
  344. UserKData = $00005800;
  345. {$endif CPUARM}
  346. SYSHANDLE_OFFSET = $004;
  347. SYS_HANDLE_BASE = 64;
  348. SH_CURTHREAD = 1;
  349. SH_CURPROC = 2;
  350. type
  351. PHandle = ^THandle;
  352. const
  353. EVENT_PULSE = 1;
  354. EVENT_RESET = 2;
  355. EVENT_SET = 3;
  356. function CreateEventW(lpEventAttributes:pointer;bManualReset:longbool;bInitialState:longbool;lpName:PWideChar): THandle;
  357. cdecl; external KernelDLL name 'CreateEventW';
  358. function CreateEvent(lpEventAttributes:pointer;bManualReset:longbool;bInitialState:longbool;lpName:pchar): THandle;
  359. var
  360. buf: array[0..MaxPathLen] of WideChar;
  361. begin
  362. if lpName=nil then
  363. CreateEvent := CreateEventW(lpEventAttributes, bManualReset, bInitialState, nil)
  364. else begin
  365. AnsiToWideBuf(lpName, -1, buf, SizeOf(buf));
  366. CreateEvent := CreateEventW(lpEventAttributes, bManualReset, bInitialState, buf);
  367. end;
  368. end;
  369. function EventModify(h: THandle; func: DWORD): LONGBOOL;
  370. cdecl; external KernelDLL name 'EventModify';
  371. function TlsCall(p1, p2: DWORD): DWORD;
  372. cdecl; external KernelDLL name 'TlsCall';
  373. function ResetEvent(h: THandle): LONGBOOL;
  374. begin
  375. ResetEvent := EventModify(h,EVENT_RESET);
  376. end;
  377. function SetEvent(h: THandle): LONGBOOL;
  378. begin
  379. SetEvent := EventModify(h,EVENT_SET);
  380. end;
  381. function GetCurrentProcessId:DWORD;
  382. var
  383. p: PHandle;
  384. begin
  385. p:=PHandle(UserKData+SYSHANDLE_OFFSET + SH_CURPROC*SizeOf(THandle));
  386. GetCurrentProcessId := p^;
  387. end;
  388. function Win32GetCurrentThreadId:DWORD;
  389. var
  390. p: PHandle;
  391. begin
  392. p:=PHandle(UserKData+SYSHANDLE_OFFSET + SH_CURTHREAD*SizeOf(THandle));
  393. Win32GetCurrentThreadId := p^;
  394. end;
  395. const
  396. TLS_FUNCALLOC = 0;
  397. TLS_FUNCFREE = 1;
  398. function TlsAlloc : DWord;
  399. begin
  400. TlsAlloc := TlsCall(TLS_FUNCALLOC, 0);
  401. end;
  402. function TlsFree(dwTlsIndex : DWord) : LongBool;
  403. begin
  404. TlsFree := LongBool(TlsCall(TLS_FUNCFREE, dwTlsIndex));
  405. end;
  406. {*****************************************************************************
  407. Parameter Handling
  408. *****************************************************************************}
  409. function GetCommandLine : pwidechar;
  410. cdecl; external KernelDLL name 'GetCommandLineW';
  411. var
  412. ModuleName : array[0..255] of char;
  413. function GetCommandFile:pchar;
  414. var
  415. buf: array[0..MaxPathLen] of WideChar;
  416. begin
  417. if ModuleName[0] = #0 then begin
  418. GetModuleFileName(0, @buf, SizeOf(buf));
  419. WideToAnsiBuf(buf, -1, @ModuleName, SizeOf(ModuleName));
  420. end;
  421. GetCommandFile:=@ModuleName;
  422. end;
  423. var
  424. Fargc: longint;
  425. Fargv: ppchar;
  426. FCmdLine: PChar;
  427. procedure setup_arguments;
  428. var
  429. arglen,
  430. count : longint;
  431. argstart,
  432. pc,arg : pchar;
  433. quote : char;
  434. argvlen : longint;
  435. procedure allocarg(idx,len:longint);
  436. var
  437. oldargvlen : longint;
  438. begin
  439. if idx>=argvlen then
  440. begin
  441. oldargvlen:=argvlen;
  442. argvlen:=(idx+8) and (not 7);
  443. sysreallocmem(Fargv,argvlen*sizeof(pointer));
  444. fillchar(Fargv[oldargvlen],(argvlen-oldargvlen)*sizeof(pointer),0);
  445. end;
  446. { use realloc to reuse already existing memory }
  447. { always allocate, even if length is zero, since }
  448. { the arg. is still present! }
  449. sysreallocmem(Fargv[idx],len+1);
  450. end;
  451. begin
  452. { create commandline, it starts with the executed filename which is argv[0] }
  453. { WinCE passes the command NOT via the args, but via getmodulefilename}
  454. if FCmdLine <> nil then exit;
  455. argvlen:=0;
  456. pc:=getcommandfile;
  457. Arglen:=0;
  458. while pc[Arglen] <> #0 do
  459. Inc(Arglen);
  460. allocarg(0,arglen);
  461. move(pc^,Fargv[0]^,arglen+1);
  462. { Setup FCmdLine variable }
  463. arg:=PChar(GetCommandLine);
  464. count:=WideToAnsiBuf(PWideChar(arg), -1, nil, 0);
  465. FCmdLine:=SysGetMem(arglen + count + 3);
  466. FCmdLine^:='"';
  467. move(pc^, (FCmdLine + 1)^, arglen);
  468. (FCmdLine + arglen + 1)^:='"';
  469. (FCmdLine + arglen + 2)^:=' ';
  470. WideToAnsiBuf(PWideChar(arg), -1, FCmdLine + arglen + 3, count);
  471. { process arguments }
  472. count:=0;
  473. pc:=FCmdLine;
  474. {$IfDef SYSTEM_DEBUG_STARTUP}
  475. Writeln(stderr,'WinCE GetCommandLine is #',pc,'#');
  476. {$EndIf }
  477. while pc^<>#0 do
  478. begin
  479. { skip leading spaces }
  480. while pc^ in [#1..#32] do
  481. inc(pc);
  482. if pc^=#0 then
  483. break;
  484. { calc argument length }
  485. quote:=' ';
  486. argstart:=pc;
  487. arglen:=0;
  488. while (pc^<>#0) do
  489. begin
  490. case pc^ of
  491. #1..#32 :
  492. begin
  493. if quote<>' ' then
  494. inc(arglen)
  495. else
  496. break;
  497. end;
  498. '"' :
  499. begin
  500. if quote<>'''' then
  501. begin
  502. if pchar(pc+1)^<>'"' then
  503. begin
  504. if quote='"' then
  505. quote:=' '
  506. else
  507. quote:='"';
  508. end
  509. else
  510. inc(pc);
  511. end
  512. else
  513. inc(arglen);
  514. end;
  515. '''' :
  516. begin
  517. if quote<>'"' then
  518. begin
  519. if pchar(pc+1)^<>'''' then
  520. begin
  521. if quote='''' then
  522. quote:=' '
  523. else
  524. quote:='''';
  525. end
  526. else
  527. inc(pc);
  528. end
  529. else
  530. inc(arglen);
  531. end;
  532. else
  533. inc(arglen);
  534. end;
  535. inc(pc);
  536. end;
  537. { copy argument }
  538. { Don't copy the first one, it is already there.}
  539. If Count<>0 then
  540. begin
  541. allocarg(count,arglen);
  542. quote:=' ';
  543. pc:=argstart;
  544. arg:=Fargv[count];
  545. while (pc^<>#0) do
  546. begin
  547. case pc^ of
  548. #1..#32 :
  549. begin
  550. if quote<>' ' then
  551. begin
  552. arg^:=pc^;
  553. inc(arg);
  554. end
  555. else
  556. break;
  557. end;
  558. '"' :
  559. begin
  560. if quote<>'''' then
  561. begin
  562. if pchar(pc+1)^<>'"' then
  563. begin
  564. if quote='"' then
  565. quote:=' '
  566. else
  567. quote:='"';
  568. end
  569. else
  570. inc(pc);
  571. end
  572. else
  573. begin
  574. arg^:=pc^;
  575. inc(arg);
  576. end;
  577. end;
  578. '''' :
  579. begin
  580. if quote<>'"' then
  581. begin
  582. if pchar(pc+1)^<>'''' then
  583. begin
  584. if quote='''' then
  585. quote:=' '
  586. else
  587. quote:='''';
  588. end
  589. else
  590. inc(pc);
  591. end
  592. else
  593. begin
  594. arg^:=pc^;
  595. inc(arg);
  596. end;
  597. end;
  598. else
  599. begin
  600. arg^:=pc^;
  601. inc(arg);
  602. end;
  603. end;
  604. inc(pc);
  605. end;
  606. arg^:=#0;
  607. end;
  608. {$IfDef SYSTEM_DEBUG_STARTUP}
  609. Writeln(stderr,'dos arg ',count,' #',arglen,'#',Fargv[count],'#');
  610. {$EndIf SYSTEM_DEBUG_STARTUP}
  611. inc(count);
  612. end;
  613. { get argc and create an nil entry }
  614. Fargc:=count;
  615. allocarg(argc,0);
  616. { free unused memory }
  617. sysreallocmem(Fargv,(argc+1)*sizeof(pointer));
  618. end;
  619. function CmdLine: PChar;
  620. begin
  621. setup_arguments;
  622. Result:=FCmdLine;
  623. end;
  624. function argc: longint;
  625. begin
  626. setup_arguments;
  627. Result:=Fargc;
  628. end;
  629. function argv: ppchar;
  630. begin
  631. setup_arguments;
  632. Result:=Fargv;
  633. end;
  634. function paramcount : longint;
  635. begin
  636. paramcount := argc - 1;
  637. end;
  638. function paramstr(l : longint) : string;
  639. begin
  640. setup_arguments;
  641. if (l>=0) and (l<Fargc) then
  642. paramstr:=strpas(Fargv[l])
  643. else
  644. paramstr:='';
  645. end;
  646. procedure randomize;
  647. begin
  648. randseed:=GetTickCount;
  649. end;
  650. {*****************************************************************************
  651. System Dependent Exit code
  652. *****************************************************************************}
  653. procedure PascalMain;external name 'PASCALMAIN';
  654. procedure ExitThread(Exitcode : longint); cdecl; external 'coredll';
  655. Procedure system_exit;
  656. begin
  657. if IsLibrary then
  658. exit;
  659. if not IsConsole then
  660. begin
  661. Close(stderr);
  662. Close(stdout);
  663. Close(erroutput);
  664. Close(Input);
  665. Close(Output);
  666. end;
  667. ExitThread(exitcode);
  668. end;
  669. {$ifdef cpu386}
  670. var
  671. { value of the stack segment
  672. to check if the call stack can be written on exceptions }
  673. _SS : Cardinal;
  674. {$endif cpu386}
  675. function Dll_entry : longbool;[public, alias : '_FPC_DLL_Entry'];
  676. begin
  677. IsLibrary:=true;
  678. Dll_entry:=false;
  679. case DLLreason of
  680. DLL_PROCESS_ATTACH :
  681. begin
  682. PASCALMAIN;
  683. Dll_entry:=true;
  684. end;
  685. DLL_THREAD_ATTACH :
  686. begin
  687. { Allocate Threadvars ?!}
  688. if assigned(Dll_Thread_Attach_Hook) then
  689. Dll_Thread_Attach_Hook(DllParam);
  690. end;
  691. DLL_THREAD_DETACH :
  692. begin
  693. if assigned(Dll_Thread_Detach_Hook) then
  694. Dll_Thread_Detach_Hook(DllParam);
  695. { Release Threadvars ?!}
  696. end;
  697. DLL_PROCESS_DETACH :
  698. begin
  699. Lib_Exit;
  700. if assigned(Dll_Process_Detach_Hook) then
  701. Dll_Process_Detach_Hook(DllParam);
  702. end;
  703. end;
  704. end;
  705. {$ifdef WINCE_EXCEPTION_HANDLING}
  706. //
  707. // Hardware exception handling
  708. //
  709. {
  710. Error code definitions for the WinCE API functions
  711. Values are 32 bit values layed out as follows:
  712. 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
  713. 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
  714. +---+-+-+-----------------------+-------------------------------+
  715. |Sev|C|R| Facility | Code |
  716. +---+-+-+-----------------------+-------------------------------+
  717. where
  718. Sev - is the severity code
  719. 00 - Success
  720. 01 - Informational
  721. 10 - Warning
  722. 11 - Error
  723. C - is the Customer code flag
  724. R - is a reserved bit
  725. Facility - is the facility code
  726. Code - is the facility's status code
  727. }
  728. const
  729. SEVERITY_SUCCESS = $00000000;
  730. SEVERITY_INFORMATIONAL = $40000000;
  731. SEVERITY_WARNING = $80000000;
  732. SEVERITY_ERROR = $C0000000;
  733. const
  734. STATUS_SEGMENT_NOTIFICATION = $40000005;
  735. DBG_TERMINATE_THREAD = $40010003;
  736. DBG_TERMINATE_PROCESS = $40010004;
  737. DBG_CONTROL_C = $40010005;
  738. DBG_CONTROL_BREAK = $40010008;
  739. STATUS_GUARD_PAGE_VIOLATION = $80000001;
  740. STATUS_DATATYPE_MISALIGNMENT = $80000002;
  741. STATUS_BREAKPOINT = $80000003;
  742. STATUS_SINGLE_STEP = $80000004;
  743. DBG_EXCEPTION_NOT_HANDLED = $80010001;
  744. STATUS_ACCESS_VIOLATION = $C0000005;
  745. STATUS_IN_PAGE_ERROR = $C0000006;
  746. STATUS_INVALID_HANDLE = $C0000008;
  747. STATUS_NO_MEMORY = $C0000017;
  748. STATUS_ILLEGAL_INSTRUCTION = $C000001D;
  749. STATUS_NONCONTINUABLE_EXCEPTION = $C0000025;
  750. STATUS_INVALID_DISPOSITION = $C0000026;
  751. STATUS_ARRAY_BOUNDS_EXCEEDED = $C000008C;
  752. STATUS_FLOAT_DENORMAL_OPERAND = $C000008D;
  753. STATUS_FLOAT_DIVIDE_BY_ZERO = $C000008E;
  754. STATUS_FLOAT_INEXACT_RESULT = $C000008F;
  755. STATUS_FLOAT_INVALID_OPERATION = $C0000090;
  756. STATUS_FLOAT_OVERFLOW = $C0000091;
  757. STATUS_FLOAT_STACK_CHECK = $C0000092;
  758. STATUS_FLOAT_UNDERFLOW = $C0000093;
  759. STATUS_INTEGER_DIVIDE_BY_ZERO = $C0000094;
  760. STATUS_INTEGER_OVERFLOW = $C0000095;
  761. STATUS_PRIVILEGED_INSTRUCTION = $C0000096;
  762. STATUS_STACK_OVERFLOW = $C00000FD;
  763. STATUS_CONTROL_C_EXIT = $C000013A;
  764. STATUS_FLOAT_MULTIPLE_FAULTS = $C00002B4;
  765. STATUS_FLOAT_MULTIPLE_TRAPS = $C00002B5;
  766. STATUS_REG_NAT_CONSUMPTION = $C00002C9;
  767. const
  768. ExceptionContinueExecution = 0;
  769. ExceptionContinueSearch = 1;
  770. ExceptionNestedException = 2;
  771. ExceptionCollidedUnwind = 3;
  772. ExceptionExecuteHandler = 4;
  773. MaxExceptionLevel = 16;
  774. exceptLevel : Byte = 0;
  775. {$ifdef CPUARM}
  776. const
  777. CONTEXT_ARM = $0000040;
  778. CONTEXT_CONTROL = CONTEXT_ARM or $00000001;
  779. CONTEXT_INTEGER = CONTEXT_ARM or $00000002;
  780. CONTEXT_SEGMENTS = CONTEXT_ARM or $00000004;
  781. CONTEXT_FLOATING_POINT = CONTEXT_ARM or $00000008;
  782. CONTEXT_DEBUG_REGISTERS = CONTEXT_ARM or $00000010;
  783. CONTEXT_EXTENDED_REGISTERS = CONTEXT_ARM or $00000020;
  784. CONTEXT_FULL = CONTEXT_CONTROL or CONTEXT_INTEGER or CONTEXT_SEGMENTS;
  785. NUM_VFP_REGS = 32;
  786. NUM_EXTRA_CONTROL_REGS = 8;
  787. type
  788. PContext = ^TContext;
  789. TContext = record
  790. ContextFlags : LongWord;
  791. // This section is specified/returned if the ContextFlags word contains
  792. // the flag CONTEXT_INTEGER.
  793. R0 : LongWord;
  794. R1 : LongWord;
  795. R2 : LongWord;
  796. R3 : LongWord;
  797. R4 : LongWord;
  798. R5 : LongWord;
  799. R6 : LongWord;
  800. R7 : LongWord;
  801. R8 : LongWord;
  802. R9 : LongWord;
  803. R10 : LongWord;
  804. R11 : LongWord;
  805. R12 : LongWord;
  806. // This section is specified/returned if the ContextFlags word contains
  807. // the flag CONTEXT_CONTROL.
  808. Sp : LongWord;
  809. Lr : LongWord;
  810. Pc : LongWord;
  811. Psr : LongWord;
  812. Fpscr : LongWord;
  813. FpExc : LongWord;
  814. // Floating point registers
  815. S : array[0..(NUM_VFP_REGS + 1)-1] of LongWord;
  816. FpExtra : array[0..(NUM_EXTRA_CONTROL_REGS)-1] of LongWord;
  817. end;
  818. {$endif CPUARM}
  819. {$ifdef CPUI386}
  820. const
  821. CONTEXT_X86 = $00010000;
  822. CONTEXT_CONTROL = CONTEXT_X86 or $00000001;
  823. CONTEXT_INTEGER = CONTEXT_X86 or $00000002;
  824. CONTEXT_SEGMENTS = CONTEXT_X86 or $00000004;
  825. CONTEXT_FLOATING_POINT = CONTEXT_X86 or $00000008;
  826. CONTEXT_DEBUG_REGISTERS = CONTEXT_X86 or $00000010;
  827. CONTEXT_EXTENDED_REGISTERS = CONTEXT_X86 or $00000020;
  828. MAXIMUM_SUPPORTED_EXTENSION = 512;
  829. type
  830. PFloatingSaveArea = ^TFloatingSaveArea;
  831. TFloatingSaveArea = packed record
  832. ControlWord : Cardinal;
  833. StatusWord : Cardinal;
  834. TagWord : Cardinal;
  835. ErrorOffset : Cardinal;
  836. ErrorSelector : Cardinal;
  837. DataOffset : Cardinal;
  838. DataSelector : Cardinal;
  839. RegisterArea : array[0..79] of Byte;
  840. Cr0NpxState : Cardinal;
  841. end;
  842. PContext = ^TContext;
  843. TContext = packed record
  844. //
  845. // The flags values within this flag control the contents of
  846. // a CONTEXT record.
  847. //
  848. ContextFlags : Cardinal;
  849. //
  850. // This section is specified/returned if CONTEXT_DEBUG_REGISTERS is
  851. // set in ContextFlags. Note that CONTEXT_DEBUG_REGISTERS is NOT
  852. // included in CONTEXT_FULL.
  853. //
  854. Dr0, Dr1, Dr2,
  855. Dr3, Dr6, Dr7 : Cardinal;
  856. //
  857. // This section is specified/returned if the
  858. // ContextFlags word contains the flag CONTEXT_FLOATING_POINT.
  859. //
  860. FloatSave : TFloatingSaveArea;
  861. //
  862. // This section is specified/returned if the
  863. // ContextFlags word contains the flag CONTEXT_SEGMENTS.
  864. //
  865. SegGs, SegFs,
  866. SegEs, SegDs : Cardinal;
  867. //
  868. // This section is specified/returned if the
  869. // ContextFlags word contains the flag CONTEXT_INTEGER.
  870. //
  871. Edi, Esi, Ebx,
  872. Edx, Ecx, Eax : Cardinal;
  873. //
  874. // This section is specified/returned if the
  875. // ContextFlags word contains the flag CONTEXT_CONTROL.
  876. //
  877. Ebp : Cardinal;
  878. Eip : Cardinal;
  879. SegCs : Cardinal;
  880. EFlags, Esp, SegSs : Cardinal;
  881. //
  882. // This section is specified/returned if the ContextFlags word
  883. // contains the flag CONTEXT_EXTENDED_REGISTERS.
  884. // The format and contexts are processor specific
  885. //
  886. ExtendedRegisters : array[0..MAXIMUM_SUPPORTED_EXTENSION-1] of Byte;
  887. end;
  888. {$endif CPUI386}
  889. type
  890. PExceptionPointers = ^TExceptionPointers;
  891. TExceptionPointers = packed record
  892. ExceptionRecord : PExceptionRecord;
  893. ContextRecord : PContext;
  894. end;
  895. {$ifdef CPUI386}
  896. {**************************** i386 Exception handling *****************************************}
  897. function GetCurrentProcess:DWORD;
  898. begin
  899. GetCurrentProcess := SH_CURPROC+SYS_HANDLE_BASE;
  900. end;
  901. function ReadProcessMemory(process : dword;address : pointer;dest : pointer;size : dword;bytesread : pdword) : longbool;
  902. cdecl; external 'coredll' name 'ReadProcessMemory';
  903. function is_prefetch(p : pointer) : boolean;
  904. var
  905. a : array[0..15] of byte;
  906. doagain : boolean;
  907. instrlo,instrhi,opcode : byte;
  908. i : longint;
  909. begin
  910. result:=false;
  911. { read memory savely without causing another exeception }
  912. if not(ReadProcessMemory(GetCurrentProcess,p,@a,sizeof(a),nil)) then
  913. exit;
  914. i:=0;
  915. doagain:=true;
  916. while doagain and (i<15) do
  917. begin
  918. opcode:=a[i];
  919. instrlo:=opcode and $f;
  920. instrhi:=opcode and $f0;
  921. case instrhi of
  922. { prefix? }
  923. $20,$30:
  924. doagain:=(instrlo and 7)=6;
  925. $60:
  926. doagain:=(instrlo and $c)=4;
  927. $f0:
  928. doagain:=instrlo in [0,2,3];
  929. $0:
  930. begin
  931. result:=(instrlo=$f) and (a[i+1] in [$d,$18]);
  932. exit;
  933. end;
  934. else
  935. doagain:=false;
  936. end;
  937. inc(i);
  938. end;
  939. end;
  940. var
  941. exceptEip : array[0..MaxExceptionLevel-1] of Longint;
  942. exceptError : array[0..MaxExceptionLevel-1] of Byte;
  943. resetFPU : array[0..MaxExceptionLevel-1] of Boolean;
  944. {$ifdef SYSTEMEXCEPTIONDEBUG}
  945. procedure DebugHandleErrorAddrFrame(error, addr, frame : longint);
  946. begin
  947. if IsConsole then
  948. begin
  949. write(stderr,'HandleErrorAddrFrame(error=',error);
  950. write(stderr,',addr=',hexstr(addr,8));
  951. writeln(stderr,',frame=',hexstr(frame,8),')');
  952. end;
  953. HandleErrorAddrFrame(error,addr,frame);
  954. end;
  955. {$endif SYSTEMEXCEPTIONDEBUG}
  956. procedure JumpToHandleErrorFrame;
  957. var
  958. eip, ebp, error : Longint;
  959. begin
  960. // save ebp
  961. asm
  962. movl (%ebp),%eax
  963. movl %eax,ebp
  964. end;
  965. if (exceptLevel > 0) then
  966. dec(exceptLevel);
  967. eip:=exceptEip[exceptLevel];
  968. error:=exceptError[exceptLevel];
  969. {$ifdef SYSTEMEXCEPTIONDEBUG}
  970. if IsConsole then
  971. writeln(stderr,'In JumpToHandleErrorFrame error=',error);
  972. {$endif SYSTEMEXCEPTIONDEBUG}
  973. if resetFPU[exceptLevel] then
  974. SysResetFPU;
  975. { build a fake stack }
  976. asm
  977. {$ifdef REGCALL}
  978. movl ebp,%ecx
  979. movl eip,%edx
  980. movl error,%eax
  981. pushl eip
  982. movl ebp,%ebp // Change frame pointer
  983. {$else}
  984. movl ebp,%eax
  985. pushl %eax
  986. movl eip,%eax
  987. pushl %eax
  988. movl error,%eax
  989. pushl %eax
  990. movl eip,%eax
  991. pushl %eax
  992. movl ebp,%ebp // Change frame pointer
  993. {$endif}
  994. {$ifdef SYSTEMEXCEPTIONDEBUG}
  995. jmpl DebugHandleErrorAddrFrame
  996. {$else not SYSTEMEXCEPTIONDEBUG}
  997. jmpl HandleErrorAddrFrame
  998. {$endif SYSTEMEXCEPTIONDEBUG}
  999. end;
  1000. end;
  1001. function i386_exception_handler(ExceptionRecord: PExceptionRecord;
  1002. EstablisherFrame: pointer; ContextRecord: PContext;
  1003. DispatcherContext: pointer): longint; cdecl;
  1004. var
  1005. res: longint;
  1006. must_reset_fpu: boolean;
  1007. begin
  1008. res := ExceptionContinueSearch;
  1009. if ContextRecord^.SegSs=_SS then begin
  1010. must_reset_fpu := true;
  1011. {$ifdef SYSTEMEXCEPTIONDEBUG}
  1012. if IsConsole then Writeln(stderr,'Exception ',
  1013. hexstr(excep^.ExceptionRecord^.ExceptionCode, 8));
  1014. {$endif SYSTEMEXCEPTIONDEBUG}
  1015. case cardinal(ExceptionRecord^.ExceptionCode) of
  1016. STATUS_INTEGER_DIVIDE_BY_ZERO,
  1017. STATUS_FLOAT_DIVIDE_BY_ZERO :
  1018. res := 200;
  1019. STATUS_ARRAY_BOUNDS_EXCEEDED :
  1020. begin
  1021. res := 201;
  1022. must_reset_fpu := false;
  1023. end;
  1024. STATUS_STACK_OVERFLOW :
  1025. begin
  1026. res := 202;
  1027. must_reset_fpu := false;
  1028. end;
  1029. STATUS_FLOAT_OVERFLOW :
  1030. res := 205;
  1031. STATUS_FLOAT_DENORMAL_OPERAND,
  1032. STATUS_FLOAT_UNDERFLOW :
  1033. res := 206;
  1034. {excep^.ContextRecord^.FloatSave.StatusWord := excep^.ContextRecord^.FloatSave.StatusWord and $ffffff00;}
  1035. STATUS_FLOAT_INEXACT_RESULT,
  1036. STATUS_FLOAT_INVALID_OPERATION,
  1037. STATUS_FLOAT_STACK_CHECK :
  1038. res := 207;
  1039. STATUS_INTEGER_OVERFLOW :
  1040. begin
  1041. res := 215;
  1042. must_reset_fpu := false;
  1043. end;
  1044. STATUS_ILLEGAL_INSTRUCTION:
  1045. res := 216;
  1046. STATUS_ACCESS_VIOLATION:
  1047. { Athlon prefetch bug? }
  1048. if is_prefetch(pointer(ContextRecord^.Eip)) then
  1049. begin
  1050. { if yes, then retry }
  1051. ExceptionRecord^.ExceptionCode := 0;
  1052. res:=ExceptionContinueExecution;
  1053. end
  1054. else
  1055. res := 216;
  1056. STATUS_CONTROL_C_EXIT:
  1057. res := 217;
  1058. STATUS_PRIVILEGED_INSTRUCTION:
  1059. begin
  1060. res := 218;
  1061. must_reset_fpu := false;
  1062. end;
  1063. else
  1064. begin
  1065. if ((ExceptionRecord^.ExceptionCode and SEVERITY_ERROR) = SEVERITY_ERROR) then
  1066. res := 217
  1067. else
  1068. res := 255;
  1069. end;
  1070. end;
  1071. if (res >= 200) and (exceptLevel < MaxExceptionLevel) then begin
  1072. exceptEip[exceptLevel] := ContextRecord^.Eip;
  1073. exceptError[exceptLevel] := res;
  1074. resetFPU[exceptLevel] := must_reset_fpu;
  1075. inc(exceptLevel);
  1076. ContextRecord^.Eip := Longint(@JumpToHandleErrorFrame);
  1077. ExceptionRecord^.ExceptionCode := 0;
  1078. res := ExceptionContinueExecution;
  1079. {$ifdef SYSTEMEXCEPTIONDEBUG}
  1080. if IsConsole then begin
  1081. writeln(stderr,'Exception Continue Exception set at ',
  1082. hexstr(exceptEip[exceptLevel],8));
  1083. writeln(stderr,'Eip changed to ',
  1084. hexstr(longint(@JumpToHandleErrorFrame),8), ' error=', error);
  1085. end;
  1086. {$endif SYSTEMEXCEPTIONDEBUG}
  1087. end;
  1088. end;
  1089. i386_exception_handler := res;
  1090. end;
  1091. {$endif CPUI386}
  1092. {$ifdef CPUARM}
  1093. {**************************** ARM Exception handling *****************************************}
  1094. var
  1095. exceptPC : array[0..MaxExceptionLevel-1] of Longint;
  1096. exceptError : array[0..MaxExceptionLevel-1] of Byte;
  1097. procedure JumpToHandleErrorFrame;
  1098. var
  1099. _pc, _fp, _error : Longint;
  1100. begin
  1101. // get original fp
  1102. asm
  1103. ldr r0,[r11,#-12]
  1104. str r0,_fp
  1105. end;
  1106. if (exceptLevel > 0) then
  1107. dec(exceptLevel);
  1108. _pc:=exceptPC[exceptLevel];
  1109. _error:=exceptError[exceptLevel];
  1110. asm
  1111. ldr r0,_error
  1112. ldr r1,_pc
  1113. ldr r2,_fp
  1114. mov r11,r2 // Change frame pointer
  1115. b HandleErrorAddrFrame
  1116. end;
  1117. end;
  1118. function ARM_ExceptionHandler(ExceptionRecord: PExceptionRecord;
  1119. EstablisherFrame: pointer; ContextRecord: PContext;
  1120. DispatcherContext: pointer): longint; [public, alias : '_ARM_ExceptionHandler'];
  1121. var
  1122. res: longint;
  1123. begin
  1124. res := ExceptionContinueSearch;
  1125. case cardinal(ExceptionRecord^.ExceptionCode) of
  1126. STATUS_INTEGER_DIVIDE_BY_ZERO,
  1127. STATUS_FLOAT_DIVIDE_BY_ZERO :
  1128. res := 200;
  1129. STATUS_ARRAY_BOUNDS_EXCEEDED :
  1130. res := 201;
  1131. STATUS_STACK_OVERFLOW :
  1132. res := 202;
  1133. STATUS_FLOAT_OVERFLOW :
  1134. res := 205;
  1135. STATUS_FLOAT_DENORMAL_OPERAND,
  1136. STATUS_FLOAT_UNDERFLOW :
  1137. res := 206;
  1138. STATUS_FLOAT_INEXACT_RESULT,
  1139. STATUS_FLOAT_INVALID_OPERATION,
  1140. STATUS_FLOAT_STACK_CHECK :
  1141. res := 207;
  1142. STATUS_INTEGER_OVERFLOW :
  1143. res := 215;
  1144. STATUS_ILLEGAL_INSTRUCTION:
  1145. res := 216;
  1146. STATUS_ACCESS_VIOLATION:
  1147. res := 216;
  1148. STATUS_DATATYPE_MISALIGNMENT:
  1149. res := 214;
  1150. STATUS_CONTROL_C_EXIT:
  1151. res := 217;
  1152. STATUS_PRIVILEGED_INSTRUCTION:
  1153. res := 218;
  1154. else
  1155. begin
  1156. if ((cardinal(ExceptionRecord^.ExceptionCode) and SEVERITY_ERROR) = SEVERITY_ERROR) then
  1157. res := 217
  1158. else
  1159. res := 255;
  1160. end;
  1161. end;
  1162. if (res <> ExceptionContinueSearch) and (exceptLevel < MaxExceptionLevel) then begin
  1163. exceptPC[exceptLevel] := ContextRecord^.PC;
  1164. exceptError[exceptLevel] := res;
  1165. inc(exceptLevel);
  1166. ContextRecord^.PC := Longint(@JumpToHandleErrorFrame);
  1167. ExceptionRecord^.ExceptionCode := 0;
  1168. res := ExceptionContinueExecution;
  1169. {$ifdef SYSTEMEXCEPTIONDEBUG}
  1170. if IsConsole then begin
  1171. writeln(stderr,'Exception Continue Exception set at ',
  1172. hexstr(exceptEip[exceptLevel],8));
  1173. writeln(stderr,'Eip changed to ',
  1174. hexstr(longint(@JumpToHandleErrorFrame),8), ' error=', error);
  1175. end;
  1176. {$endif SYSTEMEXCEPTIONDEBUG}
  1177. end;
  1178. ARM_ExceptionHandler := res;
  1179. end;
  1180. {$endif CPUARM}
  1181. {$endif WINCE_EXCEPTION_HANDLING}
  1182. procedure Exe_entry;[public, alias : '_FPC_EXE_Entry'];
  1183. begin
  1184. IsLibrary:=false;
  1185. {$ifdef CPUARM}
  1186. asm
  1187. mov fp,#0
  1188. bl PASCALMAIN;
  1189. end;
  1190. {$endif CPUARM}
  1191. {$ifdef CPUI386}
  1192. asm
  1193. {$ifdef WINCE_EXCEPTION_HANDLING}
  1194. pushl i386_exception_handler
  1195. pushl %fs:(0)
  1196. mov %esp,%fs:(0)
  1197. {$endif WINCE_EXCEPTION_HANDLING}
  1198. pushl %ebp
  1199. xorl %eax,%eax
  1200. movw %ss,%ax
  1201. movl %eax,_SS
  1202. xorl %ebp,%ebp
  1203. call PASCALMAIN
  1204. popl %ebp
  1205. {$ifdef WINCE_EXCEPTION_HANDLING}
  1206. popl %fs:(0)
  1207. addl $4, %esp
  1208. {$endif WINCE_EXCEPTION_HANDLING}
  1209. end;
  1210. {$endif CPUI386}
  1211. end;
  1212. procedure _FPC_mainCRTStartup;public name '_mainCRTStartup';
  1213. begin
  1214. IsConsole:=True;
  1215. Exe_entry;
  1216. end;
  1217. procedure _FPC_WinMainCRTStartup;public name '_WinMainCRTStartup';
  1218. begin
  1219. IsConsole:=False;
  1220. Exe_entry;
  1221. end;
  1222. procedure _FPC_DLLMainCRTStartup(_hinstance,_dllreason,_dllparam:longint);public name '_DLLMainCRTStartup';
  1223. begin
  1224. IsConsole:=true;
  1225. sysinstance:=_hinstance;
  1226. dllreason:=_dllreason;
  1227. dllparam:=_dllparam;
  1228. DLL_Entry;
  1229. end;
  1230. procedure _FPC_DLLWinMainCRTStartup(_hinstance,_dllreason,_dllparam:longint);public name '_DLLWinMainCRTStartup';
  1231. begin
  1232. IsConsole:=false;
  1233. sysinstance:=_hinstance;
  1234. dllreason:=_dllreason;
  1235. dllparam:=_dllparam;
  1236. DLL_Entry;
  1237. end;
  1238. {****************************************************************************
  1239. OS dependend widestrings
  1240. ****************************************************************************}
  1241. function CharUpperBuff(lpsz:LPWSTR; cchLength:DWORD):DWORD; cdecl; external KernelDLL name 'CharUpperBuffW';
  1242. function CharLowerBuff(lpsz:LPWSTR; cchLength:DWORD):DWORD; cdecl; external KernelDLL name 'CharLowerBuffW';
  1243. procedure WinCEWide2AnsiMove(source:pwidechar;var dest:RawByteString;cp:TSystemCodePage;len:SizeInt);
  1244. var
  1245. destlen: SizeInt;
  1246. begin
  1247. // retrieve length including trailing #0
  1248. // not anymore, because this must also be usable for single characters
  1249. destlen:=WideCharToMultiByte(cp, 0, source, len, nil, 0, nil, nil);
  1250. // this will null-terminate
  1251. setlength(dest, destlen);
  1252. if destlen>0 then
  1253. begin
  1254. WideCharToMultiByte(cp, 0, source, len, @dest[1], destlen, nil, nil);
  1255. PAnsiRec(pointer(dest)-AnsiFirstOff)^.CodePage:=cp;
  1256. end;
  1257. end;
  1258. procedure WinCEAnsi2WideMove(source:pchar;cp:TSystemCodePage;var dest:widestring;len:SizeInt);
  1259. var
  1260. destlen: SizeInt;
  1261. dwFlags: DWORD;
  1262. begin
  1263. if cp=CP_UTF8 then
  1264. dwFlags:=0
  1265. else
  1266. dwFlags:=MB_PRECOMPOSED;
  1267. destlen:=MultiByteToWideChar(cp, dwFlags, source, len, nil, 0);
  1268. // this will null-terminate
  1269. setlength(dest, destlen);
  1270. if destlen>0 then
  1271. MultiByteToWideChar(cp, dwFlags, source, len, @dest[1], destlen);
  1272. end;
  1273. function WinCEWideUpper(const s : WideString) : WideString;
  1274. begin
  1275. result:=s;
  1276. UniqueString(result);
  1277. if length(result)>0 then
  1278. CharUpperBuff(LPWSTR(result),length(result));
  1279. end;
  1280. function WinCEWideLower(const s : WideString) : WideString;
  1281. begin
  1282. result:=s;
  1283. UniqueString(result);
  1284. if length(result)>0 then
  1285. CharLowerBuff(LPWSTR(result),length(result));
  1286. end;
  1287. procedure WinCEUnicode2AnsiMove(source:punicodechar;var dest:RawByteString;cp:TSystemCodePage;len:SizeInt);
  1288. var
  1289. destlen: SizeInt;
  1290. begin
  1291. // retrieve length including trailing #0
  1292. // not anymore, because this must also be usable for single characters
  1293. destlen:=WideCharToMultiByte(cp, 0, source, len, nil, 0, nil, nil);
  1294. // this will null-terminate
  1295. setlength(dest, destlen);
  1296. if destlen>0 then
  1297. begin
  1298. WideCharToMultiByte(cp, 0, source, len, @dest[1], destlen, nil, nil);
  1299. PAnsiRec(pointer(dest)-AnsiFirstOff)^.CodePage:=cp;
  1300. end;
  1301. end;
  1302. procedure WinCEAnsi2UnicodeMove(source:pchar;cp : TSystemCodePage;var dest:UnicodeString;len:SizeInt);
  1303. var
  1304. destlen: SizeInt;
  1305. dwflags: DWORD;
  1306. begin
  1307. if cp=CP_UTF8 then
  1308. dwFlags:=0
  1309. else
  1310. dwFlags:=MB_PRECOMPOSED;
  1311. destlen:=MultiByteToWideChar(cp, dwFlags, source, len, nil, 0);
  1312. // this will null-terminate
  1313. setlength(dest, destlen);
  1314. if destlen>0 then
  1315. begin
  1316. MultiByteToWideChar(cp, dwFlags, source, len, @dest[1], destlen);
  1317. PUnicodeRec(pointer(dest)-UnicodeFirstOff)^.CodePage:=CP_UTF16;
  1318. end;
  1319. end;
  1320. function WinCEUnicodeUpper(const s : UnicodeString) : UnicodeString;
  1321. begin
  1322. Result:=WinCEWideUpper(s);
  1323. end;
  1324. function WinCEUnicodeLower(const s : UnicodeString) : UnicodeString;
  1325. begin
  1326. Result:=WinCEWideLower(s);
  1327. end;
  1328. function WinCEGetStandardCodePage(const stdcp: TStandardCodePageEnum): TSystemCodePage;
  1329. begin
  1330. case stdcp of
  1331. scpAnsi: Result := GetACP;
  1332. scpConsoleInput: Result := GetACP;
  1333. scpConsoleOutput: Result := GetACP;
  1334. { all of WinCE's file APIs are based on UTF8 -> prevent data loss when using
  1335. single byte strings }
  1336. scpFileSystemSingleByte: Result := CP_UTF8;
  1337. end;
  1338. end;
  1339. { there is a similiar procedure in sysutils which inits the fields which
  1340. are only relevant for the sysutils units }
  1341. procedure InitWinCEWidestrings;
  1342. begin
  1343. widestringmanager.Wide2AnsiMoveProc:=@WinCEWide2AnsiMove;
  1344. widestringmanager.Ansi2WideMoveProc:=@WinCEAnsi2WideMove;
  1345. widestringmanager.UpperWideStringProc:=@WinCEWideUpper;
  1346. widestringmanager.LowerWideStringProc:=@WinCEWideLower;
  1347. { Unicode }
  1348. widestringmanager.Unicode2AnsiMoveProc:=@WinCEUnicode2AnsiMove;
  1349. widestringmanager.Ansi2UnicodeMoveProc:=@WinCEAnsi2UnicodeMove;
  1350. widestringmanager.UpperUnicodeStringProc:=@WinCEUnicodeUpper;
  1351. widestringmanager.LowerUnicodeStringProc:=@WinCEUnicodeLower;
  1352. { Codepage }
  1353. widestringmanager.GetStandardCodePageProc:=@WinCEGetStandardCodePage;
  1354. DefaultSystemCodePage:=GetACP;
  1355. DefaultFileSystemCodePage:=WinCEGetStandardCodePage(scpFileSystemSingleByte);
  1356. DefaultRTLFileSystemCodePage:=DefaultFileSystemCodePage;
  1357. DefaultUnicodeCodePage:=CP_UTF16;
  1358. end;
  1359. {$IFDEF HAS_MEMORYMANAGER}
  1360. {****************************************************************************
  1361. Memory manager
  1362. ****************************************************************************}
  1363. function malloc(Size : ptruint) : Pointer; cdecl; external 'coredll';
  1364. procedure free(P : pointer); cdecl; external 'coredll';
  1365. function realloc(P : Pointer; Size : ptruint) : pointer; cdecl; external 'coredll';
  1366. function _msize(P : pointer): ptruint; cdecl; external 'coredll';
  1367. function SysGetMem (Size : ptruint) : Pointer;
  1368. begin
  1369. Result:=malloc(Size);
  1370. end;
  1371. Function SysFreeMem (P : pointer) : ptruint;
  1372. begin
  1373. free(P);
  1374. Result:=0;
  1375. end;
  1376. Function SysFreeMemSize(p:pointer;Size:ptruint):ptruint;
  1377. begin
  1378. Result:=0;
  1379. if (size > 0) and (p <> nil) then
  1380. Result:=SysFreeMem(P);
  1381. end;
  1382. Function SysAllocMem(Size : ptruint) : Pointer;
  1383. begin
  1384. Result:=SysGetMem(Size);
  1385. if Result <> nil then
  1386. FillChar(Result^, Size, 0);
  1387. end;
  1388. Function SysReAllocMem (var p:pointer;Size:ptruint):Pointer;
  1389. begin
  1390. Result:=realloc(p, Size);
  1391. p:=Result;
  1392. end;
  1393. function SysTryResizeMem(var p:pointer;size : ptruint):boolean;
  1394. var
  1395. res: pointer;
  1396. begin
  1397. res:=realloc(p, Size);
  1398. Result:=(res <> nil) or (Size = 0);
  1399. if Result then
  1400. p:=res;
  1401. end;
  1402. function SysMemSize(P : pointer): ptruint;
  1403. begin
  1404. Result:=_msize(P);
  1405. end;
  1406. function SysGetHeapStatus:THeapStatus;
  1407. begin
  1408. fillchar(Result,sizeof(Result),0);
  1409. end;
  1410. function SysGetFPCHeapStatus:TFPCHeapStatus;
  1411. begin
  1412. fillchar(Result,sizeof(Result),0);
  1413. end;
  1414. {$ENDIF HAS_MEMORYMANAGER}
  1415. {****************************************************************************
  1416. Error Message writing using messageboxes
  1417. ****************************************************************************}
  1418. const
  1419. ErrorBufferLength = 1024;
  1420. var
  1421. ErrorBuf : array[0..ErrorBufferLength] of char;
  1422. ErrorBufW : array[0..ErrorBufferLength] of widechar;
  1423. ErrorLen : longint;
  1424. procedure ErrorWrite(Var F: TextRec);
  1425. {
  1426. An error message should always end with #13#10#13#10
  1427. }
  1428. var
  1429. i : longint;
  1430. Begin
  1431. while F.BufPos>0 do
  1432. begin
  1433. begin
  1434. if F.BufPos+ErrorLen>ErrorBufferLength then
  1435. i:=ErrorBufferLength-ErrorLen
  1436. else
  1437. i:=F.BufPos;
  1438. Move(F.BufPtr^,ErrorBuf[ErrorLen],i);
  1439. inc(ErrorLen,i);
  1440. ErrorBuf[ErrorLen]:=#0;
  1441. end;
  1442. if ErrorLen=ErrorBufferLength then
  1443. begin
  1444. AnsiToWideBuf(@ErrorBuf, -1, @ErrorBufW, SizeOf(ErrorBufW));
  1445. MessageBox(0,@ErrorBufW,'Error',$10010); { MB_SETFOREGROUND or ICON_ERROR }
  1446. ErrorLen:=0;
  1447. end;
  1448. Dec(F.BufPos,i);
  1449. end;
  1450. End;
  1451. procedure ErrorClose(Var F: TextRec);
  1452. begin
  1453. if ErrorLen>0 then
  1454. begin
  1455. AnsiToWideBuf(@ErrorBuf, -1, @ErrorBufW, SizeOf(ErrorBufW));
  1456. MessageBox(0,@ErrorBufW,'Error',$10010); { MB_SETFOREGROUND or ICON_ERROR }
  1457. ErrorLen:=0;
  1458. end;
  1459. ErrorLen:=0;
  1460. end;
  1461. procedure ErrorOpen(Var F: TextRec);
  1462. Begin
  1463. TextRec(F).InOutFunc:=@ErrorWrite;
  1464. TextRec(F).FlushFunc:=@ErrorWrite;
  1465. TextRec(F).CloseFunc:=@ErrorClose;
  1466. ErrorLen:=0;
  1467. End;
  1468. procedure AssignError(Var T: Text);
  1469. begin
  1470. Assign(T,'');
  1471. TextRec(T).OpenFunc:=@ErrorOpen;
  1472. Rewrite(T);
  1473. end;
  1474. function _getstdfilex(fd: integer): pointer; cdecl; external 'coredll';
  1475. function _fileno(fd: pointer): THandle; cdecl; external 'coredll';
  1476. procedure SysInitStdIO;
  1477. begin
  1478. { Setup stdin, stdout and stderr, for GUI apps redirect stderr,stdout to be
  1479. displayed in and messagebox }
  1480. if not IsConsole then
  1481. begin
  1482. AssignError(stderr);
  1483. AssignError(stdout);
  1484. Assign(Output,'');
  1485. Assign(Input,'');
  1486. Assign(ErrOutput,'');
  1487. end
  1488. else
  1489. begin
  1490. StdInputHandle:=_fileno(_getstdfilex(0));
  1491. StdOutputHandle:=_fileno(_getstdfilex(1));
  1492. StdErrorHandle:=_fileno(_getstdfilex(2));
  1493. OpenStdIO(Input,fmInput,StdInputHandle);
  1494. OpenStdIO(Output,fmOutput,StdOutputHandle);
  1495. OpenStdIO(ErrOutput,fmOutput,StdErrorHandle);
  1496. OpenStdIO(StdOut,fmOutput,StdOutputHandle);
  1497. OpenStdIO(StdErr,fmOutput,StdErrorHandle);
  1498. end;
  1499. end;
  1500. (* ProcessID cached to avoid repeated calls to GetCurrentProcess. *)
  1501. var
  1502. ProcessID: SizeUInt;
  1503. function GetProcessID: SizeUInt;
  1504. begin
  1505. GetProcessID := ProcessID;
  1506. end;
  1507. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt;
  1508. begin
  1509. result := stklen;
  1510. end;
  1511. procedure SysCleanup;
  1512. var
  1513. i: integer;
  1514. begin
  1515. if FCmdLine = nil then
  1516. exit;
  1517. SysFreeMem(FCmdLine);
  1518. for i:=0 to Fargc do
  1519. sysfreemem(Fargv[i]);
  1520. sysfreemem(Fargv);
  1521. end;
  1522. initialization
  1523. SysResetFPU;
  1524. if not(IsLibrary) then
  1525. SysInitFPU;
  1526. StackLength := CheckInitialStkLen(InitialStkLen);
  1527. StackBottom := Sptr - StackLength;
  1528. { some misc stuff }
  1529. hprevinst:=0;
  1530. if not IsLibrary then
  1531. SysInstance:=GetModuleHandle(nil);
  1532. MainInstance:=SysInstance;
  1533. {$IFNDEF HAS_MEMORYMANAGER}
  1534. { Setup Heap }
  1535. InitHeap;
  1536. {$ENDIF HAS_MEMORYMANAGER}
  1537. SysInitExceptions;
  1538. initunicodestringmanager;
  1539. InitWinCEWidestrings;
  1540. if not IsLibrary then
  1541. begin
  1542. SysInitStdIO;
  1543. end;
  1544. { Reset IO Error }
  1545. InOutRes:=0;
  1546. ProcessID := GetCurrentProcessID;
  1547. { threading }
  1548. InitSystemThreads;
  1549. InitSystemDynLibs;
  1550. DispCallByIDProc:=@DoDispCallByIDError;
  1551. finalization
  1552. SysCleanup;
  1553. end.