include: Add constants for CryptProtectMemory/CryptUnprotectMemory.
[wine.git] / dlls / ntdll / nt.c
blob7be2a074a66aadc5442f8288046147115191257f
1 /*
2 * NT basis DLL
4 * This file contains the Nt* API functions of NTDLL.DLL.
5 * In the original ntdll.dll they all seem to just call int 0x2e (down to the NTOSKRNL)
7 * Copyright 1996-1998 Marcus Meissner
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 #include "config.h"
25 #include "wine/port.h"
27 #ifdef HAVE_SYS_PARAM_H
28 # include <sys/param.h>
29 #endif
30 #ifdef HAVE_SYS_SYSCTL_H
31 # include <sys/sysctl.h>
32 #endif
33 #ifdef HAVE_MACHINE_CPU_H
34 # include <machine/cpu.h>
35 #endif
36 #ifdef HAVE_MACH_MACHINE_H
37 # include <mach/machine.h>
38 #endif
40 #include <ctype.h>
41 #include <string.h>
42 #include <stdarg.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #ifdef HAVE_SYS_TIME_H
46 # include <sys/time.h>
47 #endif
48 #include <time.h>
50 #define NONAMELESSUNION
51 #include "ntstatus.h"
52 #define WIN32_NO_STATUS
53 #include "wine/debug.h"
54 #include "wine/unicode.h"
55 #include "windef.h"
56 #include "winternl.h"
57 #include "ntdll_misc.h"
58 #include "wine/server.h"
59 #include "ddk/wdm.h"
61 #ifdef __APPLE__
62 #include <mach/mach_init.h>
63 #include <mach/mach_host.h>
64 #include <mach/vm_map.h>
65 #endif
67 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
70 * Token
73 /******************************************************************************
74 * NtDuplicateToken [NTDLL.@]
75 * ZwDuplicateToken [NTDLL.@]
77 NTSTATUS WINAPI NtDuplicateToken(
78 IN HANDLE ExistingToken,
79 IN ACCESS_MASK DesiredAccess,
80 IN POBJECT_ATTRIBUTES ObjectAttributes,
81 IN SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
82 IN TOKEN_TYPE TokenType,
83 OUT PHANDLE NewToken)
85 NTSTATUS status;
87 TRACE("(%p,0x%08x,%s,0x%08x,0x%08x,%p)\n",
88 ExistingToken, DesiredAccess, debugstr_ObjectAttributes(ObjectAttributes),
89 ImpersonationLevel, TokenType, NewToken);
91 if (ObjectAttributes && ObjectAttributes->SecurityQualityOfService)
93 SECURITY_QUALITY_OF_SERVICE *SecurityQOS = ObjectAttributes->SecurityQualityOfService;
94 TRACE("ObjectAttributes->SecurityQualityOfService = {%d, %d, %d, %s}\n",
95 SecurityQOS->Length, SecurityQOS->ImpersonationLevel,
96 SecurityQOS->ContextTrackingMode,
97 SecurityQOS->EffectiveOnly ? "TRUE" : "FALSE");
98 ImpersonationLevel = SecurityQOS->ImpersonationLevel;
101 SERVER_START_REQ( duplicate_token )
103 req->handle = wine_server_obj_handle( ExistingToken );
104 req->access = DesiredAccess;
105 req->attributes = ObjectAttributes ? ObjectAttributes->Attributes : 0;
106 req->primary = (TokenType == TokenPrimary);
107 req->impersonation_level = ImpersonationLevel;
108 status = wine_server_call( req );
109 if (!status) *NewToken = wine_server_ptr_handle( reply->new_handle );
111 SERVER_END_REQ;
113 return status;
116 /******************************************************************************
117 * NtOpenProcessToken [NTDLL.@]
118 * ZwOpenProcessToken [NTDLL.@]
120 NTSTATUS WINAPI NtOpenProcessToken(
121 HANDLE ProcessHandle,
122 DWORD DesiredAccess,
123 HANDLE *TokenHandle)
125 return NtOpenProcessTokenEx( ProcessHandle, DesiredAccess, 0, TokenHandle );
128 /******************************************************************************
129 * NtOpenProcessTokenEx [NTDLL.@]
130 * ZwOpenProcessTokenEx [NTDLL.@]
132 NTSTATUS WINAPI NtOpenProcessTokenEx( HANDLE process, DWORD access, DWORD attributes,
133 HANDLE *handle )
135 NTSTATUS ret;
137 TRACE("(%p,0x%08x,0x%08x,%p)\n", process, access, attributes, handle);
139 SERVER_START_REQ( open_token )
141 req->handle = wine_server_obj_handle( process );
142 req->access = access;
143 req->attributes = attributes;
144 req->flags = 0;
145 ret = wine_server_call( req );
146 if (!ret) *handle = wine_server_ptr_handle( reply->token );
148 SERVER_END_REQ;
149 return ret;
152 /******************************************************************************
153 * NtOpenThreadToken [NTDLL.@]
154 * ZwOpenThreadToken [NTDLL.@]
156 NTSTATUS WINAPI NtOpenThreadToken(
157 HANDLE ThreadHandle,
158 DWORD DesiredAccess,
159 BOOLEAN OpenAsSelf,
160 HANDLE *TokenHandle)
162 return NtOpenThreadTokenEx( ThreadHandle, DesiredAccess, OpenAsSelf, 0, TokenHandle );
165 /******************************************************************************
166 * NtOpenThreadTokenEx [NTDLL.@]
167 * ZwOpenThreadTokenEx [NTDLL.@]
169 NTSTATUS WINAPI NtOpenThreadTokenEx( HANDLE thread, DWORD access, BOOLEAN as_self, DWORD attributes,
170 HANDLE *handle )
172 NTSTATUS ret;
174 TRACE("(%p,0x%08x,%u,0x%08x,%p)\n", thread, access, as_self, attributes, handle );
176 SERVER_START_REQ( open_token )
178 req->handle = wine_server_obj_handle( thread );
179 req->access = access;
180 req->attributes = attributes;
181 req->flags = OPEN_TOKEN_THREAD;
182 if (as_self) req->flags |= OPEN_TOKEN_AS_SELF;
183 ret = wine_server_call( req );
184 if (!ret) *handle = wine_server_ptr_handle( reply->token );
186 SERVER_END_REQ;
188 return ret;
191 /******************************************************************************
192 * NtAdjustPrivilegesToken [NTDLL.@]
193 * ZwAdjustPrivilegesToken [NTDLL.@]
195 * FIXME: parameters unsafe
197 NTSTATUS WINAPI NtAdjustPrivilegesToken(
198 IN HANDLE TokenHandle,
199 IN BOOLEAN DisableAllPrivileges,
200 IN PTOKEN_PRIVILEGES NewState,
201 IN DWORD BufferLength,
202 OUT PTOKEN_PRIVILEGES PreviousState,
203 OUT PDWORD ReturnLength)
205 NTSTATUS ret;
207 TRACE("(%p,0x%08x,%p,0x%08x,%p,%p)\n",
208 TokenHandle, DisableAllPrivileges, NewState, BufferLength, PreviousState, ReturnLength);
210 SERVER_START_REQ( adjust_token_privileges )
212 req->handle = wine_server_obj_handle( TokenHandle );
213 req->disable_all = DisableAllPrivileges;
214 req->get_modified_state = (PreviousState != NULL);
215 if (!DisableAllPrivileges)
217 wine_server_add_data( req, NewState->Privileges,
218 NewState->PrivilegeCount * sizeof(NewState->Privileges[0]) );
220 if (PreviousState && BufferLength >= FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ))
221 wine_server_set_reply( req, PreviousState->Privileges,
222 BufferLength - FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ) );
223 ret = wine_server_call( req );
224 if (PreviousState)
226 if (ReturnLength) *ReturnLength = reply->len + FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges );
227 PreviousState->PrivilegeCount = reply->len / sizeof(LUID_AND_ATTRIBUTES);
230 SERVER_END_REQ;
232 return ret;
235 /******************************************************************************
236 * NtQueryInformationToken [NTDLL.@]
237 * ZwQueryInformationToken [NTDLL.@]
239 * NOTES
240 * Buffer for TokenUser:
241 * 0x00 TOKEN_USER the PSID field points to the SID
242 * 0x08 SID
245 NTSTATUS WINAPI NtQueryInformationToken(
246 HANDLE token,
247 TOKEN_INFORMATION_CLASS tokeninfoclass,
248 PVOID tokeninfo,
249 ULONG tokeninfolength,
250 PULONG retlen )
252 static const ULONG info_len [] =
255 0, /* TokenUser */
256 0, /* TokenGroups */
257 0, /* TokenPrivileges */
258 0, /* TokenOwner */
259 0, /* TokenPrimaryGroup */
260 0, /* TokenDefaultDacl */
261 sizeof(TOKEN_SOURCE), /* TokenSource */
262 sizeof(TOKEN_TYPE), /* TokenType */
263 sizeof(SECURITY_IMPERSONATION_LEVEL), /* TokenImpersonationLevel */
264 sizeof(TOKEN_STATISTICS), /* TokenStatistics */
265 0, /* TokenRestrictedSids */
266 sizeof(DWORD), /* TokenSessionId */
267 0, /* TokenGroupsAndPrivileges */
268 0, /* TokenSessionReference */
269 0, /* TokenSandBoxInert */
270 0, /* TokenAuditPolicy */
271 0, /* TokenOrigin */
272 sizeof(TOKEN_ELEVATION_TYPE), /* TokenElevationType */
273 0, /* TokenLinkedToken */
274 sizeof(TOKEN_ELEVATION), /* TokenElevation */
275 0, /* TokenHasRestrictions */
276 0, /* TokenAccessInformation */
277 0, /* TokenVirtualizationAllowed */
278 0, /* TokenVirtualizationEnabled */
279 sizeof(TOKEN_MANDATORY_LABEL) + sizeof(SID), /* TokenIntegrityLevel [sizeof(SID) includes one SubAuthority] */
280 0, /* TokenUIAccess */
281 0, /* TokenMandatoryPolicy */
282 0, /* TokenLogonSid */
283 sizeof(DWORD), /* TokenIsAppContainer */
284 0, /* TokenCapabilities */
285 sizeof(TOKEN_APPCONTAINER_INFORMATION) + sizeof(SID), /* TokenAppContainerSid */
286 0, /* TokenAppContainerNumber */
287 0, /* TokenUserClaimAttributes*/
288 0, /* TokenDeviceClaimAttributes */
289 0, /* TokenRestrictedUserClaimAttributes */
290 0, /* TokenRestrictedDeviceClaimAttributes */
291 0, /* TokenDeviceGroups */
292 0, /* TokenRestrictedDeviceGroups */
293 0, /* TokenSecurityAttributes */
294 0, /* TokenIsRestricted */
295 0 /* TokenProcessTrustLevel */
298 ULONG len = 0;
299 NTSTATUS status = STATUS_SUCCESS;
301 TRACE("(%p,%d,%p,%d,%p)\n",
302 token,tokeninfoclass,tokeninfo,tokeninfolength,retlen);
304 if (tokeninfoclass < MaxTokenInfoClass)
305 len = info_len[tokeninfoclass];
307 if (retlen) *retlen = len;
309 if (tokeninfolength < len)
310 return STATUS_BUFFER_TOO_SMALL;
312 switch (tokeninfoclass)
314 case TokenUser:
315 SERVER_START_REQ( get_token_sid )
317 TOKEN_USER * tuser = tokeninfo;
318 PSID sid = tuser + 1;
319 DWORD sid_len = tokeninfolength < sizeof(TOKEN_USER) ? 0 : tokeninfolength - sizeof(TOKEN_USER);
321 req->handle = wine_server_obj_handle( token );
322 req->which_sid = tokeninfoclass;
323 wine_server_set_reply( req, sid, sid_len );
324 status = wine_server_call( req );
325 if (retlen) *retlen = reply->sid_len + sizeof(TOKEN_USER);
326 if (status == STATUS_SUCCESS)
328 tuser->User.Sid = sid;
329 tuser->User.Attributes = 0;
332 SERVER_END_REQ;
333 break;
334 case TokenGroups:
336 void *buffer;
338 /* reply buffer is always shorter than output one */
339 buffer = tokeninfolength ? RtlAllocateHeap(GetProcessHeap(), 0, tokeninfolength) : NULL;
341 SERVER_START_REQ( get_token_groups )
343 TOKEN_GROUPS *groups = tokeninfo;
345 req->handle = wine_server_obj_handle( token );
346 wine_server_set_reply( req, buffer, tokeninfolength );
347 status = wine_server_call( req );
348 if (status == STATUS_BUFFER_TOO_SMALL)
350 if (retlen) *retlen = reply->user_len;
352 else if (status == STATUS_SUCCESS)
354 struct token_groups *tg = buffer;
355 unsigned int *attr = (unsigned int *)(tg + 1);
356 ULONG i;
357 const int non_sid_portion = (sizeof(struct token_groups) + tg->count * sizeof(unsigned int));
358 SID *sids = (SID *)((char *)tokeninfo + FIELD_OFFSET( TOKEN_GROUPS, Groups[tg->count] ));
360 if (retlen) *retlen = reply->user_len;
362 groups->GroupCount = tg->count;
363 memcpy( sids, (char *)buffer + non_sid_portion,
364 reply->user_len - FIELD_OFFSET( TOKEN_GROUPS, Groups[tg->count] ));
366 for (i = 0; i < tg->count; i++)
368 groups->Groups[i].Attributes = attr[i];
369 groups->Groups[i].Sid = sids;
370 sids = (SID *)((char *)sids + RtlLengthSid(sids));
373 else if (retlen) *retlen = 0;
375 SERVER_END_REQ;
377 RtlFreeHeap(GetProcessHeap(), 0, buffer);
378 break;
380 case TokenPrimaryGroup:
381 SERVER_START_REQ( get_token_sid )
383 TOKEN_PRIMARY_GROUP *tgroup = tokeninfo;
384 PSID sid = tgroup + 1;
385 DWORD sid_len = tokeninfolength < sizeof(TOKEN_PRIMARY_GROUP) ? 0 : tokeninfolength - sizeof(TOKEN_PRIMARY_GROUP);
387 req->handle = wine_server_obj_handle( token );
388 req->which_sid = tokeninfoclass;
389 wine_server_set_reply( req, sid, sid_len );
390 status = wine_server_call( req );
391 if (retlen) *retlen = reply->sid_len + sizeof(TOKEN_PRIMARY_GROUP);
392 if (status == STATUS_SUCCESS)
393 tgroup->PrimaryGroup = sid;
395 SERVER_END_REQ;
396 break;
397 case TokenPrivileges:
398 SERVER_START_REQ( get_token_privileges )
400 TOKEN_PRIVILEGES *tpriv = tokeninfo;
401 req->handle = wine_server_obj_handle( token );
402 if (tpriv && tokeninfolength > FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ))
403 wine_server_set_reply( req, tpriv->Privileges, tokeninfolength - FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ) );
404 status = wine_server_call( req );
405 if (retlen) *retlen = FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ) + reply->len;
406 if (tpriv) tpriv->PrivilegeCount = reply->len / sizeof(LUID_AND_ATTRIBUTES);
408 SERVER_END_REQ;
409 break;
410 case TokenOwner:
411 SERVER_START_REQ( get_token_sid )
413 TOKEN_OWNER *towner = tokeninfo;
414 PSID sid = towner + 1;
415 DWORD sid_len = tokeninfolength < sizeof(TOKEN_OWNER) ? 0 : tokeninfolength - sizeof(TOKEN_OWNER);
417 req->handle = wine_server_obj_handle( token );
418 req->which_sid = tokeninfoclass;
419 wine_server_set_reply( req, sid, sid_len );
420 status = wine_server_call( req );
421 if (retlen) *retlen = reply->sid_len + sizeof(TOKEN_OWNER);
422 if (status == STATUS_SUCCESS)
423 towner->Owner = sid;
425 SERVER_END_REQ;
426 break;
427 case TokenImpersonationLevel:
428 SERVER_START_REQ( get_token_impersonation_level )
430 SECURITY_IMPERSONATION_LEVEL *impersonation_level = tokeninfo;
431 req->handle = wine_server_obj_handle( token );
432 status = wine_server_call( req );
433 if (status == STATUS_SUCCESS)
434 *impersonation_level = reply->impersonation_level;
436 SERVER_END_REQ;
437 break;
438 case TokenStatistics:
439 SERVER_START_REQ( get_token_statistics )
441 TOKEN_STATISTICS *statistics = tokeninfo;
442 req->handle = wine_server_obj_handle( token );
443 status = wine_server_call( req );
444 if (status == STATUS_SUCCESS)
446 statistics->TokenId.LowPart = reply->token_id.low_part;
447 statistics->TokenId.HighPart = reply->token_id.high_part;
448 statistics->AuthenticationId.LowPart = 0; /* FIXME */
449 statistics->AuthenticationId.HighPart = 0; /* FIXME */
450 statistics->ExpirationTime.u.HighPart = 0x7fffffff;
451 statistics->ExpirationTime.u.LowPart = 0xffffffff;
452 statistics->TokenType = reply->primary ? TokenPrimary : TokenImpersonation;
453 statistics->ImpersonationLevel = reply->impersonation_level;
455 /* kernel information not relevant to us */
456 statistics->DynamicCharged = 0;
457 statistics->DynamicAvailable = 0;
459 statistics->GroupCount = reply->group_count;
460 statistics->PrivilegeCount = reply->privilege_count;
461 statistics->ModifiedId.LowPart = reply->modified_id.low_part;
462 statistics->ModifiedId.HighPart = reply->modified_id.high_part;
465 SERVER_END_REQ;
466 break;
467 case TokenType:
468 SERVER_START_REQ( get_token_statistics )
470 TOKEN_TYPE *token_type = tokeninfo;
471 req->handle = wine_server_obj_handle( token );
472 status = wine_server_call( req );
473 if (status == STATUS_SUCCESS)
474 *token_type = reply->primary ? TokenPrimary : TokenImpersonation;
476 SERVER_END_REQ;
477 break;
478 case TokenDefaultDacl:
479 SERVER_START_REQ( get_token_default_dacl )
481 TOKEN_DEFAULT_DACL *default_dacl = tokeninfo;
482 ACL *acl = (ACL *)(default_dacl + 1);
483 DWORD acl_len;
485 if (tokeninfolength < sizeof(TOKEN_DEFAULT_DACL)) acl_len = 0;
486 else acl_len = tokeninfolength - sizeof(TOKEN_DEFAULT_DACL);
488 req->handle = wine_server_obj_handle( token );
489 wine_server_set_reply( req, acl, acl_len );
490 status = wine_server_call( req );
492 if (retlen) *retlen = reply->acl_len + sizeof(TOKEN_DEFAULT_DACL);
493 if (status == STATUS_SUCCESS)
495 if (reply->acl_len)
496 default_dacl->DefaultDacl = acl;
497 else
498 default_dacl->DefaultDacl = NULL;
501 SERVER_END_REQ;
502 break;
503 case TokenElevationType:
505 TOKEN_ELEVATION_TYPE *elevation_type = tokeninfo;
506 FIXME("QueryInformationToken( ..., TokenElevationType, ...) semi-stub\n");
507 *elevation_type = TokenElevationTypeFull;
509 break;
510 case TokenElevation:
512 TOKEN_ELEVATION *elevation = tokeninfo;
513 FIXME("QueryInformationToken( ..., TokenElevation, ...) semi-stub\n");
514 elevation->TokenIsElevated = TRUE;
516 break;
517 case TokenSessionId:
519 *((DWORD*)tokeninfo) = 0;
520 FIXME("QueryInformationToken( ..., TokenSessionId, ...) semi-stub\n");
522 break;
523 case TokenIntegrityLevel:
525 /* report always "S-1-16-12288" (high mandatory level) for now */
526 static const SID high_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
527 {SECURITY_MANDATORY_HIGH_RID}};
529 TOKEN_MANDATORY_LABEL *tml = tokeninfo;
530 PSID psid = tml + 1;
532 tml->Label.Sid = psid;
533 tml->Label.Attributes = SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED;
534 memcpy(psid, &high_level, sizeof(SID));
536 break;
537 case TokenAppContainerSid:
539 TOKEN_APPCONTAINER_INFORMATION *container = tokeninfo;
540 FIXME("QueryInformationToken( ..., TokenAppContainerSid, ...) semi-stub\n");
541 container->TokenAppContainer = NULL;
543 break;
544 case TokenIsAppContainer:
546 TRACE("TokenIsAppContainer semi-stub\n");
547 *(DWORD*)tokeninfo = 0;
548 break;
550 default:
552 ERR("Unhandled Token Information class %d!\n", tokeninfoclass);
553 return STATUS_NOT_IMPLEMENTED;
556 return status;
559 /******************************************************************************
560 * NtSetInformationToken [NTDLL.@]
561 * ZwSetInformationToken [NTDLL.@]
563 NTSTATUS WINAPI NtSetInformationToken(
564 HANDLE TokenHandle,
565 TOKEN_INFORMATION_CLASS TokenInformationClass,
566 PVOID TokenInformation,
567 ULONG TokenInformationLength)
569 NTSTATUS ret = STATUS_NOT_IMPLEMENTED;
571 TRACE("%p %d %p %u\n", TokenHandle, TokenInformationClass,
572 TokenInformation, TokenInformationLength);
574 switch (TokenInformationClass)
576 case TokenDefaultDacl:
577 if (TokenInformationLength < sizeof(TOKEN_DEFAULT_DACL))
579 ret = STATUS_INFO_LENGTH_MISMATCH;
580 break;
582 if (!TokenInformation)
584 ret = STATUS_ACCESS_VIOLATION;
585 break;
587 SERVER_START_REQ( set_token_default_dacl )
589 ACL *acl = ((TOKEN_DEFAULT_DACL *)TokenInformation)->DefaultDacl;
590 WORD size;
592 if (acl) size = acl->AclSize;
593 else size = 0;
595 req->handle = wine_server_obj_handle( TokenHandle );
596 wine_server_add_data( req, acl, size );
597 ret = wine_server_call( req );
599 SERVER_END_REQ;
600 break;
601 default:
602 FIXME("unimplemented class %u\n", TokenInformationClass);
603 break;
606 return ret;
609 /******************************************************************************
610 * NtAdjustGroupsToken [NTDLL.@]
611 * ZwAdjustGroupsToken [NTDLL.@]
613 NTSTATUS WINAPI NtAdjustGroupsToken(
614 HANDLE TokenHandle,
615 BOOLEAN ResetToDefault,
616 PTOKEN_GROUPS NewState,
617 ULONG BufferLength,
618 PTOKEN_GROUPS PreviousState,
619 PULONG ReturnLength)
621 FIXME("%p %d %p %u %p %p\n", TokenHandle, ResetToDefault,
622 NewState, BufferLength, PreviousState, ReturnLength);
623 return STATUS_NOT_IMPLEMENTED;
626 /******************************************************************************
627 * NtPrivilegeCheck [NTDLL.@]
628 * ZwPrivilegeCheck [NTDLL.@]
630 NTSTATUS WINAPI NtPrivilegeCheck(
631 HANDLE ClientToken,
632 PPRIVILEGE_SET RequiredPrivileges,
633 PBOOLEAN Result)
635 NTSTATUS status;
636 SERVER_START_REQ( check_token_privileges )
638 req->handle = wine_server_obj_handle( ClientToken );
639 req->all_required = (RequiredPrivileges->Control & PRIVILEGE_SET_ALL_NECESSARY) != 0;
640 wine_server_add_data( req, RequiredPrivileges->Privilege,
641 RequiredPrivileges->PrivilegeCount * sizeof(RequiredPrivileges->Privilege[0]) );
642 wine_server_set_reply( req, RequiredPrivileges->Privilege,
643 RequiredPrivileges->PrivilegeCount * sizeof(RequiredPrivileges->Privilege[0]) );
645 status = wine_server_call( req );
647 if (status == STATUS_SUCCESS)
648 *Result = reply->has_privileges != 0;
650 SERVER_END_REQ;
651 return status;
655 * ports
658 /******************************************************************************
659 * NtCreatePort [NTDLL.@]
660 * ZwCreatePort [NTDLL.@]
662 NTSTATUS WINAPI NtCreatePort(PHANDLE PortHandle,POBJECT_ATTRIBUTES ObjectAttributes,
663 ULONG MaxConnectInfoLength,ULONG MaxDataLength,PULONG reserved)
665 FIXME("(%p,%p,%u,%u,%p),stub!\n",PortHandle,ObjectAttributes,
666 MaxConnectInfoLength,MaxDataLength,reserved);
667 return STATUS_NOT_IMPLEMENTED;
670 /******************************************************************************
671 * NtConnectPort [NTDLL.@]
672 * ZwConnectPort [NTDLL.@]
674 NTSTATUS WINAPI NtConnectPort(
675 PHANDLE PortHandle,
676 PUNICODE_STRING PortName,
677 PSECURITY_QUALITY_OF_SERVICE SecurityQos,
678 PLPC_SECTION_WRITE WriteSection,
679 PLPC_SECTION_READ ReadSection,
680 PULONG MaximumMessageLength,
681 PVOID ConnectInfo,
682 PULONG pConnectInfoLength)
684 FIXME("(%p,%s,%p,%p,%p,%p,%p,%p),stub!\n",
685 PortHandle,debugstr_w(PortName->Buffer),SecurityQos,
686 WriteSection,ReadSection,MaximumMessageLength,ConnectInfo,
687 pConnectInfoLength);
688 if (ConnectInfo && pConnectInfoLength)
689 TRACE("\tMessage = %s\n",debugstr_an(ConnectInfo,*pConnectInfoLength));
690 return STATUS_NOT_IMPLEMENTED;
693 /******************************************************************************
694 * NtSecureConnectPort (NTDLL.@)
695 * ZwSecureConnectPort (NTDLL.@)
697 NTSTATUS WINAPI NtSecureConnectPort(
698 PHANDLE PortHandle,
699 PUNICODE_STRING PortName,
700 PSECURITY_QUALITY_OF_SERVICE SecurityQos,
701 PLPC_SECTION_WRITE WriteSection,
702 PSID pSid,
703 PLPC_SECTION_READ ReadSection,
704 PULONG MaximumMessageLength,
705 PVOID ConnectInfo,
706 PULONG pConnectInfoLength)
708 FIXME("(%p,%s,%p,%p,%p,%p,%p,%p,%p),stub!\n",
709 PortHandle,debugstr_w(PortName->Buffer),SecurityQos,
710 WriteSection,pSid,ReadSection,MaximumMessageLength,ConnectInfo,
711 pConnectInfoLength);
712 return STATUS_NOT_IMPLEMENTED;
715 /******************************************************************************
716 * NtListenPort [NTDLL.@]
717 * ZwListenPort [NTDLL.@]
719 NTSTATUS WINAPI NtListenPort(HANDLE PortHandle,PLPC_MESSAGE pLpcMessage)
721 FIXME("(%p,%p),stub!\n",PortHandle,pLpcMessage);
722 return STATUS_NOT_IMPLEMENTED;
725 /******************************************************************************
726 * NtAcceptConnectPort [NTDLL.@]
727 * ZwAcceptConnectPort [NTDLL.@]
729 NTSTATUS WINAPI NtAcceptConnectPort(
730 PHANDLE PortHandle,
731 ULONG PortIdentifier,
732 PLPC_MESSAGE pLpcMessage,
733 BOOLEAN Accept,
734 PLPC_SECTION_WRITE WriteSection,
735 PLPC_SECTION_READ ReadSection)
737 FIXME("(%p,%u,%p,%d,%p,%p),stub!\n",
738 PortHandle,PortIdentifier,pLpcMessage,Accept,WriteSection,ReadSection);
739 return STATUS_NOT_IMPLEMENTED;
742 /******************************************************************************
743 * NtCompleteConnectPort [NTDLL.@]
744 * ZwCompleteConnectPort [NTDLL.@]
746 NTSTATUS WINAPI NtCompleteConnectPort(HANDLE PortHandle)
748 FIXME("(%p),stub!\n",PortHandle);
749 return STATUS_NOT_IMPLEMENTED;
752 /******************************************************************************
753 * NtRegisterThreadTerminatePort [NTDLL.@]
754 * ZwRegisterThreadTerminatePort [NTDLL.@]
756 NTSTATUS WINAPI NtRegisterThreadTerminatePort(HANDLE PortHandle)
758 FIXME("(%p),stub!\n",PortHandle);
759 return STATUS_NOT_IMPLEMENTED;
762 /******************************************************************************
763 * NtRequestWaitReplyPort [NTDLL.@]
764 * ZwRequestWaitReplyPort [NTDLL.@]
766 NTSTATUS WINAPI NtRequestWaitReplyPort(
767 HANDLE PortHandle,
768 PLPC_MESSAGE pLpcMessageIn,
769 PLPC_MESSAGE pLpcMessageOut)
771 FIXME("(%p,%p,%p),stub!\n",PortHandle,pLpcMessageIn,pLpcMessageOut);
772 if(pLpcMessageIn)
774 TRACE("Message to send:\n");
775 TRACE("\tDataSize = %u\n",pLpcMessageIn->DataSize);
776 TRACE("\tMessageSize = %u\n",pLpcMessageIn->MessageSize);
777 TRACE("\tMessageType = %u\n",pLpcMessageIn->MessageType);
778 TRACE("\tVirtualRangesOffset = %u\n",pLpcMessageIn->VirtualRangesOffset);
779 TRACE("\tClientId.UniqueProcess = %p\n",pLpcMessageIn->ClientId.UniqueProcess);
780 TRACE("\tClientId.UniqueThread = %p\n",pLpcMessageIn->ClientId.UniqueThread);
781 TRACE("\tMessageId = %lu\n",pLpcMessageIn->MessageId);
782 TRACE("\tSectionSize = %lu\n",pLpcMessageIn->SectionSize);
783 TRACE("\tData = %s\n",
784 debugstr_an((const char*)pLpcMessageIn->Data,pLpcMessageIn->DataSize));
786 return STATUS_NOT_IMPLEMENTED;
789 /******************************************************************************
790 * NtReplyWaitReceivePort [NTDLL.@]
791 * ZwReplyWaitReceivePort [NTDLL.@]
793 NTSTATUS WINAPI NtReplyWaitReceivePort(
794 HANDLE PortHandle,
795 PULONG PortIdentifier,
796 PLPC_MESSAGE ReplyMessage,
797 PLPC_MESSAGE Message)
799 FIXME("(%p,%p,%p,%p),stub!\n",PortHandle,PortIdentifier,ReplyMessage,Message);
800 return STATUS_NOT_IMPLEMENTED;
804 * Misc
807 /******************************************************************************
808 * NtSetIntervalProfile [NTDLL.@]
809 * ZwSetIntervalProfile [NTDLL.@]
811 NTSTATUS WINAPI NtSetIntervalProfile(
812 ULONG Interval,
813 KPROFILE_SOURCE Source)
815 FIXME("%u,%d\n", Interval, Source);
816 return STATUS_SUCCESS;
819 static SYSTEM_CPU_INFORMATION cached_sci;
821 /*******************************************************************************
822 * Architecture specific feature detection for CPUs
824 * This a set of mutually exclusive #if define()s each providing its own get_cpuinfo() to be called
825 * from fill_cpu_info();
827 #if defined(__i386__) || defined(__x86_64__)
829 #define AUTH 0x68747541 /* "Auth" */
830 #define ENTI 0x69746e65 /* "enti" */
831 #define CAMD 0x444d4163 /* "cAMD" */
833 #define GENU 0x756e6547 /* "Genu" */
834 #define INEI 0x49656e69 /* "ineI" */
835 #define NTEL 0x6c65746e /* "ntel" */
837 /* Calls cpuid with an eax of 'ax' and returns the 16 bytes in *p
838 * We are compiled with -fPIC, so we can't clobber ebx.
840 static inline void do_cpuid(unsigned int ax, unsigned int *p)
842 #ifdef __i386__
843 __asm__("pushl %%ebx\n\t"
844 "cpuid\n\t"
845 "movl %%ebx, %%esi\n\t"
846 "popl %%ebx"
847 : "=a" (p[0]), "=S" (p[1]), "=c" (p[2]), "=d" (p[3])
848 : "0" (ax));
849 #elif defined(__x86_64__)
850 __asm__("push %%rbx\n\t"
851 "cpuid\n\t"
852 "movq %%rbx, %%rsi\n\t"
853 "pop %%rbx"
854 : "=a" (p[0]), "=S" (p[1]), "=c" (p[2]), "=d" (p[3])
855 : "0" (ax));
856 #endif
859 /* From xf86info havecpuid.c 1.11 */
860 static inline BOOL have_cpuid(void)
862 #ifdef __i386__
863 unsigned int f1, f2;
864 __asm__("pushfl\n\t"
865 "pushfl\n\t"
866 "popl %0\n\t"
867 "movl %0,%1\n\t"
868 "xorl %2,%0\n\t"
869 "pushl %0\n\t"
870 "popfl\n\t"
871 "pushfl\n\t"
872 "popl %0\n\t"
873 "popfl"
874 : "=&r" (f1), "=&r" (f2)
875 : "ir" (0x00200000));
876 return ((f1^f2) & 0x00200000) != 0;
877 #elif defined(__x86_64__)
878 return TRUE;
879 #else
880 return FALSE;
881 #endif
884 /* Detect if a SSE2 processor is capable of Denormals Are Zero (DAZ) mode.
886 * This function assumes you have already checked for SSE2/FXSAVE support. */
887 static inline BOOL have_sse_daz_mode(void)
889 #ifdef __i386__
890 typedef struct DECLSPEC_ALIGN(16) _M128A {
891 ULONGLONG Low;
892 LONGLONG High;
893 } M128A;
895 typedef struct _XMM_SAVE_AREA32 {
896 WORD ControlWord;
897 WORD StatusWord;
898 BYTE TagWord;
899 BYTE Reserved1;
900 WORD ErrorOpcode;
901 DWORD ErrorOffset;
902 WORD ErrorSelector;
903 WORD Reserved2;
904 DWORD DataOffset;
905 WORD DataSelector;
906 WORD Reserved3;
907 DWORD MxCsr;
908 DWORD MxCsr_Mask;
909 M128A FloatRegisters[8];
910 M128A XmmRegisters[16];
911 BYTE Reserved4[96];
912 } XMM_SAVE_AREA32;
914 /* Intel says we need a zeroed 16-byte aligned buffer */
915 char buffer[512 + 16];
916 XMM_SAVE_AREA32 *state = (XMM_SAVE_AREA32 *)(((ULONG_PTR)buffer + 15) & ~15);
917 memset(buffer, 0, sizeof(buffer));
919 __asm__ __volatile__( "fxsave %0" : "=m" (*state) : "m" (*state) );
921 return (state->MxCsr_Mask & (1 << 6)) >> 6;
922 #else /* all x86_64 processors include SSE2 with DAZ mode */
923 return TRUE;
924 #endif
927 static inline void get_cpuinfo(SYSTEM_CPU_INFORMATION* info)
929 unsigned int regs[4], regs2[4];
931 #if defined(__i386__)
932 info->Architecture = PROCESSOR_ARCHITECTURE_INTEL;
933 #elif defined(__x86_64__)
934 info->Architecture = PROCESSOR_ARCHITECTURE_AMD64;
935 #endif
937 /* We're at least a 386 */
938 info->FeatureSet = CPU_FEATURE_VME | CPU_FEATURE_X86 | CPU_FEATURE_PGE;
939 info->Level = 3;
941 if (!have_cpuid()) return;
943 do_cpuid(0x00000000, regs); /* get standard cpuid level and vendor name */
944 if (regs[0]>=0x00000001) /* Check for supported cpuid version */
946 do_cpuid(0x00000001, regs2); /* get cpu features */
948 if(regs2[3] & (1 << 3 )) info->FeatureSet |= CPU_FEATURE_PSE;
949 if(regs2[3] & (1 << 4 )) info->FeatureSet |= CPU_FEATURE_TSC;
950 if(regs2[3] & (1 << 8 )) info->FeatureSet |= CPU_FEATURE_CX8;
951 if(regs2[3] & (1 << 11)) info->FeatureSet |= CPU_FEATURE_SEP;
952 if(regs2[3] & (1 << 12)) info->FeatureSet |= CPU_FEATURE_MTRR;
953 if(regs2[3] & (1 << 15)) info->FeatureSet |= CPU_FEATURE_CMOV;
954 if(regs2[3] & (1 << 16)) info->FeatureSet |= CPU_FEATURE_PAT;
955 if(regs2[3] & (1 << 23)) info->FeatureSet |= CPU_FEATURE_MMX;
956 if(regs2[3] & (1 << 24)) info->FeatureSet |= CPU_FEATURE_FXSR;
957 if(regs2[3] & (1 << 25)) info->FeatureSet |= CPU_FEATURE_SSE;
958 if(regs2[3] & (1 << 26)) info->FeatureSet |= CPU_FEATURE_SSE2;
960 user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED] = !(regs2[3] & 1);
961 user_shared_data->ProcessorFeatures[PF_RDTSC_INSTRUCTION_AVAILABLE] = (regs2[3] >> 4) & 1;
962 user_shared_data->ProcessorFeatures[PF_PAE_ENABLED] = (regs2[3] >> 6) & 1;
963 user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE_DOUBLE] = (regs2[3] >> 8) & 1;
964 user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE] = (regs2[3] >> 23) & 1;
965 user_shared_data->ProcessorFeatures[PF_XMMI_INSTRUCTIONS_AVAILABLE] = (regs2[3] >> 25) & 1;
966 user_shared_data->ProcessorFeatures[PF_XMMI64_INSTRUCTIONS_AVAILABLE] = (regs2[3] >> 26) & 1;
967 user_shared_data->ProcessorFeatures[PF_SSE3_INSTRUCTIONS_AVAILABLE] = regs2[2] & 1;
968 user_shared_data->ProcessorFeatures[PF_XSAVE_ENABLED] = (regs2[2] >> 27) & 1;
969 user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE128] = (regs2[2] >> 13) & 1;
971 if((regs2[3] & (1 << 26)) && (regs2[3] & (1 << 24))) /* has SSE2 and FXSAVE/FXRSTOR */
972 user_shared_data->ProcessorFeatures[PF_SSE_DAZ_MODE_AVAILABLE] = have_sse_daz_mode();
974 if (regs[1] == AUTH && regs[3] == ENTI && regs[2] == CAMD)
976 info->Level = (regs2[0] >> 8) & 0xf; /* family */
977 if (info->Level == 0xf) /* AMD says to add the extended family to the family if family is 0xf */
978 info->Level += (regs2[0] >> 20) & 0xff;
980 /* repack model and stepping to make a "revision" */
981 info->Revision = ((regs2[0] >> 16) & 0xf) << 12; /* extended model */
982 info->Revision |= ((regs2[0] >> 4 ) & 0xf) << 8; /* model */
983 info->Revision |= regs2[0] & 0xf; /* stepping */
985 do_cpuid(0x80000000, regs); /* get vendor cpuid level */
986 if (regs[0] >= 0x80000001)
988 do_cpuid(0x80000001, regs2); /* get vendor features */
989 user_shared_data->ProcessorFeatures[PF_VIRT_FIRMWARE_ENABLED] = (regs2[2] >> 2) & 1;
990 user_shared_data->ProcessorFeatures[PF_NX_ENABLED] = (regs2[3] >> 20) & 1;
991 user_shared_data->ProcessorFeatures[PF_3DNOW_INSTRUCTIONS_AVAILABLE] = (regs2[3] >> 31) & 1;
992 if (regs2[3] >> 31) info->FeatureSet |= CPU_FEATURE_3DNOW;
995 else if (regs[1] == GENU && regs[3] == INEI && regs[2] == NTEL)
997 info->Level = ((regs2[0] >> 8) & 0xf) + ((regs2[0] >> 20) & 0xff); /* family + extended family */
998 if(info->Level == 15) info->Level = 6;
1000 /* repack model and stepping to make a "revision" */
1001 info->Revision = ((regs2[0] >> 16) & 0xf) << 12; /* extended model */
1002 info->Revision |= ((regs2[0] >> 4 ) & 0xf) << 8; /* model */
1003 info->Revision |= regs2[0] & 0xf; /* stepping */
1005 if(regs2[3] & (1 << 21)) info->FeatureSet |= CPU_FEATURE_DS;
1006 user_shared_data->ProcessorFeatures[PF_VIRT_FIRMWARE_ENABLED] = (regs2[2] >> 5) & 1;
1008 do_cpuid(0x80000000, regs); /* get vendor cpuid level */
1009 if (regs[0] >= 0x80000001)
1011 do_cpuid(0x80000001, regs2); /* get vendor features */
1012 user_shared_data->ProcessorFeatures[PF_NX_ENABLED] = (regs2[3] >> 20) & 1;
1015 else
1017 info->Level = (regs2[0] >> 8) & 0xf; /* family */
1019 /* repack model and stepping to make a "revision" */
1020 info->Revision = ((regs2[0] >> 4 ) & 0xf) << 8; /* model */
1021 info->Revision |= regs2[0] & 0xf; /* stepping */
1026 #elif defined(__powerpc__) || defined(__ppc__)
1028 static inline void get_cpuinfo(SYSTEM_CPU_INFORMATION* info)
1030 #ifdef __APPLE__
1031 size_t valSize;
1032 int value;
1034 valSize = sizeof(value);
1035 if (sysctlbyname("hw.optional.floatingpoint", &value, &valSize, NULL, 0) == 0)
1036 user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED] = !value;
1038 valSize = sizeof(value);
1039 if (sysctlbyname("hw.cpusubtype", &value, &valSize, NULL, 0) == 0)
1041 switch (value)
1043 case CPU_SUBTYPE_POWERPC_601:
1044 case CPU_SUBTYPE_POWERPC_602: info->Level = 1; break;
1045 case CPU_SUBTYPE_POWERPC_603: info->Level = 3; break;
1046 case CPU_SUBTYPE_POWERPC_603e:
1047 case CPU_SUBTYPE_POWERPC_603ev: info->Level = 6; break;
1048 case CPU_SUBTYPE_POWERPC_604: info->Level = 4; break;
1049 case CPU_SUBTYPE_POWERPC_604e: info->Level = 9; break;
1050 case CPU_SUBTYPE_POWERPC_620: info->Level = 20; break;
1051 case CPU_SUBTYPE_POWERPC_750: /* G3/G4 derive from 603 so ... */
1052 case CPU_SUBTYPE_POWERPC_7400:
1053 case CPU_SUBTYPE_POWERPC_7450: info->Level = 6; break;
1054 case CPU_SUBTYPE_POWERPC_970: info->Level = 9;
1055 /* :o) user_shared_data->ProcessorFeatures[PF_ALTIVEC_INSTRUCTIONS_AVAILABLE] ;-) */
1056 break;
1057 default: break;
1060 #else
1061 FIXME("CPU Feature detection not implemented.\n");
1062 #endif
1063 info->Architecture = PROCESSOR_ARCHITECTURE_PPC;
1066 #elif defined(__arm__)
1068 static inline void get_cpuinfo(SYSTEM_CPU_INFORMATION* info)
1070 #ifdef linux
1071 char line[512];
1072 char *s, *value;
1073 FILE *f = fopen("/proc/cpuinfo", "r");
1074 if (f)
1076 while (fgets(line, sizeof(line), f) != NULL)
1078 /* NOTE: the ':' is the only character we can rely on */
1079 if (!(value = strchr(line,':')))
1080 continue;
1081 /* terminate the valuename */
1082 s = value - 1;
1083 while ((s >= line) && isspace(*s)) s--;
1084 *(s + 1) = '\0';
1085 /* and strip leading spaces from value */
1086 value += 1;
1087 while (isspace(*value)) value++;
1088 if ((s = strchr(value,'\n')))
1089 *s='\0';
1090 if (!strcasecmp(line, "CPU architecture"))
1092 if (isdigit(value[0]))
1093 info->Level = atoi(value);
1094 continue;
1096 if (!strcasecmp(line, "CPU revision"))
1098 if (isdigit(value[0]))
1099 info->Revision = atoi(value);
1100 continue;
1102 if (!strcasecmp(line, "features"))
1104 if (strstr(value, "vfpv3"))
1105 user_shared_data->ProcessorFeatures[PF_ARM_VFP_32_REGISTERS_AVAILABLE] = TRUE;
1106 if (strstr(value, "neon"))
1107 user_shared_data->ProcessorFeatures[PF_ARM_NEON_INSTRUCTIONS_AVAILABLE] = TRUE;
1108 continue;
1111 fclose(f);
1113 #elif defined(__FreeBSD__)
1114 size_t valsize;
1115 char buf[8];
1116 int value;
1118 valsize = sizeof(buf);
1119 if (!sysctlbyname("hw.machine_arch", &buf, &valsize, NULL, 0) &&
1120 sscanf(buf, "armv%i", &value) == 1)
1121 info->Level = value;
1123 valsize = sizeof(value);
1124 if (!sysctlbyname("hw.floatingpoint", &value, &valsize, NULL, 0))
1125 user_shared_data->ProcessorFeatures[PF_ARM_VFP_32_REGISTERS_AVAILABLE] = value;
1126 #else
1127 FIXME("CPU Feature detection not implemented.\n");
1128 #endif
1129 if (info->Level >= 8)
1130 user_shared_data->ProcessorFeatures[PF_ARM_V8_INSTRUCTIONS_AVAILABLE] = TRUE;
1131 info->Architecture = PROCESSOR_ARCHITECTURE_ARM;
1134 #elif defined(__aarch64__)
1136 static inline void get_cpuinfo(SYSTEM_CPU_INFORMATION* info)
1138 #ifdef linux
1139 char line[512];
1140 char *s, *value;
1141 FILE *f = fopen("/proc/cpuinfo", "r");
1142 if (f)
1144 while (fgets(line, sizeof(line), f) != NULL)
1146 /* NOTE: the ':' is the only character we can rely on */
1147 if (!(value = strchr(line,':')))
1148 continue;
1149 /* terminate the valuename */
1150 s = value - 1;
1151 while ((s >= line) && isspace(*s)) s--;
1152 *(s + 1) = '\0';
1153 /* and strip leading spaces from value */
1154 value += 1;
1155 while (isspace(*value)) value++;
1156 if ((s = strchr(value,'\n')))
1157 *s='\0';
1158 if (!strcasecmp(line, "CPU architecture"))
1160 if (isdigit(value[0]))
1161 info->Level = atoi(value);
1162 continue;
1164 if (!strcasecmp(line, "CPU revision"))
1166 if (isdigit(value[0]))
1167 info->Revision = atoi(value);
1168 continue;
1170 if (!strcasecmp(line, "Features"))
1172 if (strstr(value, "crc32"))
1173 user_shared_data->ProcessorFeatures[PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE] = TRUE;
1174 if (strstr(value, "aes"))
1175 user_shared_data->ProcessorFeatures[PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE] = TRUE;
1176 continue;
1179 fclose(f);
1181 #else
1182 FIXME("CPU Feature detection not implemented.\n");
1183 #endif
1184 info->Level = max(info->Level, 8);
1185 user_shared_data->ProcessorFeatures[PF_ARM_V8_INSTRUCTIONS_AVAILABLE] = TRUE;
1186 info->Architecture = PROCESSOR_ARCHITECTURE_ARM64;
1189 #endif /* End architecture specific feature detection for CPUs */
1191 /******************************************************************
1192 * fill_cpu_info
1194 * inits a couple of places with CPU related information:
1195 * - cached_sci in this file
1196 * - Peb->NumberOfProcessors
1197 * - SharedUserData->ProcessFeatures[] array
1199 void fill_cpu_info(void)
1201 long num;
1203 #ifdef _SC_NPROCESSORS_ONLN
1204 num = sysconf(_SC_NPROCESSORS_ONLN);
1205 if (num < 1)
1207 num = 1;
1208 WARN("Failed to detect the number of processors.\n");
1210 #elif defined(CTL_HW) && defined(HW_NCPU)
1211 int mib[2];
1212 size_t len = sizeof(num);
1213 mib[0] = CTL_HW;
1214 mib[1] = HW_NCPU;
1215 if (sysctl(mib, 2, &num, &len, NULL, 0) != 0)
1217 num = 1;
1218 WARN("Failed to detect the number of processors.\n");
1220 #else
1221 num = 1;
1222 FIXME("Detecting the number of processors is not supported.\n");
1223 #endif
1224 NtCurrentTeb()->Peb->NumberOfProcessors = num;
1226 memset(&cached_sci, 0, sizeof(cached_sci));
1227 get_cpuinfo(&cached_sci);
1229 TRACE("<- CPU arch %d, level %d, rev %d, features 0x%x\n",
1230 cached_sci.Architecture, cached_sci.Level, cached_sci.Revision, cached_sci.FeatureSet);
1233 static BOOL grow_logical_proc_buf(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **pdata,
1234 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **pdataex, DWORD *max_len)
1236 if (pdata)
1238 SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;
1240 *max_len *= 2;
1241 new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *pdata, *max_len*sizeof(*new_data));
1242 if (!new_data)
1243 return FALSE;
1245 *pdata = new_data;
1247 else
1249 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *new_dataex;
1251 *max_len *= 2;
1252 new_dataex = RtlReAllocateHeap(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdataex, *max_len*sizeof(*new_dataex));
1253 if (!new_dataex)
1254 return FALSE;
1256 *pdataex = new_dataex;
1259 return TRUE;
1262 static DWORD log_proc_ex_size_plus(DWORD size)
1264 /* add SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX.Relationship and .Size */
1265 return sizeof(LOGICAL_PROCESSOR_RELATIONSHIP) + sizeof(DWORD) + size;
1268 static inline BOOL logical_proc_info_add_by_id(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **pdata,
1269 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **pdataex, DWORD *len, DWORD *pmax_len,
1270 LOGICAL_PROCESSOR_RELATIONSHIP rel, DWORD id, ULONG_PTR mask)
1272 if (pdata) {
1273 DWORD i;
1275 if(rel == RelationProcessorPackage){
1276 for(i=0; i<*len; i++)
1278 if ((*pdata)[i].Relationship!=rel || (*pdata)[i].u.Reserved[1]!=id)
1279 continue;
1281 (*pdata)[i].ProcessorMask |= mask;
1282 return TRUE;
1284 }else
1285 i = *len;
1287 while(*len == *pmax_len)
1289 if (!grow_logical_proc_buf(pdata, NULL, pmax_len))
1290 return FALSE;
1293 (*pdata)[i].Relationship = rel;
1294 (*pdata)[i].ProcessorMask = mask;
1295 /* TODO: set processor core flags */
1296 (*pdata)[i].u.Reserved[0] = 0;
1297 (*pdata)[i].u.Reserved[1] = id;
1298 *len = i+1;
1299 }else{
1300 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *dataex = *pdataex;
1301 DWORD ofs = 0;
1303 while(ofs < *len)
1305 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + ofs);
1306 if (rel == RelationProcessorPackage && dataex->Relationship == rel && dataex->u.Processor.Reserved[1] == id)
1308 dataex->u.Processor.GroupMask[0].Mask |= mask;
1309 return TRUE;
1311 ofs += dataex->Size;
1314 /* TODO: For now, just one group. If more than 64 processors, then we
1315 * need another group. */
1317 while (ofs + log_proc_ex_size_plus(sizeof(PROCESSOR_RELATIONSHIP)) > *pmax_len)
1319 if (!grow_logical_proc_buf(NULL, pdataex, pmax_len))
1320 return FALSE;
1323 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + ofs);
1325 dataex->Relationship = rel;
1326 dataex->Size = log_proc_ex_size_plus(sizeof(PROCESSOR_RELATIONSHIP));
1327 dataex->u.Processor.Flags = 0; /* TODO */
1328 dataex->u.Processor.EfficiencyClass = 0;
1329 dataex->u.Processor.GroupCount = 1;
1330 dataex->u.Processor.GroupMask[0].Mask = mask;
1331 dataex->u.Processor.GroupMask[0].Group = 0;
1332 /* mark for future lookup */
1333 dataex->u.Processor.Reserved[0] = 0;
1334 dataex->u.Processor.Reserved[1] = id;
1336 *len += dataex->Size;
1339 return TRUE;
1342 static inline BOOL logical_proc_info_add_cache(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **pdata,
1343 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **pdataex, DWORD *len,
1344 DWORD *pmax_len, ULONG_PTR mask, CACHE_DESCRIPTOR *cache)
1346 if (pdata)
1348 DWORD i;
1350 for (i=0; i<*len; i++)
1352 if ((*pdata)[i].Relationship==RelationCache && (*pdata)[i].ProcessorMask==mask
1353 && (*pdata)[i].u.Cache.Level==cache->Level && (*pdata)[i].u.Cache.Type==cache->Type)
1354 return TRUE;
1357 while (*len == *pmax_len)
1358 if (!grow_logical_proc_buf(pdata, NULL, pmax_len))
1359 return FALSE;
1361 (*pdata)[i].Relationship = RelationCache;
1362 (*pdata)[i].ProcessorMask = mask;
1363 (*pdata)[i].u.Cache = *cache;
1364 *len = i+1;
1366 else
1368 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *dataex = *pdataex;
1369 DWORD ofs;
1371 for (ofs = 0; ofs < *len; )
1373 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + ofs);
1374 if (dataex->Relationship == RelationCache && dataex->u.Cache.GroupMask.Mask == mask &&
1375 dataex->u.Cache.Level == cache->Level && dataex->u.Cache.Type == cache->Type)
1376 return TRUE;
1377 ofs += dataex->Size;
1380 while (ofs + log_proc_ex_size_plus(sizeof(CACHE_RELATIONSHIP)) > *pmax_len)
1382 if (!grow_logical_proc_buf(NULL, pdataex, pmax_len))
1383 return FALSE;
1386 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + ofs);
1388 dataex->Relationship = RelationCache;
1389 dataex->Size = log_proc_ex_size_plus(sizeof(CACHE_RELATIONSHIP));
1390 dataex->u.Cache.Level = cache->Level;
1391 dataex->u.Cache.Associativity = cache->Associativity;
1392 dataex->u.Cache.LineSize = cache->LineSize;
1393 dataex->u.Cache.CacheSize = cache->Size;
1394 dataex->u.Cache.Type = cache->Type;
1395 dataex->u.Cache.GroupMask.Mask = mask;
1396 dataex->u.Cache.GroupMask.Group = 0;
1398 *len += dataex->Size;
1401 return TRUE;
1404 static inline BOOL logical_proc_info_add_numa_node(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **pdata,
1405 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **pdataex, DWORD *len, DWORD *pmax_len, ULONG_PTR mask,
1406 DWORD node_id)
1408 if (pdata)
1410 while (*len == *pmax_len)
1411 if (!grow_logical_proc_buf(pdata, NULL, pmax_len))
1412 return FALSE;
1414 (*pdata)[*len].Relationship = RelationNumaNode;
1415 (*pdata)[*len].ProcessorMask = mask;
1416 (*pdata)[*len].u.NumaNode.NodeNumber = node_id;
1417 (*len)++;
1419 else
1421 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *dataex;
1423 while (*len + log_proc_ex_size_plus(sizeof(NUMA_NODE_RELATIONSHIP)) > *pmax_len)
1425 if (!grow_logical_proc_buf(NULL, pdataex, pmax_len))
1426 return FALSE;
1429 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + *len);
1431 dataex->Relationship = RelationNumaNode;
1432 dataex->Size = log_proc_ex_size_plus(sizeof(NUMA_NODE_RELATIONSHIP));
1433 dataex->u.NumaNode.NodeNumber = node_id;
1434 dataex->u.NumaNode.GroupMask.Mask = mask;
1435 dataex->u.NumaNode.GroupMask.Group = 0;
1437 *len += dataex->Size;
1440 return TRUE;
1443 static inline BOOL logical_proc_info_add_group(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **pdataex,
1444 DWORD *len, DWORD *pmax_len, DWORD num_cpus, ULONG_PTR mask)
1446 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *dataex;
1448 while (*len + log_proc_ex_size_plus(sizeof(GROUP_RELATIONSHIP)) > *pmax_len)
1450 if (!grow_logical_proc_buf(NULL, pdataex, pmax_len))
1451 return FALSE;
1454 dataex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*pdataex) + *len);
1456 dataex->Relationship = RelationGroup;
1457 dataex->Size = log_proc_ex_size_plus(sizeof(GROUP_RELATIONSHIP));
1458 dataex->u.Group.MaximumGroupCount = 1;
1459 dataex->u.Group.ActiveGroupCount = 1;
1460 dataex->u.Group.GroupInfo[0].MaximumProcessorCount = num_cpus;
1461 dataex->u.Group.GroupInfo[0].ActiveProcessorCount = num_cpus;
1462 dataex->u.Group.GroupInfo[0].ActiveProcessorMask = mask;
1464 *len += dataex->Size;
1466 return TRUE;
1469 #ifdef linux
1470 /* for 'data', max_len is the array count. for 'dataex', max_len is in bytes */
1471 static NTSTATUS create_logical_proc_info(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data,
1472 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **dataex, DWORD *max_len)
1474 static const char core_info[] = "/sys/devices/system/cpu/cpu%u/%s";
1475 static const char cache_info[] = "/sys/devices/system/cpu/cpu%u/cache/index%u/%s";
1476 static const char numa_info[] = "/sys/devices/system/node/node%u/cpumap";
1478 FILE *fcpu_list, *fnuma_list, *f;
1479 DWORD len = 0, beg, end, i, j, r, num_cpus = 0;
1480 char op, name[MAX_PATH];
1481 ULONG_PTR all_cpus_mask = 0;
1483 fcpu_list = fopen("/sys/devices/system/cpu/online", "r");
1484 if(!fcpu_list)
1485 return STATUS_NOT_IMPLEMENTED;
1487 while(!feof(fcpu_list))
1489 if(!fscanf(fcpu_list, "%u%c ", &beg, &op))
1490 break;
1491 if(op == '-') fscanf(fcpu_list, "%u%c ", &end, &op);
1492 else end = beg;
1494 for(i=beg; i<=end; i++)
1496 if(i > 8*sizeof(ULONG_PTR))
1498 FIXME("skipping logical processor %d\n", i);
1499 continue;
1502 sprintf(name, core_info, i, "physical_package_id");
1503 f = fopen(name, "r");
1504 if(f)
1506 fscanf(f, "%u", &r);
1507 fclose(f);
1509 else r = 0;
1510 if(!logical_proc_info_add_by_id(data, dataex, &len, max_len, RelationProcessorPackage, r, (ULONG_PTR)1 << i))
1512 fclose(fcpu_list);
1513 return STATUS_NO_MEMORY;
1516 sprintf(name, core_info, i, "core_id");
1517 f = fopen(name, "r");
1518 if(f)
1520 fscanf(f, "%u", &r);
1521 fclose(f);
1523 else r = i;
1524 if(!logical_proc_info_add_by_id(data, dataex, &len, max_len, RelationProcessorCore, r, (ULONG_PTR)1 << i))
1526 fclose(fcpu_list);
1527 return STATUS_NO_MEMORY;
1530 for(j=0; j<4; j++)
1532 CACHE_DESCRIPTOR cache;
1533 ULONG_PTR mask = 0;
1535 sprintf(name, cache_info, i, j, "shared_cpu_map");
1536 f = fopen(name, "r");
1537 if(!f) continue;
1538 while(!feof(f))
1540 if(!fscanf(f, "%x%c ", &r, &op))
1541 break;
1542 mask = (sizeof(ULONG_PTR)>sizeof(int) ? mask<<(8*sizeof(DWORD)) : 0) + r;
1544 fclose(f);
1546 sprintf(name, cache_info, i, j, "level");
1547 f = fopen(name, "r");
1548 if(!f) continue;
1549 fscanf(f, "%u", &r);
1550 fclose(f);
1551 cache.Level = r;
1553 sprintf(name, cache_info, i, j, "ways_of_associativity");
1554 f = fopen(name, "r");
1555 if(!f) continue;
1556 fscanf(f, "%u", &r);
1557 fclose(f);
1558 cache.Associativity = r;
1560 sprintf(name, cache_info, i, j, "coherency_line_size");
1561 f = fopen(name, "r");
1562 if(!f) continue;
1563 fscanf(f, "%u", &r);
1564 fclose(f);
1565 cache.LineSize = r;
1567 sprintf(name, cache_info, i, j, "size");
1568 f = fopen(name, "r");
1569 if(!f) continue;
1570 fscanf(f, "%u%c", &r, &op);
1571 fclose(f);
1572 if(op != 'K')
1573 WARN("unknown cache size %u%c\n", r, op);
1574 cache.Size = (op=='K' ? r*1024 : r);
1576 sprintf(name, cache_info, i, j, "type");
1577 f = fopen(name, "r");
1578 if(!f) continue;
1579 fscanf(f, "%s", name);
1580 fclose(f);
1581 if(!memcmp(name, "Data", 5))
1582 cache.Type = CacheData;
1583 else if(!memcmp(name, "Instruction", 11))
1584 cache.Type = CacheInstruction;
1585 else
1586 cache.Type = CacheUnified;
1588 if(!logical_proc_info_add_cache(data, dataex, &len, max_len, mask, &cache))
1590 fclose(fcpu_list);
1591 return STATUS_NO_MEMORY;
1596 fclose(fcpu_list);
1598 if(data){
1599 for(i=0; i<len; i++){
1600 if((*data)[i].Relationship == RelationProcessorCore){
1601 all_cpus_mask |= (*data)[i].ProcessorMask;
1602 ++num_cpus;
1605 }else{
1606 for(i = 0; i < len; ){
1607 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *infoex = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(((char *)*dataex) + i);
1608 if(infoex->Relationship == RelationProcessorCore){
1609 all_cpus_mask |= infoex->u.Processor.GroupMask[0].Mask;
1610 ++num_cpus;
1612 i += infoex->Size;
1616 fnuma_list = fopen("/sys/devices/system/node/online", "r");
1617 if(!fnuma_list)
1619 if(!logical_proc_info_add_numa_node(data, dataex, &len, max_len, all_cpus_mask, 0))
1620 return STATUS_NO_MEMORY;
1622 else
1624 while(!feof(fnuma_list))
1626 if(!fscanf(fnuma_list, "%u%c ", &beg, &op))
1627 break;
1628 if(op == '-') fscanf(fnuma_list, "%u%c ", &end, &op);
1629 else end = beg;
1631 for(i=beg; i<=end; i++)
1633 ULONG_PTR mask = 0;
1635 sprintf(name, numa_info, i);
1636 f = fopen(name, "r");
1637 if(!f) continue;
1638 while(!feof(f))
1640 if(!fscanf(f, "%x%c ", &r, &op))
1641 break;
1642 mask = (sizeof(ULONG_PTR)>sizeof(int) ? mask<<(8*sizeof(DWORD)) : 0) + r;
1644 fclose(f);
1646 if(!logical_proc_info_add_numa_node(data, dataex, &len, max_len, mask, i))
1648 fclose(fnuma_list);
1649 return STATUS_NO_MEMORY;
1653 fclose(fnuma_list);
1656 if(dataex)
1657 logical_proc_info_add_group(dataex, &len, max_len, num_cpus, all_cpus_mask);
1659 if(data)
1660 *max_len = len * sizeof(**data);
1661 else
1662 *max_len = len;
1664 return STATUS_SUCCESS;
1666 #elif defined(__APPLE__)
1667 /* for 'data', max_len is the array count. for 'dataex', max_len is in bytes */
1668 static NTSTATUS create_logical_proc_info(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data,
1669 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **dataex, DWORD *max_len)
1671 DWORD pkgs_no, cores_no, lcpu_no, lcpu_per_core, cores_per_package, assoc, len = 0;
1672 DWORD cache_ctrs[10] = {0};
1673 ULONG_PTR all_cpus_mask = 0;
1674 CACHE_DESCRIPTOR cache[10];
1675 LONGLONG cache_size, cache_line_size, cache_sharing[10];
1676 size_t size;
1677 DWORD p,i,j,k;
1679 lcpu_no = NtCurrentTeb()->Peb->NumberOfProcessors;
1681 size = sizeof(pkgs_no);
1682 if(sysctlbyname("hw.packages", &pkgs_no, &size, NULL, 0))
1683 pkgs_no = 1;
1685 size = sizeof(cores_no);
1686 if(sysctlbyname("hw.physicalcpu", &cores_no, &size, NULL, 0))
1687 cores_no = lcpu_no;
1689 TRACE("%u logical CPUs from %u physical cores across %u packages\n",
1690 lcpu_no, cores_no, pkgs_no);
1692 lcpu_per_core = lcpu_no / cores_no;
1693 cores_per_package = cores_no / pkgs_no;
1695 memset(cache, 0, sizeof(cache));
1696 cache[1].Level = 1;
1697 cache[1].Type = CacheInstruction;
1698 cache[1].Associativity = 8; /* reasonable default */
1699 cache[1].LineSize = 0x40; /* reasonable default */
1700 cache[2].Level = 1;
1701 cache[2].Type = CacheData;
1702 cache[2].Associativity = 8;
1703 cache[2].LineSize = 0x40;
1704 cache[3].Level = 2;
1705 cache[3].Type = CacheUnified;
1706 cache[3].Associativity = 8;
1707 cache[3].LineSize = 0x40;
1708 cache[4].Level = 3;
1709 cache[4].Type = CacheUnified;
1710 cache[4].Associativity = 12;
1711 cache[4].LineSize = 0x40;
1713 size = sizeof(cache_line_size);
1714 if(!sysctlbyname("hw.cachelinesize", &cache_line_size, &size, NULL, 0))
1716 for(i=1; i<5; i++)
1717 cache[i].LineSize = cache_line_size;
1720 /* TODO: set actual associativity for all caches */
1721 size = sizeof(assoc);
1722 if(!sysctlbyname("machdep.cpu.cache.L2_associativity", &assoc, &size, NULL, 0))
1723 cache[3].Associativity = assoc;
1725 size = sizeof(cache_size);
1726 if(!sysctlbyname("hw.l1icachesize", &cache_size, &size, NULL, 0))
1727 cache[1].Size = cache_size;
1728 size = sizeof(cache_size);
1729 if(!sysctlbyname("hw.l1dcachesize", &cache_size, &size, NULL, 0))
1730 cache[2].Size = cache_size;
1731 size = sizeof(cache_size);
1732 if(!sysctlbyname("hw.l2cachesize", &cache_size, &size, NULL, 0))
1733 cache[3].Size = cache_size;
1734 size = sizeof(cache_size);
1735 if(!sysctlbyname("hw.l3cachesize", &cache_size, &size, NULL, 0))
1736 cache[4].Size = cache_size;
1738 size = sizeof(cache_sharing);
1739 if(sysctlbyname("hw.cacheconfig", cache_sharing, &size, NULL, 0) < 0){
1740 cache_sharing[1] = lcpu_per_core;
1741 cache_sharing[2] = lcpu_per_core;
1742 cache_sharing[3] = lcpu_per_core;
1743 cache_sharing[4] = lcpu_no;
1744 }else{
1745 /* in cache[], indexes 1 and 2 are l1 caches */
1746 cache_sharing[4] = cache_sharing[3];
1747 cache_sharing[3] = cache_sharing[2];
1748 cache_sharing[2] = cache_sharing[1];
1751 for(p = 0; p < pkgs_no; ++p){
1752 for(j = 0; j < cores_per_package && p * cores_per_package + j < cores_no; ++j){
1753 ULONG_PTR mask = 0;
1755 for(k = 0; k < lcpu_per_core; ++k)
1756 mask |= (ULONG_PTR)1 << (j * lcpu_per_core + k);
1758 all_cpus_mask |= mask;
1760 /* add to package */
1761 if(!logical_proc_info_add_by_id(data, dataex, &len, max_len, RelationProcessorPackage, p, mask))
1762 return STATUS_NO_MEMORY;
1764 /* add new core */
1765 if(!logical_proc_info_add_by_id(data, dataex, &len, max_len, RelationProcessorCore, p, mask))
1766 return STATUS_NO_MEMORY;
1768 for(i = 1; i < 5; ++i){
1769 if(cache_ctrs[i] == 0 && cache[i].Size > 0){
1770 mask = 0;
1771 for(k = 0; k < cache_sharing[i]; ++k)
1772 mask |= (ULONG_PTR)1 << (j * lcpu_per_core + k);
1774 if(!logical_proc_info_add_cache(data, dataex, &len, max_len, mask, &cache[i]))
1775 return STATUS_NO_MEMORY;
1778 cache_ctrs[i] += lcpu_per_core;
1780 if(cache_ctrs[i] == cache_sharing[i])
1781 cache_ctrs[i] = 0;
1786 /* OSX doesn't support NUMA, so just make one NUMA node for all CPUs */
1787 if(!logical_proc_info_add_numa_node(data, dataex, &len, max_len, all_cpus_mask, 0))
1788 return STATUS_NO_MEMORY;
1790 if(dataex)
1791 logical_proc_info_add_group(dataex, &len, max_len, lcpu_no, all_cpus_mask);
1793 if(data)
1794 *max_len = len * sizeof(**data);
1795 else
1796 *max_len = len;
1798 return STATUS_SUCCESS;
1800 #else
1801 static NTSTATUS create_logical_proc_info(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data,
1802 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX **dataex, DWORD *max_len)
1804 FIXME("stub\n");
1805 return STATUS_NOT_IMPLEMENTED;
1807 #endif
1809 /******************************************************************************
1810 * NtQuerySystemInformation [NTDLL.@]
1811 * ZwQuerySystemInformation [NTDLL.@]
1813 * ARGUMENTS:
1814 * SystemInformationClass Index to a certain information structure
1815 * SystemTimeAdjustmentInformation SYSTEM_TIME_ADJUSTMENT
1816 * SystemCacheInformation SYSTEM_CACHE_INFORMATION
1817 * SystemConfigurationInformation CONFIGURATION_INFORMATION
1818 * observed (class/len):
1819 * 0x0/0x2c
1820 * 0x12/0x18
1821 * 0x2/0x138
1822 * 0x8/0x600
1823 * 0x25/0xc
1824 * SystemInformation caller supplies storage for the information structure
1825 * Length size of the structure
1826 * ResultLength Data written
1828 NTSTATUS WINAPI NtQuerySystemInformation(
1829 IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
1830 OUT PVOID SystemInformation,
1831 IN ULONG Length,
1832 OUT PULONG ResultLength)
1834 NTSTATUS ret = STATUS_SUCCESS;
1835 ULONG len = 0;
1837 TRACE("(0x%08x,%p,0x%08x,%p)\n",
1838 SystemInformationClass,SystemInformation,Length,ResultLength);
1840 switch (SystemInformationClass)
1842 case SystemBasicInformation:
1844 SYSTEM_BASIC_INFORMATION sbi;
1846 virtual_get_system_info( &sbi );
1847 len = sizeof(sbi);
1849 if ( Length == len)
1851 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1852 else memcpy( SystemInformation, &sbi, len);
1854 else ret = STATUS_INFO_LENGTH_MISMATCH;
1856 break;
1857 case SystemCpuInformation:
1858 if (Length >= (len = sizeof(cached_sci)))
1860 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1861 else memcpy(SystemInformation, &cached_sci, len);
1863 else ret = STATUS_INFO_LENGTH_MISMATCH;
1864 break;
1865 case SystemPerformanceInformation:
1867 SYSTEM_PERFORMANCE_INFORMATION spi;
1868 static BOOL fixme_written = FALSE;
1869 FILE *fp;
1871 memset(&spi, 0 , sizeof(spi));
1872 len = sizeof(spi);
1874 spi.Reserved3 = 0x7fffffff; /* Available paged pool memory? */
1876 if ((fp = fopen("/proc/uptime", "r")))
1878 double uptime, idle_time;
1880 fscanf(fp, "%lf %lf", &uptime, &idle_time);
1881 fclose(fp);
1882 spi.IdleTime.QuadPart = 10000000 * idle_time;
1884 else
1886 static ULONGLONG idle;
1887 /* many programs expect IdleTime to change so fake change */
1888 spi.IdleTime.QuadPart = ++idle;
1891 if (Length >= len)
1893 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1894 else memcpy( SystemInformation, &spi, len);
1896 else ret = STATUS_INFO_LENGTH_MISMATCH;
1897 if(!fixme_written) {
1898 FIXME("info_class SYSTEM_PERFORMANCE_INFORMATION\n");
1899 fixme_written = TRUE;
1902 break;
1903 case SystemTimeOfDayInformation:
1905 SYSTEM_TIMEOFDAY_INFORMATION sti;
1907 memset(&sti, 0 , sizeof(sti));
1909 /* liKeSystemTime, liExpTimeZoneBias, uCurrentTimeZoneId */
1910 sti.liKeBootTime.QuadPart = server_start_time;
1912 if (Length <= sizeof(sti))
1914 len = Length;
1915 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1916 else memcpy( SystemInformation, &sti, Length);
1918 else ret = STATUS_INFO_LENGTH_MISMATCH;
1920 break;
1921 case SystemProcessInformation:
1923 SYSTEM_PROCESS_INFORMATION* spi = SystemInformation;
1924 SYSTEM_PROCESS_INFORMATION* last = NULL;
1925 HANDLE hSnap = 0;
1926 WCHAR procname[1024];
1927 WCHAR* exename;
1928 DWORD wlen = 0;
1929 DWORD procstructlen = 0;
1931 SERVER_START_REQ( create_snapshot )
1933 req->flags = SNAP_PROCESS | SNAP_THREAD;
1934 req->attributes = 0;
1935 if (!(ret = wine_server_call( req )))
1936 hSnap = wine_server_ptr_handle( reply->handle );
1938 SERVER_END_REQ;
1939 len = 0;
1940 while (ret == STATUS_SUCCESS)
1942 SERVER_START_REQ( next_process )
1944 req->handle = wine_server_obj_handle( hSnap );
1945 req->reset = (len == 0);
1946 wine_server_set_reply( req, procname, sizeof(procname)-sizeof(WCHAR) );
1947 if (!(ret = wine_server_call( req )))
1949 /* Make sure procname is 0 terminated */
1950 procname[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
1952 /* Get only the executable name, not the path */
1953 if ((exename = strrchrW(procname, '\\')) != NULL) exename++;
1954 else exename = procname;
1956 wlen = (strlenW(exename) + 1) * sizeof(WCHAR);
1958 procstructlen = sizeof(*spi) + wlen + ((reply->threads - 1) * sizeof(SYSTEM_THREAD_INFORMATION));
1960 if (Length >= len + procstructlen)
1962 /* ftCreationTime, ftUserTime, ftKernelTime;
1963 * vmCounters, ioCounters
1966 memset(spi, 0, sizeof(*spi));
1968 spi->NextEntryOffset = procstructlen - wlen;
1969 spi->dwThreadCount = reply->threads;
1971 /* spi->pszProcessName will be set later on */
1973 spi->dwBasePriority = reply->priority;
1974 spi->UniqueProcessId = UlongToHandle(reply->pid);
1975 spi->ParentProcessId = UlongToHandle(reply->ppid);
1976 spi->HandleCount = reply->handles;
1978 /* spi->ti will be set later on */
1981 len += procstructlen;
1984 SERVER_END_REQ;
1986 if (ret != STATUS_SUCCESS)
1988 if (ret == STATUS_NO_MORE_FILES) ret = STATUS_SUCCESS;
1989 break;
1992 if (Length >= len)
1994 int i, j;
1996 /* set thread info */
1997 i = j = 0;
1998 while (ret == STATUS_SUCCESS)
2000 SERVER_START_REQ( next_thread )
2002 req->handle = wine_server_obj_handle( hSnap );
2003 req->reset = (j == 0);
2004 if (!(ret = wine_server_call( req )))
2006 j++;
2007 if (UlongToHandle(reply->pid) == spi->UniqueProcessId)
2009 /* ftKernelTime, ftUserTime, ftCreateTime;
2010 * dwTickCount, dwStartAddress
2013 memset(&spi->ti[i], 0, sizeof(spi->ti));
2015 spi->ti[i].CreateTime.QuadPart = 0xdeadbeef;
2016 spi->ti[i].ClientId.UniqueProcess = UlongToHandle(reply->pid);
2017 spi->ti[i].ClientId.UniqueThread = UlongToHandle(reply->tid);
2018 spi->ti[i].dwCurrentPriority = reply->base_pri + reply->delta_pri;
2019 spi->ti[i].dwBasePriority = reply->base_pri;
2020 i++;
2024 SERVER_END_REQ;
2026 if (ret == STATUS_NO_MORE_FILES) ret = STATUS_SUCCESS;
2028 /* now append process name */
2029 spi->ProcessName.Buffer = (WCHAR*)((char*)spi + spi->NextEntryOffset);
2030 spi->ProcessName.Length = wlen - sizeof(WCHAR);
2031 spi->ProcessName.MaximumLength = wlen;
2032 memcpy( spi->ProcessName.Buffer, exename, wlen );
2033 spi->NextEntryOffset += wlen;
2035 last = spi;
2036 spi = (SYSTEM_PROCESS_INFORMATION*)((char*)spi + spi->NextEntryOffset);
2039 if (ret == STATUS_SUCCESS && last) last->NextEntryOffset = 0;
2040 if (len > Length) ret = STATUS_INFO_LENGTH_MISMATCH;
2041 if (hSnap) NtClose(hSnap);
2043 break;
2044 case SystemProcessorPerformanceInformation:
2046 SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *sppi = NULL;
2047 unsigned int cpus = 0;
2048 int out_cpus = Length / sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION);
2050 if (out_cpus == 0)
2052 len = 0;
2053 ret = STATUS_INFO_LENGTH_MISMATCH;
2054 break;
2056 else
2057 #ifdef __APPLE__
2059 processor_cpu_load_info_data_t *pinfo;
2060 mach_msg_type_number_t info_count;
2062 if (host_processor_info (mach_host_self (),
2063 PROCESSOR_CPU_LOAD_INFO,
2064 &cpus,
2065 (processor_info_array_t*)&pinfo,
2066 &info_count) == 0)
2068 int i;
2069 cpus = min(cpus,out_cpus);
2070 len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
2071 sppi = RtlAllocateHeap(GetProcessHeap(), HEAP_ZERO_MEMORY, len);
2072 for (i = 0; i < cpus; i++)
2074 sppi[i].IdleTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_IDLE];
2075 sppi[i].KernelTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_SYSTEM];
2076 sppi[i].UserTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_USER];
2078 vm_deallocate (mach_task_self (), (vm_address_t) pinfo, info_count * sizeof(natural_t));
2081 #else
2083 FILE *cpuinfo = fopen("/proc/stat", "r");
2084 if (cpuinfo)
2086 unsigned long clk_tck = sysconf(_SC_CLK_TCK);
2087 unsigned long usr,nice,sys,idle,remainder[8];
2088 int i, count;
2089 char name[32];
2090 char line[255];
2092 /* first line is combined usage */
2093 while (fgets(line,255,cpuinfo))
2095 count = sscanf(line, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
2096 name, &usr, &nice, &sys, &idle,
2097 &remainder[0], &remainder[1], &remainder[2], &remainder[3],
2098 &remainder[4], &remainder[5], &remainder[6], &remainder[7]);
2100 if (count < 5 || strncmp( name, "cpu", 3 )) break;
2101 for (i = 0; i + 5 < count; ++i) sys += remainder[i];
2102 sys += idle;
2103 usr += nice;
2104 cpus = atoi( name + 3 ) + 1;
2105 if (cpus > out_cpus) break;
2106 len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
2107 if (sppi)
2108 sppi = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sppi, len );
2109 else
2110 sppi = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, len );
2112 sppi[cpus-1].IdleTime.QuadPart = (ULONGLONG)idle * 10000000 / clk_tck;
2113 sppi[cpus-1].KernelTime.QuadPart = (ULONGLONG)sys * 10000000 / clk_tck;
2114 sppi[cpus-1].UserTime.QuadPart = (ULONGLONG)usr * 10000000 / clk_tck;
2116 fclose(cpuinfo);
2119 #endif
2121 if (cpus == 0)
2123 static int i = 1;
2124 unsigned int n;
2125 cpus = min(NtCurrentTeb()->Peb->NumberOfProcessors, out_cpus);
2126 len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
2127 sppi = RtlAllocateHeap(GetProcessHeap(), HEAP_ZERO_MEMORY, len);
2128 FIXME("stub info_class SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION\n");
2129 /* many programs expect these values to change so fake change */
2130 for (n = 0; n < cpus; n++)
2132 sppi[n].KernelTime.QuadPart = 1 * i;
2133 sppi[n].UserTime.QuadPart = 2 * i;
2134 sppi[n].IdleTime.QuadPart = 3 * i;
2136 i++;
2139 if (Length >= len)
2141 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2142 else memcpy( SystemInformation, sppi, len);
2144 else ret = STATUS_INFO_LENGTH_MISMATCH;
2146 RtlFreeHeap(GetProcessHeap(),0,sppi);
2148 break;
2149 case SystemModuleInformation:
2150 /* FIXME: should be system-wide */
2151 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2152 else ret = LdrQueryProcessModuleInformation( SystemInformation, Length, &len );
2153 break;
2154 case SystemHandleInformation:
2156 struct handle_info *info;
2157 DWORD i, num_handles;
2159 if (Length < sizeof(SYSTEM_HANDLE_INFORMATION))
2161 ret = STATUS_INFO_LENGTH_MISMATCH;
2162 break;
2165 if (!SystemInformation)
2167 ret = STATUS_ACCESS_VIOLATION;
2168 break;
2171 num_handles = (Length - FIELD_OFFSET( SYSTEM_HANDLE_INFORMATION, Handle )) / sizeof(SYSTEM_HANDLE_ENTRY);
2172 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) * num_handles )))
2173 return STATUS_NO_MEMORY;
2175 SERVER_START_REQ( get_system_handles )
2177 wine_server_set_reply( req, info, sizeof(*info) * num_handles );
2178 if (!(ret = wine_server_call( req )))
2180 SYSTEM_HANDLE_INFORMATION *shi = SystemInformation;
2181 shi->Count = wine_server_reply_size( req ) / sizeof(*info);
2182 len = FIELD_OFFSET( SYSTEM_HANDLE_INFORMATION, Handle[shi->Count] );
2183 for (i = 0; i < shi->Count; i++)
2185 memset( &shi->Handle[i], 0, sizeof(shi->Handle[i]) );
2186 shi->Handle[i].OwnerPid = info[i].owner;
2187 shi->Handle[i].HandleValue = info[i].handle;
2188 shi->Handle[i].AccessMask = info[i].access;
2189 /* FIXME: Fill out ObjectType, HandleFlags, ObjectPointer */
2192 else if (ret == STATUS_BUFFER_TOO_SMALL)
2194 len = FIELD_OFFSET( SYSTEM_HANDLE_INFORMATION, Handle[reply->count] );
2195 ret = STATUS_INFO_LENGTH_MISMATCH;
2198 SERVER_END_REQ;
2200 RtlFreeHeap( GetProcessHeap(), 0, info );
2202 break;
2203 case SystemCacheInformation:
2205 SYSTEM_CACHE_INFORMATION sci;
2207 memset(&sci, 0, sizeof(sci)); /* FIXME */
2208 len = sizeof(sci);
2210 if ( Length >= len)
2212 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2213 else memcpy( SystemInformation, &sci, len);
2215 else ret = STATUS_INFO_LENGTH_MISMATCH;
2216 FIXME("info_class SYSTEM_CACHE_INFORMATION\n");
2218 break;
2219 case SystemInterruptInformation:
2221 SYSTEM_INTERRUPT_INFORMATION sii;
2223 memset(&sii, 0, sizeof(sii));
2224 len = sizeof(sii);
2226 if ( Length >= len)
2228 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2229 else memcpy( SystemInformation, &sii, len);
2231 else ret = STATUS_INFO_LENGTH_MISMATCH;
2232 FIXME("info_class SYSTEM_INTERRUPT_INFORMATION\n");
2234 break;
2235 case SystemKernelDebuggerInformation:
2237 SYSTEM_KERNEL_DEBUGGER_INFORMATION skdi;
2239 skdi.DebuggerEnabled = FALSE;
2240 skdi.DebuggerNotPresent = TRUE;
2241 len = sizeof(skdi);
2243 if ( Length >= len)
2245 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2246 else memcpy( SystemInformation, &skdi, len);
2248 else ret = STATUS_INFO_LENGTH_MISMATCH;
2250 break;
2251 case SystemRegistryQuotaInformation:
2253 /* Something to do with the size of the registry *
2254 * Since we don't have a size limitation, fake it *
2255 * This is almost certainly wrong. *
2256 * This sets each of the three words in the struct to 32 MB, *
2257 * which is enough to make the IE 5 installer happy. */
2258 SYSTEM_REGISTRY_QUOTA_INFORMATION srqi;
2260 srqi.RegistryQuotaAllowed = 0x2000000;
2261 srqi.RegistryQuotaUsed = 0x200000;
2262 srqi.Reserved1 = (void*)0x200000;
2263 len = sizeof(srqi);
2265 if ( Length >= len)
2267 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2268 else
2270 FIXME("SystemRegistryQuotaInformation: faking max registry size of 32 MB\n");
2271 memcpy( SystemInformation, &srqi, len);
2274 else ret = STATUS_INFO_LENGTH_MISMATCH;
2276 break;
2277 case SystemLogicalProcessorInformation:
2279 SYSTEM_LOGICAL_PROCESSOR_INFORMATION *buf;
2281 /* Each logical processor may use up to 7 entries in returned table:
2282 * core, numa node, package, L1i, L1d, L2, L3 */
2283 len = 7 * NtCurrentTeb()->Peb->NumberOfProcessors;
2284 buf = RtlAllocateHeap(GetProcessHeap(), 0, len * sizeof(*buf));
2285 if(!buf)
2287 ret = STATUS_NO_MEMORY;
2288 break;
2291 ret = create_logical_proc_info(&buf, NULL, &len);
2292 if( ret != STATUS_SUCCESS )
2294 RtlFreeHeap(GetProcessHeap(), 0, buf);
2295 break;
2298 if( Length >= len)
2300 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2301 else memcpy( SystemInformation, buf, len);
2303 else ret = STATUS_INFO_LENGTH_MISMATCH;
2304 RtlFreeHeap(GetProcessHeap(), 0, buf);
2306 break;
2307 case SystemRecommendedSharedDataAlignment:
2309 len = sizeof(DWORD);
2310 if (Length >= len)
2312 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2313 else *((DWORD *)SystemInformation) = 64;
2315 else ret = STATUS_INFO_LENGTH_MISMATCH;
2317 break;
2318 default:
2319 FIXME("(0x%08x,%p,0x%08x,%p) stub\n",
2320 SystemInformationClass,SystemInformation,Length,ResultLength);
2322 /* Several Information Classes are not implemented on Windows and return 2 different values
2323 * STATUS_NOT_IMPLEMENTED or STATUS_INVALID_INFO_CLASS
2324 * in 95% of the cases it's STATUS_INVALID_INFO_CLASS, so use this as the default
2326 ret = STATUS_INVALID_INFO_CLASS;
2329 if (ResultLength) *ResultLength = len;
2331 return ret;
2334 /******************************************************************************
2335 * NtQuerySystemInformationEx [NTDLL.@]
2336 * ZwQuerySystemInformationEx [NTDLL.@]
2338 NTSTATUS WINAPI NtQuerySystemInformationEx(SYSTEM_INFORMATION_CLASS SystemInformationClass,
2339 void *Query, ULONG QueryLength, void *SystemInformation, ULONG Length, ULONG *ResultLength)
2341 ULONG len = 0;
2342 NTSTATUS ret = STATUS_NOT_IMPLEMENTED;
2344 TRACE("(0x%08x,%p,%u,%p,%u,%p) stub\n", SystemInformationClass, Query, QueryLength, SystemInformation,
2345 Length, ResultLength);
2347 switch (SystemInformationClass) {
2348 case SystemLogicalProcessorInformationEx:
2350 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buf;
2352 if (!Query || QueryLength < sizeof(DWORD))
2354 ret = STATUS_INVALID_PARAMETER;
2355 break;
2358 if (*(DWORD*)Query != RelationAll)
2359 FIXME("Relationship filtering not implemented: 0x%x\n", *(DWORD*)Query);
2361 len = 3 * sizeof(*buf);
2362 buf = RtlAllocateHeap(GetProcessHeap(), 0, len);
2363 if (!buf)
2365 ret = STATUS_NO_MEMORY;
2366 break;
2369 ret = create_logical_proc_info(NULL, &buf, &len);
2370 if (ret != STATUS_SUCCESS)
2372 RtlFreeHeap(GetProcessHeap(), 0, buf);
2373 break;
2376 if (Length >= len)
2378 if (!SystemInformation)
2379 ret = STATUS_ACCESS_VIOLATION;
2380 else
2381 memcpy( SystemInformation, buf, len);
2383 else
2384 ret = STATUS_INFO_LENGTH_MISMATCH;
2386 RtlFreeHeap(GetProcessHeap(), 0, buf);
2388 break;
2390 default:
2391 FIXME("(0x%08x,%p,%u,%p,%u,%p) stub\n", SystemInformationClass, Query, QueryLength, SystemInformation,
2392 Length, ResultLength);
2393 break;
2396 if (ResultLength)
2397 *ResultLength = len;
2399 return ret;
2402 /******************************************************************************
2403 * NtSetSystemInformation [NTDLL.@]
2404 * ZwSetSystemInformation [NTDLL.@]
2406 NTSTATUS WINAPI NtSetSystemInformation(SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG Length)
2408 FIXME("(0x%08x,%p,0x%08x) stub\n",SystemInformationClass,SystemInformation,Length);
2409 return STATUS_SUCCESS;
2412 /******************************************************************************
2413 * NtCreatePagingFile [NTDLL.@]
2414 * ZwCreatePagingFile [NTDLL.@]
2416 NTSTATUS WINAPI NtCreatePagingFile(
2417 PUNICODE_STRING PageFileName,
2418 PLARGE_INTEGER MinimumSize,
2419 PLARGE_INTEGER MaximumSize,
2420 PLARGE_INTEGER ActualSize)
2422 FIXME("(%p %p %p %p) stub\n", PageFileName, MinimumSize, MaximumSize, ActualSize);
2423 return STATUS_SUCCESS;
2426 /******************************************************************************
2427 * NtDisplayString [NTDLL.@]
2429 * writes a string to the nt-textmode screen eg. during startup
2431 NTSTATUS WINAPI NtDisplayString ( PUNICODE_STRING string )
2433 STRING stringA;
2434 NTSTATUS ret;
2436 if (!(ret = RtlUnicodeStringToAnsiString( &stringA, string, TRUE )))
2438 MESSAGE( "%.*s", stringA.Length, stringA.Buffer );
2439 RtlFreeAnsiString( &stringA );
2441 return ret;
2444 /******************************************************************************
2445 * NtInitiatePowerAction [NTDLL.@]
2448 NTSTATUS WINAPI NtInitiatePowerAction(
2449 IN POWER_ACTION SystemAction,
2450 IN SYSTEM_POWER_STATE MinSystemState,
2451 IN ULONG Flags,
2452 IN BOOLEAN Asynchronous)
2454 FIXME("(%d,%d,0x%08x,%d),stub\n",
2455 SystemAction,MinSystemState,Flags,Asynchronous);
2456 return STATUS_NOT_IMPLEMENTED;
2459 #ifdef linux
2460 /* Fallback using /proc/cpuinfo for Linux systems without cpufreq. For
2461 * most distributions on recent enough hardware, this is only likely to
2462 * happen while running in virtualized environments such as QEMU. */
2463 static ULONG mhz_from_cpuinfo(void)
2465 char line[512];
2466 char *s, *value;
2467 double cmz = 0;
2468 FILE* f = fopen("/proc/cpuinfo", "r");
2469 if(f) {
2470 while (fgets(line, sizeof(line), f) != NULL) {
2471 if (!(value = strchr(line,':')))
2472 continue;
2473 s = value - 1;
2474 while ((s >= line) && isspace(*s)) s--;
2475 *(s + 1) = '\0';
2476 value++;
2477 if (!strcasecmp(line, "cpu MHz")) {
2478 sscanf(value, " %lf", &cmz);
2479 break;
2482 fclose(f);
2484 return cmz;
2486 #endif
2488 /******************************************************************************
2489 * NtPowerInformation [NTDLL.@]
2492 NTSTATUS WINAPI NtPowerInformation(
2493 IN POWER_INFORMATION_LEVEL InformationLevel,
2494 IN PVOID lpInputBuffer,
2495 IN ULONG nInputBufferSize,
2496 IN PVOID lpOutputBuffer,
2497 IN ULONG nOutputBufferSize)
2499 TRACE("(%d,%p,%d,%p,%d)\n",
2500 InformationLevel,lpInputBuffer,nInputBufferSize,lpOutputBuffer,nOutputBufferSize);
2501 switch(InformationLevel) {
2502 case SystemPowerCapabilities: {
2503 PSYSTEM_POWER_CAPABILITIES PowerCaps = lpOutputBuffer;
2504 FIXME("semi-stub: SystemPowerCapabilities\n");
2505 if (nOutputBufferSize < sizeof(SYSTEM_POWER_CAPABILITIES))
2506 return STATUS_BUFFER_TOO_SMALL;
2507 /* FIXME: These values are based off a native XP desktop, should probably use APM/ACPI to get the 'real' values */
2508 PowerCaps->PowerButtonPresent = TRUE;
2509 PowerCaps->SleepButtonPresent = FALSE;
2510 PowerCaps->LidPresent = FALSE;
2511 PowerCaps->SystemS1 = TRUE;
2512 PowerCaps->SystemS2 = FALSE;
2513 PowerCaps->SystemS3 = FALSE;
2514 PowerCaps->SystemS4 = TRUE;
2515 PowerCaps->SystemS5 = TRUE;
2516 PowerCaps->HiberFilePresent = TRUE;
2517 PowerCaps->FullWake = TRUE;
2518 PowerCaps->VideoDimPresent = FALSE;
2519 PowerCaps->ApmPresent = FALSE;
2520 PowerCaps->UpsPresent = FALSE;
2521 PowerCaps->ThermalControl = FALSE;
2522 PowerCaps->ProcessorThrottle = FALSE;
2523 PowerCaps->ProcessorMinThrottle = 100;
2524 PowerCaps->ProcessorMaxThrottle = 100;
2525 PowerCaps->DiskSpinDown = TRUE;
2526 PowerCaps->SystemBatteriesPresent = FALSE;
2527 PowerCaps->BatteriesAreShortTerm = FALSE;
2528 PowerCaps->BatteryScale[0].Granularity = 0;
2529 PowerCaps->BatteryScale[0].Capacity = 0;
2530 PowerCaps->BatteryScale[1].Granularity = 0;
2531 PowerCaps->BatteryScale[1].Capacity = 0;
2532 PowerCaps->BatteryScale[2].Granularity = 0;
2533 PowerCaps->BatteryScale[2].Capacity = 0;
2534 PowerCaps->AcOnLineWake = PowerSystemUnspecified;
2535 PowerCaps->SoftLidWake = PowerSystemUnspecified;
2536 PowerCaps->RtcWake = PowerSystemSleeping1;
2537 PowerCaps->MinDeviceWakeState = PowerSystemUnspecified;
2538 PowerCaps->DefaultLowLatencyWake = PowerSystemUnspecified;
2539 return STATUS_SUCCESS;
2541 case SystemExecutionState: {
2542 PULONG ExecutionState = lpOutputBuffer;
2543 WARN("semi-stub: SystemExecutionState\n"); /* Needed for .NET Framework, but using a FIXME is really noisy. */
2544 if (lpInputBuffer != NULL)
2545 return STATUS_INVALID_PARAMETER;
2546 /* FIXME: The actual state should be the value set by SetThreadExecutionState which is not currently implemented. */
2547 *ExecutionState = ES_USER_PRESENT;
2548 return STATUS_SUCCESS;
2550 case ProcessorInformation: {
2551 const int cannedMHz = 1000; /* We fake a 1GHz processor if we can't conjure up real values */
2552 PROCESSOR_POWER_INFORMATION* cpu_power = lpOutputBuffer;
2553 int i, out_cpus;
2555 if ((lpOutputBuffer == NULL) || (nOutputBufferSize == 0))
2556 return STATUS_INVALID_PARAMETER;
2557 out_cpus = NtCurrentTeb()->Peb->NumberOfProcessors;
2558 if ((nOutputBufferSize / sizeof(PROCESSOR_POWER_INFORMATION)) < out_cpus)
2559 return STATUS_BUFFER_TOO_SMALL;
2560 #if defined(linux)
2562 char filename[128];
2563 FILE* f;
2565 for(i = 0; i < out_cpus; i++) {
2566 sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq", i);
2567 f = fopen(filename, "r");
2568 if (f && (fscanf(f, "%d", &cpu_power[i].CurrentMhz) == 1)) {
2569 cpu_power[i].CurrentMhz /= 1000;
2570 fclose(f);
2572 else {
2573 if(i == 0) {
2574 cpu_power[0].CurrentMhz = mhz_from_cpuinfo();
2575 if(cpu_power[0].CurrentMhz == 0)
2576 cpu_power[0].CurrentMhz = cannedMHz;
2578 else
2579 cpu_power[i].CurrentMhz = cpu_power[0].CurrentMhz;
2580 if(f) fclose(f);
2583 sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", i);
2584 f = fopen(filename, "r");
2585 if (f && (fscanf(f, "%d", &cpu_power[i].MaxMhz) == 1)) {
2586 cpu_power[i].MaxMhz /= 1000;
2587 fclose(f);
2589 else {
2590 cpu_power[i].MaxMhz = cpu_power[i].CurrentMhz;
2591 if(f) fclose(f);
2594 sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_max_freq", i);
2595 f = fopen(filename, "r");
2596 if(f && (fscanf(f, "%d", &cpu_power[i].MhzLimit) == 1)) {
2597 cpu_power[i].MhzLimit /= 1000;
2598 fclose(f);
2600 else
2602 cpu_power[i].MhzLimit = cpu_power[i].MaxMhz;
2603 if(f) fclose(f);
2606 cpu_power[i].Number = i;
2607 cpu_power[i].MaxIdleState = 0; /* FIXME */
2608 cpu_power[i].CurrentIdleState = 0; /* FIXME */
2611 #elif defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__DragonFly__)
2613 int num;
2614 size_t valSize = sizeof(num);
2615 if (sysctlbyname("hw.clockrate", &num, &valSize, NULL, 0))
2616 num = cannedMHz;
2617 for(i = 0; i < out_cpus; i++) {
2618 cpu_power[i].CurrentMhz = num;
2619 cpu_power[i].MaxMhz = num;
2620 cpu_power[i].MhzLimit = num;
2621 cpu_power[i].Number = i;
2622 cpu_power[i].MaxIdleState = 0; /* FIXME */
2623 cpu_power[i].CurrentIdleState = 0; /* FIXME */
2626 #elif defined (__APPLE__)
2628 size_t valSize;
2629 unsigned long long currentMhz;
2630 unsigned long long maxMhz;
2632 valSize = sizeof(currentMhz);
2633 if (!sysctlbyname("hw.cpufrequency", &currentMhz, &valSize, NULL, 0))
2634 currentMhz /= 1000000;
2635 else
2636 currentMhz = cannedMHz;
2638 valSize = sizeof(maxMhz);
2639 if (!sysctlbyname("hw.cpufrequency_max", &maxMhz, &valSize, NULL, 0))
2640 maxMhz /= 1000000;
2641 else
2642 maxMhz = currentMhz;
2644 for(i = 0; i < out_cpus; i++) {
2645 cpu_power[i].CurrentMhz = currentMhz;
2646 cpu_power[i].MaxMhz = maxMhz;
2647 cpu_power[i].MhzLimit = maxMhz;
2648 cpu_power[i].Number = i;
2649 cpu_power[i].MaxIdleState = 0; /* FIXME */
2650 cpu_power[i].CurrentIdleState = 0; /* FIXME */
2653 #else
2654 for(i = 0; i < out_cpus; i++) {
2655 cpu_power[i].CurrentMhz = cannedMHz;
2656 cpu_power[i].MaxMhz = cannedMHz;
2657 cpu_power[i].MhzLimit = cannedMHz;
2658 cpu_power[i].Number = i;
2659 cpu_power[i].MaxIdleState = 0; /* FIXME */
2660 cpu_power[i].CurrentIdleState = 0; /* FIXME */
2662 WARN("Unable to detect CPU MHz for this platform. Reporting %d MHz.\n", cannedMHz);
2663 #endif
2664 for(i = 0; i < out_cpus; i++) {
2665 TRACE("cpu_power[%d] = %u %u %u %u %u %u\n", i, cpu_power[i].Number,
2666 cpu_power[i].MaxMhz, cpu_power[i].CurrentMhz, cpu_power[i].MhzLimit,
2667 cpu_power[i].MaxIdleState, cpu_power[i].CurrentIdleState);
2669 return STATUS_SUCCESS;
2671 default:
2672 /* FIXME: Needed by .NET Framework */
2673 WARN("Unimplemented NtPowerInformation action: %d\n", InformationLevel);
2674 return STATUS_NOT_IMPLEMENTED;
2678 /******************************************************************************
2679 * NtShutdownSystem [NTDLL.@]
2682 NTSTATUS WINAPI NtShutdownSystem(SHUTDOWN_ACTION Action)
2684 FIXME("%d\n",Action);
2685 return STATUS_SUCCESS;
2688 /******************************************************************************
2689 * NtAllocateLocallyUniqueId (NTDLL.@)
2691 NTSTATUS WINAPI NtAllocateLocallyUniqueId(PLUID Luid)
2693 NTSTATUS status;
2695 TRACE("%p\n", Luid);
2697 if (!Luid)
2698 return STATUS_ACCESS_VIOLATION;
2700 SERVER_START_REQ( allocate_locally_unique_id )
2702 status = wine_server_call( req );
2703 if (!status)
2705 Luid->LowPart = reply->luid.low_part;
2706 Luid->HighPart = reply->luid.high_part;
2709 SERVER_END_REQ;
2711 return status;
2714 /******************************************************************************
2715 * VerSetConditionMask (NTDLL.@)
2717 ULONGLONG WINAPI VerSetConditionMask( ULONGLONG dwlConditionMask, DWORD dwTypeBitMask,
2718 BYTE dwConditionMask)
2720 if(dwTypeBitMask == 0)
2721 return dwlConditionMask;
2722 dwConditionMask &= 0x07;
2723 if(dwConditionMask == 0)
2724 return dwlConditionMask;
2726 if(dwTypeBitMask & VER_PRODUCT_TYPE)
2727 dwlConditionMask |= dwConditionMask << 7*3;
2728 else if (dwTypeBitMask & VER_SUITENAME)
2729 dwlConditionMask |= dwConditionMask << 6*3;
2730 else if (dwTypeBitMask & VER_SERVICEPACKMAJOR)
2731 dwlConditionMask |= dwConditionMask << 5*3;
2732 else if (dwTypeBitMask & VER_SERVICEPACKMINOR)
2733 dwlConditionMask |= dwConditionMask << 4*3;
2734 else if (dwTypeBitMask & VER_PLATFORMID)
2735 dwlConditionMask |= dwConditionMask << 3*3;
2736 else if (dwTypeBitMask & VER_BUILDNUMBER)
2737 dwlConditionMask |= dwConditionMask << 2*3;
2738 else if (dwTypeBitMask & VER_MAJORVERSION)
2739 dwlConditionMask |= dwConditionMask << 1*3;
2740 else if (dwTypeBitMask & VER_MINORVERSION)
2741 dwlConditionMask |= dwConditionMask << 0*3;
2742 return dwlConditionMask;
2745 /******************************************************************************
2746 * NtAccessCheckAndAuditAlarm (NTDLL.@)
2747 * ZwAccessCheckAndAuditAlarm (NTDLL.@)
2749 NTSTATUS WINAPI NtAccessCheckAndAuditAlarm(PUNICODE_STRING SubsystemName, HANDLE HandleId, PUNICODE_STRING ObjectTypeName,
2750 PUNICODE_STRING ObjectName, PSECURITY_DESCRIPTOR SecurityDescriptor,
2751 ACCESS_MASK DesiredAccess, PGENERIC_MAPPING GenericMapping, BOOLEAN ObjectCreation,
2752 PACCESS_MASK GrantedAccess, PBOOLEAN AccessStatus, PBOOLEAN GenerateOnClose)
2754 FIXME("(%s, %p, %s, %p, 0x%08x, %p, %d, %p, %p, %p), stub\n", debugstr_us(SubsystemName), HandleId,
2755 debugstr_us(ObjectTypeName), SecurityDescriptor, DesiredAccess, GenericMapping, ObjectCreation,
2756 GrantedAccess, AccessStatus, GenerateOnClose);
2758 return STATUS_NOT_IMPLEMENTED;
2761 /******************************************************************************
2762 * NtSystemDebugControl (NTDLL.@)
2763 * ZwSystemDebugControl (NTDLL.@)
2765 NTSTATUS WINAPI NtSystemDebugControl(SYSDBG_COMMAND command, PVOID inbuffer, ULONG inbuflength, PVOID outbuffer,
2766 ULONG outbuflength, PULONG retlength)
2768 FIXME("(%d, %p, %d, %p, %d, %p), stub\n", command, inbuffer, inbuflength, outbuffer, outbuflength, retlength);
2770 return STATUS_NOT_IMPLEMENTED;
2773 /******************************************************************************
2774 * NtSetLdtEntries (NTDLL.@)
2775 * ZwSetLdtEntries (NTDLL.@)
2777 NTSTATUS WINAPI NtSetLdtEntries(ULONG selector1, ULONG entry1_low, ULONG entry1_high,
2778 ULONG selector2, ULONG entry2_low, ULONG entry2_high)
2780 FIXME("(%u, %u, %u, %u, %u, %u): stub\n", selector1, entry1_low, entry1_high, selector2, entry2_low, entry2_high);
2782 return STATUS_NOT_IMPLEMENTED;