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. function addd(d1,d2 : double) : double; compilerproc;
  87. cdecl;external 'coredll' name '__addd';
  88. function subd(d1,d2 : double) : double; compilerproc;
  89. cdecl;external 'coredll' name '__subd';
  90. function muld(d1,d2 : double) : double; compilerproc;
  91. cdecl;external 'coredll' name '__muld';
  92. function divd(d1,d2 : double) : double; compilerproc;
  93. cdecl;external 'coredll' name '__divd';
  94. function eqd(d1,d2 : double) : boolean; compilerproc;
  95. cdecl;external 'coredll' name '__eqd';
  96. function ned(d1,d2 : double) : boolean; compilerproc;
  97. cdecl;external 'coredll' name '__ned';
  98. function ltd(d1,d2 : double) : boolean; compilerproc;
  99. cdecl;external 'coredll' name '__ltd';
  100. function gtd(d1,d2 : double) : boolean; compilerproc;
  101. cdecl;external 'coredll' name '__gtd';
  102. function ged(d1,d2 : double) : boolean; compilerproc;
  103. cdecl;external 'coredll' name '__ged';
  104. function led(d1,d2 : double) : boolean; compilerproc;
  105. cdecl;external 'coredll' name '__led';
  106. { ***************** single ******************** }
  107. function eqs(d1,d2 : single) : boolean; compilerproc;
  108. cdecl;external 'coredll' name '__eqs';
  109. function nes(d1,d2 : single) : boolean; compilerproc;
  110. cdecl;external 'coredll' name '__nes';
  111. function lts(d1,d2 : single) : boolean; compilerproc;
  112. cdecl;external 'coredll' name '__lts';
  113. function gts(d1,d2 : single) : boolean; compilerproc;
  114. cdecl;external 'coredll' name '__gts';
  115. function ges(d1,d2 : single) : boolean; compilerproc;
  116. cdecl;external 'coredll' name '__ges';
  117. function les(d1,d2 : single) : boolean; compilerproc;
  118. cdecl;external 'coredll' name '__les';
  119. function dtos(d : double) : single; compilerproc;
  120. cdecl;external 'coredll' name '__dtos';
  121. function stod(d : single) : double; compilerproc;
  122. cdecl;external 'coredll' name '__stod';
  123. function negs(d : single) : single; compilerproc;
  124. cdecl;external 'coredll' name '__negs';
  125. function negd(d : double) : double; compilerproc;
  126. cdecl;external 'coredll' name '__negd';
  127. function utod(i : dword) : double; compilerproc;
  128. cdecl;external 'coredll' name '__utod';
  129. function itod(i : longint) : double; compilerproc;
  130. cdecl;external 'coredll' name '__itod';
  131. function ui64tod(i : qword) : double; compilerproc;
  132. cdecl;external 'coredll' name '__u64tod';
  133. function i64tod(i : int64) : double; compilerproc;
  134. cdecl;external 'coredll' name '__i64tod';
  135. function utos(i : dword) : single; compilerproc;
  136. cdecl;external 'coredll' name '__utos';
  137. function itos(i : longint) : single; compilerproc;
  138. cdecl;external 'coredll' name '__itos';
  139. function ui64tos(i : qword) : single; compilerproc;
  140. cdecl;external 'coredll' name '__u64tos';
  141. function i64tos(i : int64) : single; compilerproc;
  142. cdecl;external 'coredll' name '__i64tos';
  143. function adds(s1,s2 : single) : single; compilerproc;
  144. function subs(s1,s2 : single) : single; compilerproc;
  145. function muls(s1,s2 : single) : single; compilerproc;
  146. function divs(s1,s2 : single) : single; compilerproc;
  147. {$endif CPUARM}
  148. function CmdLine: PChar;
  149. { C compatible arguments }
  150. function argc: longint;
  151. function argv: ppchar;
  152. implementation
  153. var
  154. SysInstance : Longint;public name '_FPC_SysInstance';
  155. function MessageBox(w1:longint;l1,l2:PWideChar;w2:longint):longint;
  156. cdecl; external 'coredll' name 'MessageBoxW';
  157. function CreateDirectoryW(name : pwidechar;sec : pointer) : longbool;
  158. cdecl; external KernelDLL name 'CreateDirectoryW';
  159. function RemoveDirectoryW(name:pwidechar):longbool;
  160. cdecl; external KernelDLL name 'RemoveDirectoryW';
  161. {*****************************************************************************}
  162. {$define FPC_SYSTEM_HAS_MOVE}
  163. procedure memmove(dest, src: pointer; count: longint);
  164. cdecl; external 'coredll' name 'memmove';
  165. procedure Move(const source;var dest;count:SizeInt);[public, alias: 'FPC_MOVE'];
  166. begin
  167. if count > 0 then
  168. memmove(@dest, @source, count);
  169. end;
  170. {$define FPC_SYSTEM_HAS_COMPAREBYTE}
  171. function memcmp(buf1, buf2: pointer; count: longint): longint;
  172. cdecl; external 'coredll' name 'memcmp';
  173. function CompareByte(Const buf1,buf2;len:SizeInt):SizeInt;
  174. begin
  175. CompareByte := memcmp(@buf1, @buf2, len);
  176. end;
  177. {$ifdef CPUARM}
  178. {$define FPC_SYSTEM_HAS_INT}
  179. function floor(d : double) : double;
  180. cdecl;external 'coredll' name 'floor';
  181. function ceil(d : double) : double;
  182. cdecl;external 'coredll' name 'ceil';
  183. function fpc_int_real(d: ValReal): ValReal;compilerproc;
  184. begin
  185. if d > 0 then
  186. fpc_int_real:=floor(d)
  187. else
  188. fpc_int_real:=ceil(d);
  189. end;
  190. {$define FPC_SYSTEM_HAS_TRUNC}
  191. function __dtoi64(d: double) : int64; cdecl; external 'coredll';
  192. function fpc_trunc_real(d : ValReal) : int64; assembler; nostackframe; compilerproc;
  193. asm
  194. b __dtoi64
  195. end;
  196. {$define FPC_SYSTEM_HAS_ABS}
  197. function fabs(d: double): double; cdecl; external 'coredll';
  198. function fpc_abs_real(d : ValReal) : ValReal; assembler; nostackframe; compilerproc;
  199. asm
  200. b fabs
  201. end;
  202. {$define FPC_SYSTEM_HAS_SQRT}
  203. function coresqrt(d: double): double; cdecl; external 'coredll' name 'sqrt';
  204. function fpc_sqrt_real(d : ValReal) : ValReal; assembler; nostackframe; compilerproc;
  205. asm
  206. b coresqrt
  207. end;
  208. function adds(s1,s2 : single) : single;
  209. begin
  210. adds := double(s1) + double(s2);
  211. end;
  212. function subs(s1,s2 : single) : single;
  213. begin
  214. subs := double(s1) - double(s2);
  215. end;
  216. function muls(s1,s2 : single) : single;
  217. begin
  218. muls := double(s1) * double(s2);
  219. end;
  220. function divs(s1,s2 : single) : single;
  221. begin
  222. divs := double(s1) / double(s2);
  223. end;
  224. {$endif CPUARM}
  225. {*****************************************************************************}
  226. { include system independent routines }
  227. {$I system.inc}
  228. {*****************************************************************************
  229. ANSI <-> Wide
  230. *****************************************************************************}
  231. const
  232. { MultiByteToWideChar }
  233. MB_PRECOMPOSED = 1;
  234. MB_COMPOSITE = 2;
  235. MB_ERR_INVALID_CHARS = 8;
  236. MB_USEGLYPHCHARS = 4;
  237. function MultiByteToWideChar(CodePage:UINT; dwFlags:DWORD; lpMultiByteStr:PChar; cchMultiByte:longint; lpWideCharStr:PWideChar;cchWideChar:longint):longint;
  238. cdecl; external 'coredll' name 'MultiByteToWideChar';
  239. function WideCharToMultiByte(CodePage:UINT; dwFlags:DWORD; lpWideCharStr:PWideChar; cchWideChar:longint; lpMultiByteStr:PChar;cchMultiByte:longint; lpDefaultChar:PChar; lpUsedDefaultChar:pointer):longint;
  240. cdecl; external 'coredll' name 'WideCharToMultiByte';
  241. function GetACP:UINT; cdecl; external 'coredll' name 'GetACP';
  242. { Returns number of characters stored to WideBuf, including null-terminator. }
  243. function AnsiToWideBuf(AnsiBuf: PChar; AnsiBufLen: longint; WideBuf: PWideChar; WideBufLen: longint): longint;
  244. begin
  245. Result := MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, AnsiBuf, AnsiBufLen, WideBuf, WideBufLen div SizeOf(WideChar));
  246. if ((AnsiBufLen <> -1) or (Result = 0)) and (WideBuf <> nil) then
  247. begin
  248. if (Result + 1)*SizeOf(WideChar) > WideBufLen then
  249. begin
  250. Result := 0;
  251. if WideBufLen < SizeOf(WideChar) then
  252. exit;
  253. end;
  254. WideBuf[Result] := #0;
  255. end;
  256. if (AnsiBufLen <> -1) and ((Result <> 0) or (AnsiBufLen = 0)) then
  257. Inc(Result);
  258. end;
  259. { Returns number of characters stored to AnsiBuf, including null-terminator. }
  260. function WideToAnsiBuf(WideBuf: PWideChar; WideCharsLen: longint; AnsiBuf: PChar; AnsiBufLen: longint): longint;
  261. begin
  262. Result := WideCharToMultiByte(CP_ACP, 0, WideBuf, WideCharsLen, AnsiBuf, AnsiBufLen, nil, nil);
  263. if ((WideCharsLen <> -1) or (Result = 0)) and (AnsiBuf <> nil) then
  264. begin
  265. if Result + 1 > AnsiBufLen then
  266. begin
  267. Result := 0;
  268. if AnsiBufLen < 1 then
  269. exit;
  270. end;
  271. AnsiBuf[Result] := #0;
  272. end;
  273. if (WideCharsLen <> -1) and ((Result <> 0) or (WideCharsLen = 0)) then
  274. Inc(Result);
  275. end;
  276. { Returns dynamic memory block, which contains wide string. This memory should be freed using FreeMem. }
  277. { outlen will contain number of wide characters stored to result buffer, including null-terminator. }
  278. function PCharToPWideChar(str: PChar; strlen: longint = -1; outlen: PLongInt = nil): PWideChar;
  279. var
  280. len: longint;
  281. begin
  282. while True do begin
  283. if strlen <> -1 then
  284. len:=strlen + 1
  285. else
  286. len:=AnsiToWideBuf(str, -1, nil, 0);
  287. if len > 0 then
  288. begin
  289. len:=len*SizeOf(WideChar);
  290. GetMem(Result, len);
  291. len:=AnsiToWideBuf(str, strlen, Result, len);
  292. if (len = 0) and (strlen <> -1) then
  293. begin
  294. FreeMem(Result);
  295. strlen:=-1;
  296. continue;
  297. end;
  298. end
  299. else begin
  300. GetMem(Result, SizeOf(WideChar));
  301. len:=1;
  302. Result^:=#0;
  303. end;
  304. break;
  305. end;
  306. if outlen <> nil then
  307. outlen^:=len;
  308. end;
  309. { Returns dynamic memory block, which contains wide string. This memory should be freed using FreeMem. }
  310. { outlen will contain number of wide characters stored to result buffer, including null-terminator. }
  311. function StringToPWideChar(const s: AnsiString; outlen: PLongInt = nil): PWideChar;
  312. var
  313. len, wlen: longint;
  314. begin
  315. len:=Length(s);
  316. wlen:=(len + 1)*SizeOf(WideChar);
  317. GetMem(Result, wlen);
  318. wlen:=AnsiToWideBuf(PChar(s), len, Result, wlen)*SizeOf(WideChar);
  319. if wlen = 0 then
  320. begin
  321. wlen:=AnsiToWideBuf(PChar(s), len, nil, 0)*SizeOf(WideChar);
  322. if wlen > 0 then
  323. begin
  324. ReAllocMem(Result, wlen);
  325. wlen:=AnsiToWideBuf(PChar(s), len, Result, wlen)*SizeOf(WideChar);
  326. end
  327. else
  328. begin
  329. Result^:=#0;
  330. wlen:=SizeOf(WideChar);
  331. end;
  332. end;
  333. if outlen <> nil then
  334. outlen^:=wlen div SizeOf(WideChar);
  335. end;
  336. {*****************************************************************************
  337. WinAPI wrappers implementation
  338. *****************************************************************************}
  339. const
  340. {$ifdef CPUARM}
  341. UserKData = $FFFFC800;
  342. {$else CPUARM}
  343. UserKData = $00005800;
  344. {$endif CPUARM}
  345. SYSHANDLE_OFFSET = $004;
  346. SYS_HANDLE_BASE = 64;
  347. SH_CURTHREAD = 1;
  348. SH_CURPROC = 2;
  349. type
  350. PHandle = ^THandle;
  351. const
  352. EVENT_PULSE = 1;
  353. EVENT_RESET = 2;
  354. EVENT_SET = 3;
  355. function CreateEventW(lpEventAttributes:pointer;bManualReset:longbool;bInitialState:longbool;lpName:PWideChar): THandle;
  356. cdecl; external KernelDLL name 'CreateEventW';
  357. function CreateEvent(lpEventAttributes:pointer;bManualReset:longbool;bInitialState:longbool;lpName:pchar): THandle;
  358. var
  359. buf: array[0..MaxPathLen] of WideChar;
  360. begin
  361. if lpName=nil then
  362. CreateEvent := CreateEventW(lpEventAttributes, bManualReset, bInitialState, nil)
  363. else begin
  364. AnsiToWideBuf(lpName, -1, buf, SizeOf(buf));
  365. CreateEvent := CreateEventW(lpEventAttributes, bManualReset, bInitialState, buf);
  366. end;
  367. end;
  368. function EventModify(h: THandle; func: DWORD): LONGBOOL;
  369. cdecl; external KernelDLL name 'EventModify';
  370. function TlsCall(p1, p2: DWORD): DWORD;
  371. cdecl; external KernelDLL name 'TlsCall';
  372. function ResetEvent(h: THandle): LONGBOOL;
  373. begin
  374. ResetEvent := EventModify(h,EVENT_RESET);
  375. end;
  376. function SetEvent(h: THandle): LONGBOOL;
  377. begin
  378. SetEvent := EventModify(h,EVENT_SET);
  379. end;
  380. function GetCurrentProcessId:DWORD;
  381. var
  382. p: PHandle;
  383. begin
  384. p:=PHandle(UserKData+SYSHANDLE_OFFSET + SH_CURPROC*SizeOf(THandle));
  385. GetCurrentProcessId := p^;
  386. end;
  387. function Win32GetCurrentThreadId:DWORD;
  388. var
  389. p: PHandle;
  390. begin
  391. p:=PHandle(UserKData+SYSHANDLE_OFFSET + SH_CURTHREAD*SizeOf(THandle));
  392. Win32GetCurrentThreadId := p^;
  393. end;
  394. const
  395. TLS_FUNCALLOC = 0;
  396. TLS_FUNCFREE = 1;
  397. function TlsAlloc : DWord;
  398. begin
  399. TlsAlloc := TlsCall(TLS_FUNCALLOC, 0);
  400. end;
  401. function TlsFree(dwTlsIndex : DWord) : LongBool;
  402. begin
  403. TlsFree := LongBool(TlsCall(TLS_FUNCFREE, dwTlsIndex));
  404. end;
  405. {*****************************************************************************
  406. Parameter Handling
  407. *****************************************************************************}
  408. function GetCommandLine : pwidechar;
  409. cdecl; external KernelDLL name 'GetCommandLineW';
  410. var
  411. ModuleName : array[0..255] of char;
  412. function GetCommandFile:pchar;
  413. var
  414. buf: array[0..MaxPathLen] of WideChar;
  415. begin
  416. if ModuleName[0] = #0 then begin
  417. GetModuleFileName(0, @buf, SizeOf(buf));
  418. WideToAnsiBuf(buf, -1, @ModuleName, SizeOf(ModuleName));
  419. end;
  420. GetCommandFile:=@ModuleName;
  421. end;
  422. var
  423. Fargc: longint;
  424. Fargv: ppchar;
  425. FCmdLine: PChar;
  426. procedure setup_arguments;
  427. var
  428. arglen,
  429. count : longint;
  430. argstart,
  431. pc,arg : pchar;
  432. quote : char;
  433. argvlen : longint;
  434. procedure allocarg(idx,len:longint);
  435. var
  436. oldargvlen : longint;
  437. begin
  438. if idx>=argvlen then
  439. begin
  440. oldargvlen:=argvlen;
  441. argvlen:=(idx+8) and (not 7);
  442. sysreallocmem(Fargv,argvlen*sizeof(pointer));
  443. fillchar(Fargv[oldargvlen],(argvlen-oldargvlen)*sizeof(pointer),0);
  444. end;
  445. { use realloc to reuse already existing memory }
  446. { always allocate, even if length is zero, since }
  447. { the arg. is still present! }
  448. sysreallocmem(Fargv[idx],len+1);
  449. end;
  450. begin
  451. { create commandline, it starts with the executed filename which is argv[0] }
  452. { WinCE passes the command NOT via the args, but via getmodulefilename}
  453. if FCmdLine <> nil then exit;
  454. argvlen:=0;
  455. pc:=getcommandfile;
  456. Arglen:=0;
  457. while pc[Arglen] <> #0 do
  458. Inc(Arglen);
  459. allocarg(0,arglen);
  460. move(pc^,Fargv[0]^,arglen+1);
  461. { Setup FCmdLine variable }
  462. arg:=PChar(GetCommandLine);
  463. count:=WideToAnsiBuf(PWideChar(arg), -1, nil, 0);
  464. FCmdLine:=SysGetMem(arglen + count + 3);
  465. FCmdLine^:='"';
  466. move(pc^, (FCmdLine + 1)^, arglen);
  467. (FCmdLine + arglen + 1)^:='"';
  468. (FCmdLine + arglen + 2)^:=' ';
  469. WideToAnsiBuf(PWideChar(arg), -1, FCmdLine + arglen + 3, count);
  470. { process arguments }
  471. count:=0;
  472. pc:=FCmdLine;
  473. {$IfDef SYSTEM_DEBUG_STARTUP}
  474. Writeln(stderr,'WinCE GetCommandLine is #',pc,'#');
  475. {$EndIf }
  476. while pc^<>#0 do
  477. begin
  478. { skip leading spaces }
  479. while pc^ in [#1..#32] do
  480. inc(pc);
  481. if pc^=#0 then
  482. break;
  483. { calc argument length }
  484. quote:=' ';
  485. argstart:=pc;
  486. arglen:=0;
  487. while (pc^<>#0) do
  488. begin
  489. case pc^ of
  490. #1..#32 :
  491. begin
  492. if quote<>' ' then
  493. inc(arglen)
  494. else
  495. break;
  496. end;
  497. '"' :
  498. begin
  499. if quote<>'''' then
  500. begin
  501. if pchar(pc+1)^<>'"' then
  502. begin
  503. if quote='"' then
  504. quote:=' '
  505. else
  506. quote:='"';
  507. end
  508. else
  509. inc(pc);
  510. end
  511. else
  512. inc(arglen);
  513. end;
  514. '''' :
  515. begin
  516. if quote<>'"' then
  517. begin
  518. if pchar(pc+1)^<>'''' then
  519. begin
  520. if quote='''' then
  521. quote:=' '
  522. else
  523. quote:='''';
  524. end
  525. else
  526. inc(pc);
  527. end
  528. else
  529. inc(arglen);
  530. end;
  531. else
  532. inc(arglen);
  533. end;
  534. inc(pc);
  535. end;
  536. { copy argument }
  537. { Don't copy the first one, it is already there.}
  538. If Count<>0 then
  539. begin
  540. allocarg(count,arglen);
  541. quote:=' ';
  542. pc:=argstart;
  543. arg:=Fargv[count];
  544. while (pc^<>#0) do
  545. begin
  546. case pc^ of
  547. #1..#32 :
  548. begin
  549. if quote<>' ' then
  550. begin
  551. arg^:=pc^;
  552. inc(arg);
  553. end
  554. else
  555. break;
  556. end;
  557. '"' :
  558. begin
  559. if quote<>'''' then
  560. begin
  561. if pchar(pc+1)^<>'"' then
  562. begin
  563. if quote='"' then
  564. quote:=' '
  565. else
  566. quote:='"';
  567. end
  568. else
  569. inc(pc);
  570. end
  571. else
  572. begin
  573. arg^:=pc^;
  574. inc(arg);
  575. end;
  576. end;
  577. '''' :
  578. begin
  579. if quote<>'"' then
  580. begin
  581. if pchar(pc+1)^<>'''' then
  582. begin
  583. if quote='''' then
  584. quote:=' '
  585. else
  586. quote:='''';
  587. end
  588. else
  589. inc(pc);
  590. end
  591. else
  592. begin
  593. arg^:=pc^;
  594. inc(arg);
  595. end;
  596. end;
  597. else
  598. begin
  599. arg^:=pc^;
  600. inc(arg);
  601. end;
  602. end;
  603. inc(pc);
  604. end;
  605. arg^:=#0;
  606. end;
  607. {$IfDef SYSTEM_DEBUG_STARTUP}
  608. Writeln(stderr,'dos arg ',count,' #',arglen,'#',Fargv[count],'#');
  609. {$EndIf SYSTEM_DEBUG_STARTUP}
  610. inc(count);
  611. end;
  612. { get argc and create an nil entry }
  613. Fargc:=count;
  614. allocarg(argc,0);
  615. { free unused memory }
  616. sysreallocmem(Fargv,(argc+1)*sizeof(pointer));
  617. end;
  618. function CmdLine: PChar;
  619. begin
  620. setup_arguments;
  621. Result:=FCmdLine;
  622. end;
  623. function argc: longint;
  624. begin
  625. setup_arguments;
  626. Result:=Fargc;
  627. end;
  628. function argv: ppchar;
  629. begin
  630. setup_arguments;
  631. Result:=Fargv;
  632. end;
  633. function paramcount : longint;
  634. begin
  635. paramcount := argc - 1;
  636. end;
  637. function paramstr(l : longint) : string;
  638. begin
  639. setup_arguments;
  640. if (l>=0) and (l<Fargc) then
  641. paramstr:=strpas(Fargv[l])
  642. else
  643. paramstr:='';
  644. end;
  645. procedure randomize;
  646. begin
  647. randseed:=GetTickCount;
  648. end;
  649. {*****************************************************************************
  650. System Dependent Exit code
  651. *****************************************************************************}
  652. procedure PascalMain;external name 'PASCALMAIN';
  653. procedure ExitThread(Exitcode : longint); cdecl; external 'coredll';
  654. Procedure system_exit;
  655. begin
  656. if IsLibrary then
  657. exit;
  658. if not IsConsole then
  659. begin
  660. Close(stderr);
  661. Close(stdout);
  662. Close(erroutput);
  663. Close(Input);
  664. Close(Output);
  665. end;
  666. ExitThread(exitcode);
  667. end;
  668. {$ifdef cpu386}
  669. var
  670. { value of the stack segment
  671. to check if the call stack can be written on exceptions }
  672. _SS : Cardinal;
  673. {$endif cpu386}
  674. procedure fpc_lib_exit_intern; external name 'FPC_LIB_EXIT';
  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. Fpc_Lib_Exit_intern;
  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 := 208;
  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.