syswin.inc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 1999-2008 by Florian Klaempfl and Pavel Ozerski
  4. member of the Free Pascal development team.
  5. FPC Pascal system unit part shared by win32/win64.
  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. {
  13. Error code definitions for the Win32 API functions
  14. Values are 32 bit values layed out as follows:
  15. 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
  16. 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
  17. +---+-+-+-----------------------+-------------------------------+
  18. |Sev|C|R| Facility | Code |
  19. +---+-+-+-----------------------+-------------------------------+
  20. where
  21. Sev - is the severity code
  22. 00 - Success
  23. 01 - Informational
  24. 10 - Warning
  25. 11 - Error
  26. C - is the Customer code flag
  27. R - is a reserved bit
  28. Facility - is the facility code
  29. Code - is the facility's status code
  30. }
  31. const
  32. SEVERITY_SUCCESS = $00000000;
  33. SEVERITY_INFORMATIONAL = $40000000;
  34. SEVERITY_WARNING = $80000000;
  35. SEVERITY_ERROR = $C0000000;
  36. const
  37. STATUS_SEGMENT_NOTIFICATION = $40000005;
  38. DBG_TERMINATE_THREAD = $40010003;
  39. DBG_TERMINATE_PROCESS = $40010004;
  40. DBG_CONTROL_C = $40010005;
  41. DBG_CONTROL_BREAK = $40010008;
  42. STATUS_GUARD_PAGE_VIOLATION = $80000001;
  43. STATUS_DATATYPE_MISALIGNMENT = $80000002;
  44. STATUS_BREAKPOINT = $80000003;
  45. STATUS_SINGLE_STEP = $80000004;
  46. DBG_EXCEPTION_NOT_HANDLED = $80010001;
  47. STATUS_ACCESS_VIOLATION = $C0000005;
  48. STATUS_IN_PAGE_ERROR = $C0000006;
  49. STATUS_INVALID_HANDLE = $C0000008;
  50. STATUS_NO_MEMORY = $C0000017;
  51. STATUS_ILLEGAL_INSTRUCTION = $C000001D;
  52. STATUS_NONCONTINUABLE_EXCEPTION = $C0000025;
  53. STATUS_INVALID_DISPOSITION = $C0000026;
  54. STATUS_ARRAY_BOUNDS_EXCEEDED = $C000008C;
  55. STATUS_FLOAT_DENORMAL_OPERAND = $C000008D;
  56. STATUS_FLOAT_DIVIDE_BY_ZERO = $C000008E;
  57. STATUS_FLOAT_INEXACT_RESULT = $C000008F;
  58. STATUS_FLOAT_INVALID_OPERATION = $C0000090;
  59. STATUS_FLOAT_OVERFLOW = $C0000091;
  60. STATUS_FLOAT_STACK_CHECK = $C0000092;
  61. STATUS_FLOAT_UNDERFLOW = $C0000093;
  62. STATUS_INTEGER_DIVIDE_BY_ZERO = $C0000094;
  63. STATUS_INTEGER_OVERFLOW = $C0000095;
  64. STATUS_PRIVILEGED_INSTRUCTION = $C0000096;
  65. STATUS_STACK_OVERFLOW = $C00000FD;
  66. STATUS_CONTROL_C_EXIT = $C000013A;
  67. STATUS_FLOAT_MULTIPLE_FAULTS = $C00002B4;
  68. STATUS_FLOAT_MULTIPLE_TRAPS = $C00002B5;
  69. STATUS_REG_NAT_CONSUMPTION = $C00002C9;
  70. { Exceptions raised by RTL use this code }
  71. FPC_EXCEPTION_CODE = $E0465043;
  72. EXCEPTION_EXECUTE_HANDLER = 1;
  73. EXCEPTION_CONTINUE_EXECUTION = -1;
  74. EXCEPTION_CONTINUE_SEARCH = 0;
  75. { exception flags (not everything applies to Win32!) }
  76. EXCEPTION_NONCONTINUABLE = $01;
  77. EXCEPTION_UNWINDING = $02;
  78. EXCEPTION_EXIT_UNWIND = $04;
  79. EXCEPTION_STACK_INVALID = $08;
  80. EXCEPTION_NESTED_CALL = $10;
  81. EXCEPTION_TARGET_UNWIND = $20;
  82. EXCEPTION_COLLIDED_UNWIND = $40;
  83. CONTEXT_X86 = $00010000;
  84. CONTEXT_CONTROL = CONTEXT_X86 or $00000001;
  85. CONTEXT_INTEGER = CONTEXT_X86 or $00000002;
  86. CONTEXT_SEGMENTS = CONTEXT_X86 or $00000004;
  87. CONTEXT_FLOATING_POINT = CONTEXT_X86 or $00000008;
  88. CONTEXT_DEBUG_REGISTERS = CONTEXT_X86 or $00000010;
  89. CONTEXT_EXTENDED_REGISTERS = CONTEXT_X86 or $00000020;
  90. CONTEXT_FULL = CONTEXT_CONTROL or CONTEXT_INTEGER or CONTEXT_SEGMENTS;
  91. MAXIMUM_SUPPORTED_EXTENSION = 512;
  92. type
  93. EXCEPTION_DISPOSITION=(
  94. ExceptionContinueExecution,
  95. ExceptionContinueSearch,
  96. ExceptionNestedException,
  97. ExceptionCollidedUnwind
  98. );
  99. TUnwindProc=procedure(frame: PtrUInt);
  100. PFilterRec=^TFilterRec;
  101. TFilterRec=record
  102. RvaClass: DWord;
  103. RvaHandler: DWord;
  104. end;
  105. TExceptObjProc=function(code: Longint; const rec: TExceptionRecord): Pointer; { Exception }
  106. TExceptClsProc=function(code: Longint): Pointer; { ExceptClass }
  107. procedure RaiseException(
  108. dwExceptionCode: DWORD;
  109. dwExceptionFlags: DWORD;
  110. dwArgCount: DWORD;
  111. lpArguments: Pointer); // msdn: *ULONG_PTR
  112. stdcall; external 'kernel32.dll' name 'RaiseException';
  113. function RunErrorCode(const rec: TExceptionRecord): longint;
  114. begin
  115. { negative result means 'FPU reset required' }
  116. case rec.ExceptionCode of
  117. STATUS_INTEGER_DIVIDE_BY_ZERO: result := 200; { reDivByZero }
  118. STATUS_FLOAT_DIVIDE_BY_ZERO: result := -208; { !!reZeroDivide }
  119. STATUS_ARRAY_BOUNDS_EXCEEDED: result := 201; { reRangeError }
  120. STATUS_STACK_OVERFLOW: result := 202; { reStackOverflow }
  121. STATUS_FLOAT_OVERFLOW: result := -205; { reOverflow }
  122. STATUS_FLOAT_DENORMAL_OPERAND,
  123. STATUS_FLOAT_UNDERFLOW: result := -206; { reUnderflow }
  124. STATUS_FLOAT_INEXACT_RESULT,
  125. STATUS_FLOAT_INVALID_OPERATION,
  126. STATUS_FLOAT_STACK_CHECK: result := -207; { reInvalidOp }
  127. STATUS_INTEGER_OVERFLOW: result := 215; { reIntOverflow }
  128. STATUS_ILLEGAL_INSTRUCTION: result := -216;
  129. STATUS_ACCESS_VIOLATION: result := 216; { reAccessViolation }
  130. STATUS_CONTROL_C_EXIT: result := 217; { reControlBreak }
  131. STATUS_PRIVILEGED_INSTRUCTION: result := 218; { rePrivilegedInstruction }
  132. STATUS_FLOAT_MULTIPLE_TRAPS,
  133. STATUS_FLOAT_MULTIPLE_FAULTS: result := -255; { indicate FPU reset }
  134. else
  135. result := 255; { reExternalException }
  136. end;
  137. end;
  138. procedure TranslateMxcsr(mxcsr: longword; var code: longint);
  139. begin
  140. { we can return only one value, further one's are lost }
  141. { InvalidOp }
  142. if (mxcsr and 1)<>0 then
  143. code:=-207
  144. { Denormal }
  145. else if (mxcsr and 2)<>0 then
  146. code:=-206
  147. { !!reZeroDivide }
  148. else if (mxcsr and 4)<>0 then
  149. code:=-208
  150. { reOverflow }
  151. else if (mxcsr and 8)<>0 then
  152. code:=-205
  153. { Underflow }
  154. else if (mxcsr and 16)<>0 then
  155. code:=-206
  156. { Precision }
  157. else if (mxcsr and 32)<>0 then
  158. code:=-207
  159. else { this should not happen }
  160. code:=-255
  161. end;
  162. function FilterException(var rec:TExceptionRecord; imagebase: PtrUInt; filterRva: DWord; errcode: Longint): Pointer;
  163. var
  164. ExClass: TClass;
  165. i: Longint;
  166. Filter: Pointer;
  167. curFilt: PFilterRec;
  168. begin
  169. result:=nil;
  170. if rec.ExceptionCode=FPC_EXCEPTION_CODE then
  171. ExClass:=TObject(rec.ExceptionInformation[1]).ClassType
  172. else if Assigned(ExceptClsProc) then
  173. ExClass:=TClass(TExceptClsProc(ExceptClsProc)(errcode))
  174. else
  175. Exit; { if we cannot determine type of exception, don't handle it }
  176. Filter:=Pointer(imagebase+filterRva);
  177. for i:=0 to PLongint(Filter)^-1 do
  178. begin
  179. CurFilt:=@PFilterRec(Filter+sizeof(Longint))[i];
  180. if (CurFilt^.RvaClass=$FFFFFFFF) or
  181. { TODO: exception might be coming from another module, need more advanced comparing }
  182. (ExClass.InheritsFrom(TClass(imagebase+CurFilt^.RvaClass))) then
  183. begin
  184. result:=Pointer(imagebase+CurFilt^.RvaHandler);
  185. exit;
  186. end;
  187. end;
  188. end;
  189. {*****************************************************************************
  190. Parameter Handling
  191. *****************************************************************************}
  192. procedure setup_arguments;
  193. var
  194. arglen,
  195. count : longint;
  196. argstart,
  197. pc,arg : pchar;
  198. quote : Boolean;
  199. argvlen : longint;
  200. buf: array[0..259] of char; // need MAX_PATH bytes, not 256!
  201. procedure allocarg(idx,len:longint);
  202. var
  203. oldargvlen : longint;
  204. begin
  205. if idx>=argvlen then
  206. begin
  207. oldargvlen:=argvlen;
  208. argvlen:=(idx+8) and (not 7);
  209. sysreallocmem(argv,argvlen*sizeof(pointer));
  210. fillchar(argv[oldargvlen],(argvlen-oldargvlen)*sizeof(pointer),0);
  211. end;
  212. { use realloc to reuse already existing memory }
  213. { always allocate, even if length is zero, since }
  214. { the arg. is still present! }
  215. sysreallocmem(argv[idx],len+1);
  216. end;
  217. begin
  218. { create commandline, it starts with the executed filename which is argv[0] }
  219. { Win32 passes the command NOT via the args, but via getmodulefilename}
  220. count:=0;
  221. argv:=nil;
  222. argvlen:=0;
  223. ArgLen := GetModuleFileName(0, @buf[0], sizeof(buf));
  224. buf[ArgLen] := #0; // be safe
  225. allocarg(0,arglen);
  226. move(buf,argv[0]^,arglen+1);
  227. { Setup cmdline variable }
  228. cmdline:=GetCommandLine;
  229. { process arguments }
  230. pc:=cmdline;
  231. {$IfDef SYSTEM_DEBUG_STARTUP}
  232. Writeln(stderr,'Win32 GetCommandLine is #',pc,'#');
  233. {$EndIf }
  234. while pc^<>#0 do
  235. begin
  236. { skip leading spaces }
  237. while pc^ in [#1..#32] do
  238. inc(pc);
  239. if pc^=#0 then
  240. break;
  241. { calc argument length }
  242. quote:=False;
  243. argstart:=pc;
  244. arglen:=0;
  245. while (pc^<>#0) do
  246. begin
  247. case pc^ of
  248. #1..#32 :
  249. begin
  250. if quote then
  251. inc(arglen)
  252. else
  253. break;
  254. end;
  255. '"' :
  256. if pc[1]<>'"' then
  257. quote := not quote
  258. else
  259. inc(pc);
  260. else
  261. inc(arglen);
  262. end;
  263. inc(pc);
  264. end;
  265. { copy argument }
  266. { Don't copy the first one, it is already there.}
  267. If Count<>0 then
  268. begin
  269. allocarg(count,arglen);
  270. quote:=False;
  271. pc:=argstart;
  272. arg:=argv[count];
  273. while (pc^<>#0) do
  274. begin
  275. case pc^ of
  276. #1..#32 :
  277. begin
  278. if quote then
  279. begin
  280. arg^:=pc^;
  281. inc(arg);
  282. end
  283. else
  284. break;
  285. end;
  286. '"' :
  287. if pc[1]<>'"' then
  288. quote := not quote
  289. else
  290. inc(pc);
  291. else
  292. begin
  293. arg^:=pc^;
  294. inc(arg);
  295. end;
  296. end;
  297. inc(pc);
  298. end;
  299. arg^:=#0;
  300. end;
  301. {$IfDef SYSTEM_DEBUG_STARTUP}
  302. Writeln(stderr,'dos arg ',count,' #',arglen,'#',argv[count],'#');
  303. {$EndIf SYSTEM_DEBUG_STARTUP}
  304. inc(count);
  305. end;
  306. { get argc }
  307. argc:=count;
  308. { free unused memory, leaving a nil entry at the end }
  309. sysreallocmem(argv,(count+1)*sizeof(pointer));
  310. argv[count] := nil;
  311. end;
  312. function paramcount : longint;
  313. begin
  314. paramcount := argc - 1;
  315. end;
  316. function paramstr(l : longint) : string;
  317. begin
  318. if (l>=0) and (l<argc) then
  319. paramstr:=strpas(argv[l])
  320. else
  321. paramstr:='';
  322. end;
  323. procedure randomize;
  324. begin
  325. randseed:=GetTickCount;
  326. end;
  327. Var
  328. DLLInitState : Longint = -1;
  329. DLLBuf : Jmp_buf;
  330. function Dll_entry{$ifdef FPC_HAS_INDIRECT_ENTRY_INFORMATION}(constref info : TEntryInformation){$endif FPC_HAS_INDIRECT_ENTRY_INFORMATION} : longbool; [public,alias:'_FPC_DLL_Entry'];
  331. begin
  332. {$ifdef FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  333. SetupEntryInformation(info);
  334. {$endif FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  335. IsLibrary:=true;
  336. DllInitState:=DLLreason;
  337. Dll_entry:=false; { return value is ignored, except when DLLreason=DLL_PROCESS_ATTACH }
  338. case DLLreason of
  339. DLL_PROCESS_ATTACH :
  340. begin
  341. MainThreadIdWin32 := Win32GetCurrentThreadId;
  342. If SetJmp(DLLBuf) = 0 then
  343. begin
  344. {$ifdef FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  345. EntryInformation.PascalMain();
  346. {$else FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  347. PascalMain;
  348. {$endif FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  349. Dll_entry:=true;
  350. end
  351. else
  352. Dll_entry:=(ExitCode=0);
  353. end;
  354. DLL_THREAD_ATTACH :
  355. begin
  356. { SysInitMultithreading must not be called here,
  357. see comments in exec_tls_callback below }
  358. { Allocate Threadvars }
  359. SysAllocateThreadVars;
  360. { NS : no idea what is correct to pass here - pass dummy value for now }
  361. { passing a dummy is ok, the correct value is read from the coff header of SysInstance (FK) }
  362. InitThread($1000000); { Assume everything is idempotent there, as the thread could have been created with BeginThread... }
  363. if assigned(Dll_Thread_Attach_Hook) then
  364. Dll_Thread_Attach_Hook(DllParam);
  365. end;
  366. DLL_THREAD_DETACH :
  367. begin
  368. if assigned(Dll_Thread_Detach_Hook) then
  369. Dll_Thread_Detach_Hook(DllParam);
  370. { Release Threadvars }
  371. if TlsGetValue(TLSKey^)<>nil then
  372. DoneThread; { Assume everything is idempotent there }
  373. end;
  374. DLL_PROCESS_DETACH :
  375. begin
  376. if MainThreadIDWin32=0 then // already been here.
  377. exit;
  378. If SetJmp(DLLBuf) = 0 then
  379. begin
  380. if assigned(Dll_Process_Detach_Hook) then
  381. Dll_Process_Detach_Hook(DllParam);
  382. InternalExit;
  383. end;
  384. SysReleaseThreadVars;
  385. { Free TLS resources used by ThreadVars }
  386. SysFiniMultiThreading;
  387. MainThreadIDWin32:=0;
  388. end;
  389. end;
  390. DllInitState:=-1;
  391. end;
  392. {****************************************************************************
  393. Error Message writing using messageboxes
  394. ****************************************************************************}
  395. function MessageBox(w1:THandle;l1,l2:pointer;w2:longint):longint;
  396. stdcall;external 'user32' name 'MessageBoxA';
  397. const
  398. ErrorBufferLength = 1024;
  399. var
  400. ErrorBuf : array[0..ErrorBufferLength] of char;
  401. ErrorLen : SizeInt;
  402. procedure ErrorWrite(Var F: TextRec);
  403. {
  404. An error message should always end with #13#10#13#10
  405. }
  406. var
  407. i : SizeInt;
  408. Begin
  409. while F.BufPos>0 do
  410. begin
  411. begin
  412. if F.BufPos+ErrorLen>ErrorBufferLength then
  413. i:=ErrorBufferLength-ErrorLen
  414. else
  415. i:=F.BufPos;
  416. Move(F.BufPtr^,ErrorBuf[ErrorLen],i);
  417. inc(ErrorLen,i);
  418. ErrorBuf[ErrorLen]:=#0;
  419. end;
  420. if ErrorLen=ErrorBufferLength then
  421. begin
  422. if not NoErrMsg then
  423. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  424. ErrorLen:=0;
  425. end;
  426. Dec(F.BufPos,i);
  427. end;
  428. End;
  429. procedure ErrorClose(Var F: TextRec);
  430. begin
  431. if ErrorLen>0 then
  432. begin
  433. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  434. ErrorLen:=0;
  435. end;
  436. ErrorLen:=0;
  437. end;
  438. procedure ErrorOpen(Var F: TextRec);
  439. Begin
  440. TextRec(F).InOutFunc:=@ErrorWrite;
  441. TextRec(F).FlushFunc:=@ErrorWrite;
  442. TextRec(F).CloseFunc:=@ErrorClose;
  443. ErrorLen:=0;
  444. End;
  445. procedure AssignError(Var T: Text);
  446. begin
  447. Assign(T,'');
  448. TextRec(T).OpenFunc:=@ErrorOpen;
  449. Rewrite(T);
  450. end;
  451. procedure SysInitStdIO;
  452. begin
  453. { Setup stdin, stdout and stderr, for GUI apps redirect stderr,stdout to be
  454. displayed in a messagebox }
  455. { WARNING: this should be done only once at startup,
  456. not for DLL entry code, as the standard handles might
  457. have been redirected }
  458. if StdInputHandle=0 then
  459. StdInputHandle:=THandle(GetStdHandle(cardinal(STD_INPUT_HANDLE)));
  460. if StdOutputHandle=0 then
  461. StdOutputHandle:=THandle(GetStdHandle(cardinal(STD_OUTPUT_HANDLE)));
  462. if StdErrorHandle=0 then
  463. StdErrorHandle:=THandle(GetStdHandle(cardinal(STD_ERROR_HANDLE)));
  464. if not IsConsole then
  465. begin
  466. AssignError(stderr);
  467. AssignError(StdOut);
  468. Assign(Output,'');
  469. Assign(Input,'');
  470. Assign(ErrOutput,'');
  471. end
  472. else
  473. begin
  474. OpenStdIO(Input,fmInput,StdInputHandle);
  475. OpenStdIO(Output,fmOutput,StdOutputHandle);
  476. OpenStdIO(ErrOutput,fmOutput,StdErrorHandle);
  477. OpenStdIO(StdOut,fmOutput,StdOutputHandle);
  478. OpenStdIO(StdErr,fmOutput,StdErrorHandle);
  479. end;
  480. end;
  481. { ProcessID cached to avoid repeated calls to GetCurrentProcess. }
  482. var
  483. ProcessID: SizeUInt;
  484. function GetProcessID: SizeUInt;
  485. begin
  486. GetProcessID := ProcessID;
  487. end;
  488. {******************************************************************************
  489. Unicode
  490. ******************************************************************************}
  491. const
  492. { MultiByteToWideChar }
  493. MB_PRECOMPOSED = 1;
  494. WC_NO_BEST_FIT_CHARS = $400;
  495. function MultiByteToWideChar(CodePage:UINT; dwFlags:DWORD; lpMultiByteStr:PChar; cchMultiByte:longint; lpWideCharStr:PWideChar;cchWideChar:longint):longint;
  496. stdcall; external 'kernel32' name 'MultiByteToWideChar';
  497. function WideCharToMultiByte(CodePage:UINT; dwFlags:DWORD; lpWideCharStr:PWideChar; cchWideChar:longint; lpMultiByteStr:PChar;cchMultiByte:longint; lpDefaultChar:PChar; lpUsedDefaultChar:pointer):longint;
  498. stdcall; external 'kernel32' name 'WideCharToMultiByte';
  499. function CharUpperBuff(lpsz:LPWSTR; cchLength:DWORD):DWORD;
  500. stdcall; external 'user32' name 'CharUpperBuffW';
  501. function CharLowerBuff(lpsz:LPWSTR; cchLength:DWORD):DWORD;
  502. stdcall; external 'user32' name 'CharLowerBuffW';
  503. procedure Win32Unicode2AnsiMove(source:punicodechar;var dest:RawByteString;cp : TSystemCodePage;len:SizeInt);
  504. var
  505. destlen: SizeInt;
  506. begin
  507. // retrieve length including trailing #0
  508. // not anymore, because this must also be usable for single characters
  509. destlen:=WideCharToMultiByte(cp, 0, source, len, nil, 0, nil, nil);
  510. // this will null-terminate
  511. setlength(dest, destlen);
  512. if destlen>0 then
  513. begin
  514. WideCharToMultiByte(cp, 0, source, len, @dest[1], destlen, nil, nil);
  515. PAnsiRec(pointer(dest)-AnsiFirstOff)^.CodePage:=cp;
  516. end;
  517. end;
  518. procedure Win32Ansi2UnicodeMove(source:pchar;cp : TSystemCodePage;var dest:UnicodeString;len:SizeInt);
  519. var
  520. destlen: SizeInt;
  521. dwflags: DWORD;
  522. begin
  523. // retrieve length including trailing #0
  524. // not anymore, because this must also be usable for single characters
  525. if cp=CP_UTF8 then
  526. dwFlags:=0
  527. else
  528. dwFlags:=MB_PRECOMPOSED;
  529. destlen:=MultiByteToWideChar(cp, dwFlags, source, len, nil, 0);
  530. // this will null-terminate
  531. setlength(dest, destlen);
  532. if destlen>0 then
  533. begin
  534. MultiByteToWideChar(cp, dwFlags, source, len, @dest[1], destlen);
  535. PUnicodeRec(pointer(dest)-UnicodeFirstOff)^.CodePage:=CP_UTF16;
  536. end;
  537. end;
  538. function Win32UnicodeUpper(const s : UnicodeString) : UnicodeString;
  539. begin
  540. result:=s;
  541. UniqueString(result);
  542. if length(result)>0 then
  543. CharUpperBuff(LPWSTR(result),length(result));
  544. end;
  545. function Win32UnicodeLower(const s : UnicodeString) : UnicodeString;
  546. begin
  547. result:=s;
  548. UniqueString(result);
  549. if length(result)>0 then
  550. CharLowerBuff(LPWSTR(result),length(result));
  551. end;
  552. {******************************************************************************
  553. Widestring
  554. ******************************************************************************}
  555. procedure Win32Ansi2WideMove(source:pchar;cp : TSystemCodePage;var dest:widestring;len:SizeInt);
  556. var
  557. destlen: SizeInt;
  558. dwFlags: DWORD;
  559. begin
  560. // retrieve length including trailing #0
  561. // not anymore, because this must also be usable for single characters
  562. if cp=CP_UTF8 then
  563. dwFlags:=0
  564. else
  565. dwFlags:=MB_PRECOMPOSED;
  566. destlen:=MultiByteToWideChar(cp, dwFlags, source, len, nil, 0);
  567. // this will null-terminate
  568. setlength(dest, destlen);
  569. if destlen>0 then
  570. MultiByteToWideChar(cp, dwFlags, source, len, @dest[1], destlen);
  571. end;
  572. function Win32WideUpper(const s : WideString) : WideString;
  573. begin
  574. result:=s;
  575. if length(result)>0 then
  576. CharUpperBuff(LPWSTR(result),length(result));
  577. end;
  578. function Win32WideLower(const s : WideString) : WideString;
  579. begin
  580. result:=s;
  581. if length(result)>0 then
  582. CharLowerBuff(LPWSTR(result),length(result));
  583. end;
  584. type
  585. PWStrInitEntry = ^TWStrInitEntry;
  586. TWStrInitEntry = record
  587. addr: PPointer;
  588. data: Pointer;
  589. end;
  590. PWStrInitTablesTable = ^TWStrInitTablesTable;
  591. TWStrInitTablesTable = packed record
  592. count : {$ifdef VER2_6}longint{$else}sizeint{$endif};
  593. tables : packed array [1..32767] of PWStrInitEntry;
  594. end;
  595. var
  596. {$ifdef FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  597. WStrInitTablesTable: PWStrInitTablesTable;
  598. {$else FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  599. WStrInitTablesTableVar: TWStrInitTablesTable; external name 'FPC_WIDEINITTABLES';
  600. WStrInitTablesTable: PWStrInitTablesTable = @WStrInitTablesTableVar;
  601. {$endif FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  602. function GetACP:UINT; stdcall; external 'kernel32' name 'GetACP';
  603. function GetConsoleCP:UINT; stdcall; external 'kernel32' name 'GetConsoleCP';
  604. function Win32GetStandardCodePage(const stdcp: TStandardCodePageEnum): TSystemCodePage;
  605. begin
  606. case stdcp of
  607. scpAnsi,
  608. scpFileSystemSingleByte: Result := GetACP;
  609. scpConsoleInput: Result := GetConsoleCP;
  610. scpConsoleOutput: Result := GetConsoleOutputCP;
  611. end;
  612. end;
  613. { there is a similiar procedure in sysutils which inits the fields which
  614. are only relevant for the sysutils units }
  615. procedure InitWin32Widestrings;
  616. var
  617. i: longint;
  618. ptable: PWStrInitEntry;
  619. begin
  620. {$if not(defined(VER2_2) or defined(VER2_4))}
  621. { assign initial values to global Widestring typed consts }
  622. for i:=1 to WStrInitTablesTable^.count do
  623. begin
  624. ptable:=WStrInitTablesTable^.tables[i];
  625. while Assigned(ptable^.addr) do
  626. begin
  627. fpc_widestr_assign(ptable^.addr^, ptable^.data);
  628. Inc(ptable);
  629. end;
  630. end;
  631. {$endif}
  632. { Note: since WideChar=UnicodeChar and PWideChar=PUnicodeChar,
  633. Wide2AnsiMoveProc is identical to Unicode2AnsiStrMoveProc. }
  634. { Widestring }
  635. widestringmanager.Wide2AnsiMoveProc:=@Win32Unicode2AnsiMove;
  636. widestringmanager.Ansi2WideMoveProc:=@Win32Ansi2WideMove;
  637. widestringmanager.UpperWideStringProc:=@Win32WideUpper;
  638. widestringmanager.LowerWideStringProc:=@Win32WideLower;
  639. { Unicode }
  640. widestringmanager.Unicode2AnsiMoveProc:=@Win32Unicode2AnsiMove;
  641. widestringmanager.Ansi2UnicodeMoveProc:=@Win32Ansi2UnicodeMove;
  642. widestringmanager.UpperUnicodeStringProc:=@Win32UnicodeUpper;
  643. widestringmanager.LowerUnicodeStringProc:=@Win32UnicodeLower;
  644. { Codepage }
  645. widestringmanager.GetStandardCodePageProc:=@Win32GetStandardCodePage;
  646. DefaultSystemCodePage:=GetACP;
  647. DefaultUnicodeCodePage:=CP_UTF16;
  648. DefaultFileSystemCodePage:=CP_UTF8;
  649. DefaultRTLFileSystemCodePage:=DefaultSystemCodePage;
  650. end;
  651. type
  652. WINBOOL = longbool;
  653. PHANDLER_ROUTINE = function (dwCtrlType:DWORD):WINBOOL; stdcall;
  654. function SetConsoleCtrlHandler(HandlerRoutine:PHANDLER_ROUTINE; Add:WINBOOL):WINBOOL; stdcall;
  655. external 'kernel32' name 'SetConsoleCtrlHandler';
  656. function WinCtrlBreakHandler(dwCtrlType:DWORD): WINBOOL;stdcall;
  657. const
  658. CTRL_BREAK_EVENT = 1;
  659. begin
  660. if Assigned(CtrlBreakHandler) then
  661. Result:=CtrlBreakHandler((dwCtrlType and CTRL_BREAK_EVENT > 0))
  662. else
  663. Result:=false;
  664. end;
  665. function SysSetCtrlBreakHandler (Handler: TCtrlBreakHandler): TCtrlBreakHandler;
  666. begin
  667. (* Return either nil or previous handler *)
  668. if (Assigned(CtrlBreakHandler)) and (not Assigned(Handler)) then
  669. SetConsoleCtrlHandler(@WinCtrlBreakHandler, false)
  670. else if (not Assigned(CtrlBreakHandler)) and (Assigned(Handler)) then
  671. SetConsoleCtrlHandler(@WinCtrlBreakHandler, true);
  672. SysSetCtrlBreakHandler := CtrlBreakHandler;
  673. CtrlBreakHandler := Handler;
  674. end;