syswin.inc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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. case (mxcsr and $3f) of
  141. 1,32: code:=-207; { InvalidOp, Precision }
  142. 2,16: code:=-206; { Denormal, Underflow }
  143. 4: code:=-208; { !!reZeroDivide }
  144. 8: code:=-205; { reOverflow }
  145. end;
  146. end;
  147. function FilterException(var rec:TExceptionRecord; imagebase: PtrUInt; filterRva: DWord; errcode: Longint): Pointer;
  148. var
  149. ExClass: TClass;
  150. i: Longint;
  151. Filter: Pointer;
  152. curFilt: PFilterRec;
  153. begin
  154. result:=nil;
  155. if rec.ExceptionCode=FPC_EXCEPTION_CODE then
  156. ExClass:=TObject(rec.ExceptionInformation[1]).ClassType
  157. else if Assigned(ExceptClsProc) then
  158. ExClass:=TClass(TExceptClsProc(ExceptClsProc)(errcode))
  159. else
  160. Exit; { if we cannot determine type of exception, don't handle it }
  161. Filter:=Pointer(imagebase+filterRva);
  162. for i:=0 to PLongint(Filter)^-1 do
  163. begin
  164. CurFilt:=@PFilterRec(Filter+sizeof(Longint))[i];
  165. if (CurFilt^.RvaClass=$FFFFFFFF) or
  166. { TODO: exception might be coming from another module, need more advanced comparing }
  167. (ExClass.InheritsFrom(TClass(imagebase+CurFilt^.RvaClass))) then
  168. begin
  169. result:=Pointer(imagebase+CurFilt^.RvaHandler);
  170. exit;
  171. end;
  172. end;
  173. end;
  174. {*****************************************************************************
  175. Parameter Handling
  176. *****************************************************************************}
  177. procedure setup_arguments;
  178. var
  179. arglen,
  180. count : longint;
  181. argstart,
  182. pc,arg : pchar;
  183. quote : Boolean;
  184. argvlen : longint;
  185. buf: array[0..259] of char; // need MAX_PATH bytes, not 256!
  186. procedure allocarg(idx,len:longint);
  187. var
  188. oldargvlen : longint;
  189. begin
  190. if idx>=argvlen then
  191. begin
  192. oldargvlen:=argvlen;
  193. argvlen:=(idx+8) and (not 7);
  194. sysreallocmem(argv,argvlen*sizeof(pointer));
  195. fillchar(argv[oldargvlen],(argvlen-oldargvlen)*sizeof(pointer),0);
  196. end;
  197. { use realloc to reuse already existing memory }
  198. { always allocate, even if length is zero, since }
  199. { the arg. is still present! }
  200. sysreallocmem(argv[idx],len+1);
  201. end;
  202. begin
  203. { create commandline, it starts with the executed filename which is argv[0] }
  204. { Win32 passes the command NOT via the args, but via getmodulefilename}
  205. count:=0;
  206. argv:=nil;
  207. argvlen:=0;
  208. ArgLen := GetModuleFileName(0, @buf[0], sizeof(buf));
  209. buf[ArgLen] := #0; // be safe
  210. allocarg(0,arglen);
  211. move(buf,argv[0]^,arglen+1);
  212. { Setup cmdline variable }
  213. cmdline:=GetCommandLine;
  214. { process arguments }
  215. pc:=cmdline;
  216. {$IfDef SYSTEM_DEBUG_STARTUP}
  217. Writeln(stderr,'Win32 GetCommandLine is #',pc,'#');
  218. {$EndIf }
  219. while pc^<>#0 do
  220. begin
  221. { skip leading spaces }
  222. while pc^ in [#1..#32] do
  223. inc(pc);
  224. if pc^=#0 then
  225. break;
  226. { calc argument length }
  227. quote:=False;
  228. argstart:=pc;
  229. arglen:=0;
  230. while (pc^<>#0) do
  231. begin
  232. case pc^ of
  233. #1..#32 :
  234. begin
  235. if quote then
  236. inc(arglen)
  237. else
  238. break;
  239. end;
  240. '"' :
  241. if pc[1]<>'"' then
  242. quote := not quote
  243. else
  244. inc(pc);
  245. else
  246. inc(arglen);
  247. end;
  248. inc(pc);
  249. end;
  250. { copy argument }
  251. { Don't copy the first one, it is already there.}
  252. If Count<>0 then
  253. begin
  254. allocarg(count,arglen);
  255. quote:=False;
  256. pc:=argstart;
  257. arg:=argv[count];
  258. while (pc^<>#0) do
  259. begin
  260. case pc^ of
  261. #1..#32 :
  262. begin
  263. if quote then
  264. begin
  265. arg^:=pc^;
  266. inc(arg);
  267. end
  268. else
  269. break;
  270. end;
  271. '"' :
  272. if pc[1]<>'"' then
  273. quote := not quote
  274. else
  275. inc(pc);
  276. else
  277. begin
  278. arg^:=pc^;
  279. inc(arg);
  280. end;
  281. end;
  282. inc(pc);
  283. end;
  284. arg^:=#0;
  285. end;
  286. {$IfDef SYSTEM_DEBUG_STARTUP}
  287. Writeln(stderr,'dos arg ',count,' #',arglen,'#',argv[count],'#');
  288. {$EndIf SYSTEM_DEBUG_STARTUP}
  289. inc(count);
  290. end;
  291. { get argc }
  292. argc:=count;
  293. { free unused memory, leaving a nil entry at the end }
  294. sysreallocmem(argv,(count+1)*sizeof(pointer));
  295. argv[count] := nil;
  296. end;
  297. function paramcount : longint;
  298. begin
  299. paramcount := argc - 1;
  300. end;
  301. function paramstr(l : longint) : string;
  302. begin
  303. if (l>=0) and (l<argc) then
  304. paramstr:=strpas(argv[l])
  305. else
  306. paramstr:='';
  307. end;
  308. procedure randomize;
  309. begin
  310. randseed:=GetTickCount;
  311. end;
  312. type
  313. PWStrInitEntry = ^TWStrInitEntry;
  314. TWStrInitEntry = record
  315. addr: PPointer;
  316. data: Pointer;
  317. end;
  318. PPWStrInitEntry = ^PWStrInitEntry;
  319. PWStrInitTablesTable = ^TWStrInitTablesTable;
  320. TWStrInitTablesTable = packed record
  321. count : {$ifdef VER2_6}longint{$else}sizeint{$endif};
  322. tables : packed array [1..32767] of {$ifndef ver2_6}PPWStrInitEntry{$else}PWStrInitEntry{$endif};
  323. end;
  324. {$if not(defined(VER2_2) or defined(VER2_4))}
  325. var
  326. WStrInitTablesTable: PWStrInitTablesTable;
  327. {$endif}
  328. Var
  329. DLLInitState : Longint = -1;
  330. DLLBuf : Jmp_buf;
  331. function Dll_entry{$ifdef FPC_HAS_INDIRECT_MAIN_INFORMATION}(const info : TEntryInformation){$endif FPC_HAS_INDIRECT_MAIN_INFORMATION} : longbool; [public,alias:'_FPC_DLL_Entry'];
  332. begin
  333. {$ifdef FPC_HAS_INDIRECT_MAIN_INFORMATION}
  334. EntryInformation:=info;
  335. FPCResStrInitTables:=info.ResStrInitTables;
  336. FPCResourceStringTables:=info.ResourceStringTables;
  337. FPCSysInstance:=info.Platform.SysInstanceAddr^;
  338. FPCTlsKey:=info.Platform.TlsKeyAddr;
  339. WStrInitTablesTable:=info.WideInitTables;
  340. {$endif FPC_HAS_INDIRECT_MAIN_INFORMATION}
  341. IsLibrary:=true;
  342. DllInitState:=DLLreason;
  343. Dll_entry:=false; { return value is ignored, except when DLLreason=DLL_PROCESS_ATTACH }
  344. case DLLreason of
  345. DLL_PROCESS_ATTACH :
  346. begin
  347. MainThreadIdWin32 := Win32GetCurrentThreadId;
  348. If SetJmp(DLLBuf) = 0 then
  349. begin
  350. {$ifdef FPC_HAS_INDIRECT_MAIN_INFORMATION}
  351. EntryInformation.PascalMain();
  352. {$else FPC_HAS_INDIRECT_MAIN_INFORMATION}
  353. PascalMain;
  354. {$endif FPC_HAS_INDIRECT_MAIN_INFORMATION}
  355. Dll_entry:=true;
  356. end
  357. else
  358. Dll_entry:=(ExitCode=0);
  359. end;
  360. DLL_THREAD_ATTACH :
  361. begin
  362. { SysInitMultithreading must not be called here,
  363. see comments in exec_tls_callback below }
  364. { Allocate Threadvars }
  365. SysAllocateThreadVars;
  366. { NS : no idea what is correct to pass here - pass dummy value for now }
  367. { passing a dummy is ok, the correct value is read from the coff header of SysInstance (FK) }
  368. InitThread($1000000); { Assume everything is idempotent there, as the thread could have been created with BeginThread... }
  369. if assigned(Dll_Thread_Attach_Hook) then
  370. Dll_Thread_Attach_Hook(DllParam);
  371. end;
  372. DLL_THREAD_DETACH :
  373. begin
  374. if assigned(Dll_Thread_Detach_Hook) then
  375. Dll_Thread_Detach_Hook(DllParam);
  376. { Release Threadvars }
  377. if TlsGetValue(TLSKey^)<>nil then
  378. DoneThread; { Assume everything is idempotent there }
  379. end;
  380. DLL_PROCESS_DETACH :
  381. begin
  382. if MainThreadIDWin32=0 then // already been here.
  383. exit;
  384. If SetJmp(DLLBuf) = 0 then
  385. begin
  386. if assigned(Dll_Process_Detach_Hook) then
  387. Dll_Process_Detach_Hook(DllParam);
  388. InternalExit;
  389. end;
  390. SysReleaseThreadVars;
  391. { Free TLS resources used by ThreadVars }
  392. SysFiniMultiThreading;
  393. MainThreadIDWin32:=0;
  394. end;
  395. end;
  396. DllInitState:=-1;
  397. end;
  398. {****************************************************************************
  399. Error Message writing using messageboxes
  400. ****************************************************************************}
  401. function MessageBox(w1:THandle;l1,l2:pointer;w2:longint):longint;
  402. stdcall;external 'user32' name 'MessageBoxA';
  403. const
  404. ErrorBufferLength = 1024;
  405. var
  406. ErrorBuf : array[0..ErrorBufferLength] of char;
  407. ErrorLen : SizeInt;
  408. procedure ErrorWrite(Var F: TextRec);
  409. {
  410. An error message should always end with #13#10#13#10
  411. }
  412. var
  413. i : SizeInt;
  414. Begin
  415. while F.BufPos>0 do
  416. begin
  417. begin
  418. if F.BufPos+ErrorLen>ErrorBufferLength then
  419. i:=ErrorBufferLength-ErrorLen
  420. else
  421. i:=F.BufPos;
  422. Move(F.BufPtr^,ErrorBuf[ErrorLen],i);
  423. inc(ErrorLen,i);
  424. ErrorBuf[ErrorLen]:=#0;
  425. end;
  426. if ErrorLen=ErrorBufferLength then
  427. begin
  428. if not NoErrMsg then
  429. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  430. ErrorLen:=0;
  431. end;
  432. Dec(F.BufPos,i);
  433. end;
  434. End;
  435. procedure ErrorClose(Var F: TextRec);
  436. begin
  437. if ErrorLen>0 then
  438. begin
  439. MessageBox(0,@ErrorBuf,pchar('Error'),0);
  440. ErrorLen:=0;
  441. end;
  442. ErrorLen:=0;
  443. end;
  444. procedure ErrorOpen(Var F: TextRec);
  445. Begin
  446. TextRec(F).InOutFunc:=@ErrorWrite;
  447. TextRec(F).FlushFunc:=@ErrorWrite;
  448. TextRec(F).CloseFunc:=@ErrorClose;
  449. ErrorLen:=0;
  450. End;
  451. procedure AssignError(Var T: Text);
  452. begin
  453. Assign(T,'');
  454. TextRec(T).OpenFunc:=@ErrorOpen;
  455. Rewrite(T);
  456. end;
  457. procedure SysInitStdIO;
  458. begin
  459. { Setup stdin, stdout and stderr, for GUI apps redirect stderr,stdout to be
  460. displayed in a messagebox }
  461. StdInputHandle:=longint(GetStdHandle(cardinal(STD_INPUT_HANDLE)));
  462. StdOutputHandle:=longint(GetStdHandle(cardinal(STD_OUTPUT_HANDLE)));
  463. StdErrorHandle:=longint(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. function GetACP:UINT; stdcall; external 'kernel32' name 'GetACP';
  585. function GetConsoleCP:UINT; stdcall; external 'kernel32' name 'GetConsoleCP';
  586. function Win32GetStandardCodePage(const stdcp: TStandardCodePageEnum): TSystemCodePage;
  587. begin
  588. case stdcp of
  589. scpAnsi,
  590. scpFileSystemSingleByte: Result := GetACP;
  591. scpConsoleInput: Result := GetConsoleCP;
  592. scpConsoleOutput: Result := GetConsoleOutputCP;
  593. end;
  594. end;
  595. { there is a similiar procedure in sysutils which inits the fields which
  596. are only relevant for the sysutils units }
  597. procedure InitWin32Widestrings;
  598. var
  599. i: longint;
  600. ptable: PWStrInitEntry;
  601. begin
  602. {$if not(defined(VER2_2) or defined(VER2_4))}
  603. { assign initial values to global Widestring typed consts }
  604. for i:=1 to WStrInitTablesTable^.count do
  605. begin
  606. ptable:=WStrInitTablesTable^.tables[i]{$ifndef ver2_6}^{$endif};
  607. while Assigned(ptable^.addr) do
  608. begin
  609. fpc_widestr_assign(ptable^.addr^, ptable^.data);
  610. Inc(ptable);
  611. end;
  612. end;
  613. {$endif}
  614. { Note: since WideChar=UnicodeChar and PWideChar=PUnicodeChar,
  615. Wide2AnsiMoveProc is identical to Unicode2AnsiStrMoveProc. }
  616. { Widestring }
  617. widestringmanager.Wide2AnsiMoveProc:=@Win32Unicode2AnsiMove;
  618. widestringmanager.Ansi2WideMoveProc:=@Win32Ansi2WideMove;
  619. widestringmanager.UpperWideStringProc:=@Win32WideUpper;
  620. widestringmanager.LowerWideStringProc:=@Win32WideLower;
  621. { Unicode }
  622. widestringmanager.Unicode2AnsiMoveProc:=@Win32Unicode2AnsiMove;
  623. widestringmanager.Ansi2UnicodeMoveProc:=@Win32Ansi2UnicodeMove;
  624. widestringmanager.UpperUnicodeStringProc:=@Win32UnicodeUpper;
  625. widestringmanager.LowerUnicodeStringProc:=@Win32UnicodeLower;
  626. { Codepage }
  627. widestringmanager.GetStandardCodePageProc:=@Win32GetStandardCodePage;
  628. DefaultSystemCodePage:=GetACP;
  629. DefaultUnicodeCodePage:=CP_UTF16;
  630. DefaultFileSystemCodePage:=CP_UTF8;
  631. DefaultRTLFileSystemCodePage:=DefaultSystemCodePage;
  632. end;