Release 1.5.29.
[wine] / dlls / ntdll / nt.c
1 /*
2  * NT basis DLL
3  *
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)
6  *
7  * Copyright 1996-1998 Marcus Meissner
8  *
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.
13  *
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.
18  *
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
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
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
39
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>
49
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"
60
61 #ifdef __APPLE__
62 #include <mach/mach_init.h>
63 #include <mach/mach_host.h>
64 #include <mach/vm_map.h>
65 #endif
66
67 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
68
69 /*
70  *      Token
71  */
72
73 /******************************************************************************
74  *  NtDuplicateToken            [NTDLL.@]
75  *  ZwDuplicateToken            [NTDLL.@]
76  */
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)
84 {
85     NTSTATUS status;
86
87     TRACE("(%p,0x%08x,%s,0x%08x,0x%08x,%p)\n",
88           ExistingToken, DesiredAccess, debugstr_ObjectAttributes(ObjectAttributes),
89           ImpersonationLevel, TokenType, NewToken);
90
91     if (ObjectAttributes && ObjectAttributes->SecurityQualityOfService)
92     {
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;
99     }
100
101     SERVER_START_REQ( duplicate_token )
102     {
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 );
110     }
111     SERVER_END_REQ;
112
113     return status;
114 }
115
116 /******************************************************************************
117  *  NtOpenProcessToken          [NTDLL.@]
118  *  ZwOpenProcessToken          [NTDLL.@]
119  */
120 NTSTATUS WINAPI NtOpenProcessToken(
121         HANDLE ProcessHandle,
122         DWORD DesiredAccess,
123         HANDLE *TokenHandle)
124 {
125     return NtOpenProcessTokenEx( ProcessHandle, DesiredAccess, 0, TokenHandle );
126 }
127
128 /******************************************************************************
129  *  NtOpenProcessTokenEx   [NTDLL.@]
130  *  ZwOpenProcessTokenEx   [NTDLL.@]
131  */
132 NTSTATUS WINAPI NtOpenProcessTokenEx( HANDLE process, DWORD access, DWORD attributes,
133                                       HANDLE *handle )
134 {
135     NTSTATUS ret;
136
137     TRACE("(%p,0x%08x,0x%08x,%p)\n", process, access, attributes, handle);
138
139     SERVER_START_REQ( open_token )
140     {
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 );
147     }
148     SERVER_END_REQ;
149     return ret;
150 }
151
152 /******************************************************************************
153  *  NtOpenThreadToken           [NTDLL.@]
154  *  ZwOpenThreadToken           [NTDLL.@]
155  */
156 NTSTATUS WINAPI NtOpenThreadToken(
157         HANDLE ThreadHandle,
158         DWORD DesiredAccess,
159         BOOLEAN OpenAsSelf,
160         HANDLE *TokenHandle)
161 {
162     return NtOpenThreadTokenEx( ThreadHandle, DesiredAccess, OpenAsSelf, 0, TokenHandle );
163 }
164
165 /******************************************************************************
166  *  NtOpenThreadTokenEx   [NTDLL.@]
167  *  ZwOpenThreadTokenEx   [NTDLL.@]
168  */
169 NTSTATUS WINAPI NtOpenThreadTokenEx( HANDLE thread, DWORD access, BOOLEAN as_self, DWORD attributes,
170                                      HANDLE *handle )
171 {
172     NTSTATUS ret;
173
174     TRACE("(%p,0x%08x,%u,0x%08x,%p)\n", thread, access, as_self, attributes, handle );
175
176     SERVER_START_REQ( open_token )
177     {
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 );
185     }
186     SERVER_END_REQ;
187
188     return ret;
189 }
190
191 /******************************************************************************
192  *  NtAdjustPrivilegesToken             [NTDLL.@]
193  *  ZwAdjustPrivilegesToken             [NTDLL.@]
194  *
195  * FIXME: parameters unsafe
196  */
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)
204 {
205     NTSTATUS ret;
206
207     TRACE("(%p,0x%08x,%p,0x%08x,%p,%p)\n",
208         TokenHandle, DisableAllPrivileges, NewState, BufferLength, PreviousState, ReturnLength);
209
210     SERVER_START_REQ( adjust_token_privileges )
211     {
212         req->handle = wine_server_obj_handle( TokenHandle );
213         req->disable_all = DisableAllPrivileges;
214         req->get_modified_state = (PreviousState != NULL);
215         if (!DisableAllPrivileges)
216         {
217             wine_server_add_data( req, NewState->Privileges,
218                                   NewState->PrivilegeCount * sizeof(NewState->Privileges[0]) );
219         }
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)
225         {
226             *ReturnLength = reply->len + FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges );
227             PreviousState->PrivilegeCount = reply->len / sizeof(LUID_AND_ATTRIBUTES);
228         }
229     }
230     SERVER_END_REQ;
231
232     return ret;
233 }
234
235 /******************************************************************************
236 *  NtQueryInformationToken              [NTDLL.@]
237 *  ZwQueryInformationToken              [NTDLL.@]
238 *
239 * NOTES
240 *  Buffer for TokenUser:
241 *   0x00 TOKEN_USER the PSID field points to the SID
242 *   0x08 SID
243 *
244 */
245 NTSTATUS WINAPI NtQueryInformationToken(
246         HANDLE token,
247         TOKEN_INFORMATION_CLASS tokeninfoclass,
248         PVOID tokeninfo,
249         ULONG tokeninfolength,
250         PULONG retlen )
251 {
252     static const ULONG info_len [] =
253     {
254         0,
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     };
284
285     ULONG len = 0;
286     NTSTATUS status = STATUS_SUCCESS;
287
288     TRACE("(%p,%d,%p,%d,%p)\n",
289           token,tokeninfoclass,tokeninfo,tokeninfolength,retlen);
290
291     if (tokeninfoclass < MaxTokenInfoClass)
292         len = info_len[tokeninfoclass];
293
294     if (retlen) *retlen = len;
295
296     if (tokeninfolength < len)
297         return STATUS_BUFFER_TOO_SMALL;
298
299     switch (tokeninfoclass)
300     {
301     case TokenUser:
302         SERVER_START_REQ( get_token_sid )
303         {
304             TOKEN_USER * tuser = tokeninfo;
305             PSID sid = tuser + 1;
306             DWORD sid_len = tokeninfolength < sizeof(TOKEN_USER) ? 0 : tokeninfolength - sizeof(TOKEN_USER);
307
308             req->handle = wine_server_obj_handle( token );
309             req->which_sid = tokeninfoclass;
310             wine_server_set_reply( req, sid, sid_len );
311             status = wine_server_call( req );
312             if (retlen) *retlen = reply->sid_len + sizeof(TOKEN_USER);
313             if (status == STATUS_SUCCESS)
314             {
315                 tuser->User.Sid = sid;
316                 tuser->User.Attributes = 0;
317             }
318         }
319         SERVER_END_REQ;
320         break;
321     case TokenGroups:
322     {
323         void *buffer;
324
325         /* reply buffer is always shorter than output one */
326         buffer = tokeninfolength ? RtlAllocateHeap(GetProcessHeap(), 0, tokeninfolength) : NULL;
327
328         SERVER_START_REQ( get_token_groups )
329         {
330             TOKEN_GROUPS *groups = tokeninfo;
331
332             req->handle = wine_server_obj_handle( token );
333             wine_server_set_reply( req, buffer, tokeninfolength );
334             status = wine_server_call( req );
335             if (status == STATUS_BUFFER_TOO_SMALL)
336             {
337                 if (retlen) *retlen = reply->user_len;
338             }
339             else if (status == STATUS_SUCCESS)
340             {
341                 struct token_groups *tg = buffer;
342                 unsigned int *attr = (unsigned int *)(tg + 1);
343                 ULONG i;
344                 const int non_sid_portion = (sizeof(struct token_groups) + tg->count * sizeof(unsigned int));
345                 SID *sids = (SID *)((char *)tokeninfo + FIELD_OFFSET( TOKEN_GROUPS, Groups[tg->count] ));
346
347                 if (retlen) *retlen = reply->user_len;
348
349                 groups->GroupCount = tg->count;
350                 memcpy( sids, (char *)buffer + non_sid_portion,
351                         reply->user_len - FIELD_OFFSET( TOKEN_GROUPS, Groups[tg->count] ));
352
353                 for (i = 0; i < tg->count; i++)
354                 {
355                     groups->Groups[i].Attributes = attr[i];
356                     groups->Groups[i].Sid = sids;
357                     sids = (SID *)((char *)sids + RtlLengthSid(sids));
358                 }
359              }
360              else if (retlen) *retlen = 0;
361         }
362         SERVER_END_REQ;
363
364         RtlFreeHeap(GetProcessHeap(), 0, buffer);
365         break;
366     }
367     case TokenPrimaryGroup:
368         SERVER_START_REQ( get_token_sid )
369         {
370             TOKEN_PRIMARY_GROUP *tgroup = tokeninfo;
371             PSID sid = tgroup + 1;
372             DWORD sid_len = tokeninfolength < sizeof(TOKEN_PRIMARY_GROUP) ? 0 : tokeninfolength - sizeof(TOKEN_PRIMARY_GROUP);
373
374             req->handle = wine_server_obj_handle( token );
375             req->which_sid = tokeninfoclass;
376             wine_server_set_reply( req, sid, sid_len );
377             status = wine_server_call( req );
378             if (retlen) *retlen = reply->sid_len + sizeof(TOKEN_PRIMARY_GROUP);
379             if (status == STATUS_SUCCESS)
380                 tgroup->PrimaryGroup = sid;
381         }
382         SERVER_END_REQ;
383         break;
384     case TokenPrivileges:
385         SERVER_START_REQ( get_token_privileges )
386         {
387             TOKEN_PRIVILEGES *tpriv = tokeninfo;
388             req->handle = wine_server_obj_handle( token );
389             if (tpriv && tokeninfolength > FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ))
390                 wine_server_set_reply( req, tpriv->Privileges, tokeninfolength - FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ) );
391             status = wine_server_call( req );
392             if (retlen) *retlen = FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ) + reply->len;
393             if (tpriv) tpriv->PrivilegeCount = reply->len / sizeof(LUID_AND_ATTRIBUTES);
394         }
395         SERVER_END_REQ;
396         break;
397     case TokenOwner:
398         SERVER_START_REQ( get_token_sid )
399         {
400             TOKEN_OWNER *towner = tokeninfo;
401             PSID sid = towner + 1;
402             DWORD sid_len = tokeninfolength < sizeof(TOKEN_OWNER) ? 0 : tokeninfolength - sizeof(TOKEN_OWNER);
403
404             req->handle = wine_server_obj_handle( token );
405             req->which_sid = tokeninfoclass;
406             wine_server_set_reply( req, sid, sid_len );
407             status = wine_server_call( req );
408             if (retlen) *retlen = reply->sid_len + sizeof(TOKEN_OWNER);
409             if (status == STATUS_SUCCESS)
410                 towner->Owner = sid;
411         }
412         SERVER_END_REQ;
413         break;
414     case TokenImpersonationLevel:
415         SERVER_START_REQ( get_token_impersonation_level )
416         {
417             SECURITY_IMPERSONATION_LEVEL *impersonation_level = tokeninfo;
418             req->handle = wine_server_obj_handle( token );
419             status = wine_server_call( req );
420             if (status == STATUS_SUCCESS)
421                 *impersonation_level = reply->impersonation_level;
422         }
423         SERVER_END_REQ;
424         break;
425     case TokenStatistics:
426         SERVER_START_REQ( get_token_statistics )
427         {
428             TOKEN_STATISTICS *statistics = tokeninfo;
429             req->handle = wine_server_obj_handle( token );
430             status = wine_server_call( req );
431             if (status == STATUS_SUCCESS)
432             {
433                 statistics->TokenId.LowPart  = reply->token_id.low_part;
434                 statistics->TokenId.HighPart = reply->token_id.high_part;
435                 statistics->AuthenticationId.LowPart  = 0; /* FIXME */
436                 statistics->AuthenticationId.HighPart = 0; /* FIXME */
437                 statistics->ExpirationTime.u.HighPart = 0x7fffffff;
438                 statistics->ExpirationTime.u.LowPart  = 0xffffffff;
439                 statistics->TokenType = reply->primary ? TokenPrimary : TokenImpersonation;
440                 statistics->ImpersonationLevel = reply->impersonation_level;
441
442                 /* kernel information not relevant to us */
443                 statistics->DynamicCharged = 0;
444                 statistics->DynamicAvailable = 0;
445
446                 statistics->GroupCount = reply->group_count;
447                 statistics->PrivilegeCount = reply->privilege_count;
448                 statistics->ModifiedId.LowPart  = reply->modified_id.low_part;
449                 statistics->ModifiedId.HighPart = reply->modified_id.high_part;
450             }
451         }
452         SERVER_END_REQ;
453         break;
454     case TokenType:
455         SERVER_START_REQ( get_token_statistics )
456         {
457             TOKEN_TYPE *token_type = tokeninfo;
458             req->handle = wine_server_obj_handle( token );
459             status = wine_server_call( req );
460             if (status == STATUS_SUCCESS)
461                 *token_type = reply->primary ? TokenPrimary : TokenImpersonation;
462         }
463         SERVER_END_REQ;
464         break;
465     case TokenDefaultDacl:
466         SERVER_START_REQ( get_token_default_dacl )
467         {
468             TOKEN_DEFAULT_DACL *default_dacl = tokeninfo;
469             ACL *acl = (ACL *)(default_dacl + 1);
470             DWORD acl_len;
471
472             if (tokeninfolength < sizeof(TOKEN_DEFAULT_DACL)) acl_len = 0;
473             else acl_len = tokeninfolength - sizeof(TOKEN_DEFAULT_DACL);
474
475             req->handle = wine_server_obj_handle( token );
476             wine_server_set_reply( req, acl, acl_len );
477             status = wine_server_call( req );
478
479             if (retlen) *retlen = reply->acl_len + sizeof(TOKEN_DEFAULT_DACL);
480             if (status == STATUS_SUCCESS)
481             {
482                 if (reply->acl_len)
483                     default_dacl->DefaultDacl = acl;
484                 else
485                     default_dacl->DefaultDacl = NULL;
486             }
487         }
488         SERVER_END_REQ;
489         break;
490     case TokenElevationType:
491         {
492             TOKEN_ELEVATION_TYPE *elevation_type = tokeninfo;
493             FIXME("QueryInformationToken( ..., TokenElevationType, ...) semi-stub\n");
494             *elevation_type = TokenElevationTypeFull;
495         }
496         break;
497     case TokenElevation:
498         {
499             TOKEN_ELEVATION *elevation = tokeninfo;
500             FIXME("QueryInformationToken( ..., TokenElevation, ...) semi-stub\n");
501             elevation->TokenIsElevated = TRUE;
502         }
503         break;
504     case TokenSessionId:
505         {
506             *((DWORD*)tokeninfo) = 0;
507             FIXME("QueryInformationToken( ..., TokenSessionId, ...) semi-stub\n");
508         }
509         break;
510     case TokenIntegrityLevel:
511         {
512             /* report always "S-1-16-12288" (high mandatory level) for now */
513             static const SID high_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
514                                                             {SECURITY_MANDATORY_HIGH_RID}};
515
516             TOKEN_MANDATORY_LABEL *tml = tokeninfo;
517             PSID psid = tml + 1;
518
519             tml->Label.Sid = psid;
520             tml->Label.Attributes = SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED;
521             memcpy(psid, &high_level, sizeof(SID));
522         }
523         break;
524     default:
525         {
526             ERR("Unhandled Token Information class %d!\n", tokeninfoclass);
527             return STATUS_NOT_IMPLEMENTED;
528         }
529     }
530     return status;
531 }
532
533 /******************************************************************************
534 *  NtSetInformationToken                [NTDLL.@]
535 *  ZwSetInformationToken                [NTDLL.@]
536 */
537 NTSTATUS WINAPI NtSetInformationToken(
538         HANDLE TokenHandle,
539         TOKEN_INFORMATION_CLASS TokenInformationClass,
540         PVOID TokenInformation,
541         ULONG TokenInformationLength)
542 {
543     NTSTATUS ret = STATUS_NOT_IMPLEMENTED;
544
545     TRACE("%p %d %p %u\n", TokenHandle, TokenInformationClass,
546            TokenInformation, TokenInformationLength);
547
548     switch (TokenInformationClass)
549     {
550     case TokenDefaultDacl:
551         if (TokenInformationLength < sizeof(TOKEN_DEFAULT_DACL))
552         {
553             ret = STATUS_INFO_LENGTH_MISMATCH;
554             break;
555         }
556         if (!TokenInformation)
557         {
558             ret = STATUS_ACCESS_VIOLATION;
559             break;
560         }
561         SERVER_START_REQ( set_token_default_dacl )
562         {
563             ACL *acl = ((TOKEN_DEFAULT_DACL *)TokenInformation)->DefaultDacl;
564             WORD size;
565
566             if (acl) size = acl->AclSize;
567             else size = 0;
568
569             req->handle = wine_server_obj_handle( TokenHandle );
570             wine_server_add_data( req, acl, size );
571             ret = wine_server_call( req );
572         }
573         SERVER_END_REQ;
574         break;
575     default:
576         FIXME("unimplemented class %u\n", TokenInformationClass);
577         break;
578     }
579
580     return ret;
581 }
582
583 /******************************************************************************
584 *  NtAdjustGroupsToken          [NTDLL.@]
585 *  ZwAdjustGroupsToken          [NTDLL.@]
586 */
587 NTSTATUS WINAPI NtAdjustGroupsToken(
588         HANDLE TokenHandle,
589         BOOLEAN ResetToDefault,
590         PTOKEN_GROUPS NewState,
591         ULONG BufferLength,
592         PTOKEN_GROUPS PreviousState,
593         PULONG ReturnLength)
594 {
595     FIXME("%p %d %p %u %p %p\n", TokenHandle, ResetToDefault,
596           NewState, BufferLength, PreviousState, ReturnLength);
597     return STATUS_NOT_IMPLEMENTED;
598 }
599
600 /******************************************************************************
601 *  NtPrivilegeCheck             [NTDLL.@]
602 *  ZwPrivilegeCheck             [NTDLL.@]
603 */
604 NTSTATUS WINAPI NtPrivilegeCheck(
605     HANDLE ClientToken,
606     PPRIVILEGE_SET RequiredPrivileges,
607     PBOOLEAN Result)
608 {
609     NTSTATUS status;
610     SERVER_START_REQ( check_token_privileges )
611     {
612         req->handle = wine_server_obj_handle( ClientToken );
613         req->all_required = (RequiredPrivileges->Control & PRIVILEGE_SET_ALL_NECESSARY) != 0;
614         wine_server_add_data( req, RequiredPrivileges->Privilege,
615             RequiredPrivileges->PrivilegeCount * sizeof(RequiredPrivileges->Privilege[0]) );
616         wine_server_set_reply( req, RequiredPrivileges->Privilege,
617             RequiredPrivileges->PrivilegeCount * sizeof(RequiredPrivileges->Privilege[0]) );
618
619         status = wine_server_call( req );
620
621         if (status == STATUS_SUCCESS)
622             *Result = reply->has_privileges != 0;
623     }
624     SERVER_END_REQ;
625     return status;
626 }
627
628 /*
629  *      Section
630  */
631
632 /******************************************************************************
633  *  NtQuerySection      [NTDLL.@]
634  */
635 NTSTATUS WINAPI NtQuerySection(
636         IN HANDLE SectionHandle,
637         IN SECTION_INFORMATION_CLASS SectionInformationClass,
638         OUT PVOID SectionInformation,
639         IN ULONG Length,
640         OUT PULONG ResultLength)
641 {
642         FIXME("(%p,%d,%p,0x%08x,%p) stub!\n",
643         SectionHandle,SectionInformationClass,SectionInformation,Length,ResultLength);
644         return 0;
645 }
646
647 /*
648  *      ports
649  */
650
651 /******************************************************************************
652  *  NtCreatePort                [NTDLL.@]
653  *  ZwCreatePort                [NTDLL.@]
654  */
655 NTSTATUS WINAPI NtCreatePort(PHANDLE PortHandle,POBJECT_ATTRIBUTES ObjectAttributes,
656                              ULONG MaxConnectInfoLength,ULONG MaxDataLength,PULONG reserved)
657 {
658   FIXME("(%p,%p,%u,%u,%p),stub!\n",PortHandle,ObjectAttributes,
659         MaxConnectInfoLength,MaxDataLength,reserved);
660   return STATUS_NOT_IMPLEMENTED;
661 }
662
663 /******************************************************************************
664  *  NtConnectPort               [NTDLL.@]
665  *  ZwConnectPort               [NTDLL.@]
666  */
667 NTSTATUS WINAPI NtConnectPort(
668         PHANDLE PortHandle,
669         PUNICODE_STRING PortName,
670         PSECURITY_QUALITY_OF_SERVICE SecurityQos,
671         PLPC_SECTION_WRITE WriteSection,
672         PLPC_SECTION_READ ReadSection,
673         PULONG MaximumMessageLength,
674         PVOID ConnectInfo,
675         PULONG pConnectInfoLength)
676 {
677     FIXME("(%p,%s,%p,%p,%p,%p,%p,%p),stub!\n",
678           PortHandle,debugstr_w(PortName->Buffer),SecurityQos,
679           WriteSection,ReadSection,MaximumMessageLength,ConnectInfo,
680           pConnectInfoLength);
681     if (ConnectInfo && pConnectInfoLength)
682         TRACE("\tMessage = %s\n",debugstr_an(ConnectInfo,*pConnectInfoLength));
683     return STATUS_NOT_IMPLEMENTED;
684 }
685
686 /******************************************************************************
687  *  NtSecureConnectPort                (NTDLL.@)
688  *  ZwSecureConnectPort                (NTDLL.@)
689  */
690 NTSTATUS WINAPI NtSecureConnectPort(
691         PHANDLE PortHandle,
692         PUNICODE_STRING PortName,
693         PSECURITY_QUALITY_OF_SERVICE SecurityQos,
694         PLPC_SECTION_WRITE WriteSection,
695         PSID pSid,
696         PLPC_SECTION_READ ReadSection,
697         PULONG MaximumMessageLength,
698         PVOID ConnectInfo,
699         PULONG pConnectInfoLength)
700 {
701     FIXME("(%p,%s,%p,%p,%p,%p,%p,%p,%p),stub!\n",
702           PortHandle,debugstr_w(PortName->Buffer),SecurityQos,
703           WriteSection,pSid,ReadSection,MaximumMessageLength,ConnectInfo,
704           pConnectInfoLength);
705     return STATUS_NOT_IMPLEMENTED;
706 }
707
708 /******************************************************************************
709  *  NtListenPort                [NTDLL.@]
710  *  ZwListenPort                [NTDLL.@]
711  */
712 NTSTATUS WINAPI NtListenPort(HANDLE PortHandle,PLPC_MESSAGE pLpcMessage)
713 {
714   FIXME("(%p,%p),stub!\n",PortHandle,pLpcMessage);
715   return STATUS_NOT_IMPLEMENTED;
716 }
717
718 /******************************************************************************
719  *  NtAcceptConnectPort [NTDLL.@]
720  *  ZwAcceptConnectPort [NTDLL.@]
721  */
722 NTSTATUS WINAPI NtAcceptConnectPort(
723         PHANDLE PortHandle,
724         ULONG PortIdentifier,
725         PLPC_MESSAGE pLpcMessage,
726         BOOLEAN Accept,
727         PLPC_SECTION_WRITE WriteSection,
728         PLPC_SECTION_READ ReadSection)
729 {
730   FIXME("(%p,%u,%p,%d,%p,%p),stub!\n",
731         PortHandle,PortIdentifier,pLpcMessage,Accept,WriteSection,ReadSection);
732   return STATUS_NOT_IMPLEMENTED;
733 }
734
735 /******************************************************************************
736  *  NtCompleteConnectPort       [NTDLL.@]
737  *  ZwCompleteConnectPort       [NTDLL.@]
738  */
739 NTSTATUS WINAPI NtCompleteConnectPort(HANDLE PortHandle)
740 {
741   FIXME("(%p),stub!\n",PortHandle);
742   return STATUS_NOT_IMPLEMENTED;
743 }
744
745 /******************************************************************************
746  *  NtRegisterThreadTerminatePort       [NTDLL.@]
747  *  ZwRegisterThreadTerminatePort       [NTDLL.@]
748  */
749 NTSTATUS WINAPI NtRegisterThreadTerminatePort(HANDLE PortHandle)
750 {
751   FIXME("(%p),stub!\n",PortHandle);
752   return STATUS_NOT_IMPLEMENTED;
753 }
754
755 /******************************************************************************
756  *  NtRequestWaitReplyPort              [NTDLL.@]
757  *  ZwRequestWaitReplyPort              [NTDLL.@]
758  */
759 NTSTATUS WINAPI NtRequestWaitReplyPort(
760         HANDLE PortHandle,
761         PLPC_MESSAGE pLpcMessageIn,
762         PLPC_MESSAGE pLpcMessageOut)
763 {
764   FIXME("(%p,%p,%p),stub!\n",PortHandle,pLpcMessageIn,pLpcMessageOut);
765   if(pLpcMessageIn)
766   {
767     TRACE("Message to send:\n");
768     TRACE("\tDataSize            = %u\n",pLpcMessageIn->DataSize);
769     TRACE("\tMessageSize         = %u\n",pLpcMessageIn->MessageSize);
770     TRACE("\tMessageType         = %u\n",pLpcMessageIn->MessageType);
771     TRACE("\tVirtualRangesOffset = %u\n",pLpcMessageIn->VirtualRangesOffset);
772     TRACE("\tClientId.UniqueProcess = %p\n",pLpcMessageIn->ClientId.UniqueProcess);
773     TRACE("\tClientId.UniqueThread  = %p\n",pLpcMessageIn->ClientId.UniqueThread);
774     TRACE("\tMessageId           = %lu\n",pLpcMessageIn->MessageId);
775     TRACE("\tSectionSize         = %lu\n",pLpcMessageIn->SectionSize);
776     TRACE("\tData                = %s\n",
777       debugstr_an((const char*)pLpcMessageIn->Data,pLpcMessageIn->DataSize));
778   }
779   return STATUS_NOT_IMPLEMENTED;
780 }
781
782 /******************************************************************************
783  *  NtReplyWaitReceivePort      [NTDLL.@]
784  *  ZwReplyWaitReceivePort      [NTDLL.@]
785  */
786 NTSTATUS WINAPI NtReplyWaitReceivePort(
787         HANDLE PortHandle,
788         PULONG PortIdentifier,
789         PLPC_MESSAGE ReplyMessage,
790         PLPC_MESSAGE Message)
791 {
792   FIXME("(%p,%p,%p,%p),stub!\n",PortHandle,PortIdentifier,ReplyMessage,Message);
793   return STATUS_NOT_IMPLEMENTED;
794 }
795
796 /*
797  *      Misc
798  */
799
800  /******************************************************************************
801  *  NtSetIntervalProfile        [NTDLL.@]
802  *  ZwSetIntervalProfile        [NTDLL.@]
803  */
804 NTSTATUS WINAPI NtSetIntervalProfile(
805         ULONG Interval,
806         KPROFILE_SOURCE Source)
807 {
808     FIXME("%u,%d\n", Interval, Source);
809     return STATUS_SUCCESS;
810 }
811
812 static  SYSTEM_CPU_INFORMATION cached_sci;
813
814 /*******************************************************************************
815  * Architecture specific feature detection for CPUs
816  *
817  * This a set of mutually exclusive #if define()s each providing its own get_cpuinfo() to be called
818  * from fill_cpu_info();
819  */
820 #if defined(__i386__) || defined(__x86_64__)
821
822 #define AUTH    0x68747541      /* "Auth" */
823 #define ENTI    0x69746e65      /* "enti" */
824 #define CAMD    0x444d4163      /* "cAMD" */
825
826 #define GENU    0x756e6547      /* "Genu" */
827 #define INEI    0x49656e69      /* "ineI" */
828 #define NTEL    0x6c65746e      /* "ntel" */
829
830 /* Calls cpuid with an eax of 'ax' and returns the 16 bytes in *p
831  * We are compiled with -fPIC, so we can't clobber ebx.
832  */
833 static inline void do_cpuid(unsigned int ax, unsigned int *p)
834 {
835 #ifdef __i386__
836         __asm__("pushl %%ebx\n\t"
837                 "cpuid\n\t"
838                 "movl %%ebx, %%esi\n\t"
839                 "popl %%ebx"
840                 : "=a" (p[0]), "=S" (p[1]), "=c" (p[2]), "=d" (p[3])
841                 :  "0" (ax));
842 #elif defined(__x86_64__)
843         __asm__("push %%rbx\n\t"
844                 "cpuid\n\t"
845                 "movq %%rbx, %%rsi\n\t"
846                 "pop %%rbx"
847                 : "=a" (p[0]), "=S" (p[1]), "=c" (p[2]), "=d" (p[3])
848                 :  "0" (ax));
849 #endif
850 }
851
852 /* From xf86info havecpuid.c 1.11 */
853 static inline int have_cpuid(void)
854 {
855 #ifdef __i386__
856         unsigned int f1, f2;
857         __asm__("pushfl\n\t"
858                 "pushfl\n\t"
859                 "popl %0\n\t"
860                 "movl %0,%1\n\t"
861                 "xorl %2,%0\n\t"
862                 "pushl %0\n\t"
863                 "popfl\n\t"
864                 "pushfl\n\t"
865                 "popl %0\n\t"
866                 "popfl"
867                 : "=&r" (f1), "=&r" (f2)
868                 : "ir" (0x00200000));
869         return ((f1^f2) & 0x00200000) != 0;
870 #elif defined(__x86_64__)
871         return 1;
872 #else
873         return 0;
874 #endif
875 }
876
877 /* Detect if a SSE2 processor is capable of Denormals Are Zero (DAZ) mode.
878  *
879  * This function assumes you have already checked for SSE2/FXSAVE support. */
880 static inline int have_sse_daz_mode(void)
881 {
882 #ifdef __i386__
883     typedef struct DECLSPEC_ALIGN(16) _M128A {
884         ULONGLONG Low;
885         LONGLONG High;
886     } M128A;
887
888     typedef struct _XMM_SAVE_AREA32 {
889         WORD ControlWord;
890         WORD StatusWord;
891         BYTE TagWord;
892         BYTE Reserved1;
893         WORD ErrorOpcode;
894         DWORD ErrorOffset;
895         WORD ErrorSelector;
896         WORD Reserved2;
897         DWORD DataOffset;
898         WORD DataSelector;
899         WORD Reserved3;
900         DWORD MxCsr;
901         DWORD MxCsr_Mask;
902         M128A FloatRegisters[8];
903         M128A XmmRegisters[16];
904         BYTE Reserved4[96];
905     } XMM_SAVE_AREA32;
906
907     /* Intel says we need a zeroed 16-byte aligned buffer */
908     char buffer[512 + 16];
909     XMM_SAVE_AREA32 *state = (XMM_SAVE_AREA32 *)(((ULONG_PTR)buffer + 15) & ~15);
910     memset(buffer, 0, sizeof(buffer));
911
912     __asm__ __volatile__( "fxsave %0" : "=m" (*state) : "m" (*state) );
913
914     return (state->MxCsr_Mask & (1 << 6)) >> 6;
915 #else /* all x86_64 processors include SSE2 with DAZ mode */
916     return 1;
917 #endif
918 }
919
920 static inline void get_cpuinfo(SYSTEM_CPU_INFORMATION* info)
921 {
922     unsigned int regs[4], regs2[4];
923
924 #if defined(__i386__)
925     info->Architecture = PROCESSOR_ARCHITECTURE_INTEL;
926 #elif defined(__x86_64__)
927     info->Architecture = PROCESSOR_ARCHITECTURE_AMD64;
928 #endif
929
930     /* We're at least a 386 */
931     info->FeatureSet = CPU_FEATURE_VME | CPU_FEATURE_X86 | CPU_FEATURE_PGE;
932     info->Level = 3;
933
934     if (!have_cpuid()) return;
935
936     do_cpuid(0x00000000, regs);  /* get standard cpuid level and vendor name */
937     if (regs[0]>=0x00000001)   /* Check for supported cpuid version */
938     {
939         do_cpuid(0x00000001, regs2); /* get cpu features */
940
941         if(regs2[3] & (1 << 3 )) info->FeatureSet |= CPU_FEATURE_PSE;
942         if(regs2[3] & (1 << 4 )) info->FeatureSet |= CPU_FEATURE_TSC;
943         if(regs2[3] & (1 << 8 )) info->FeatureSet |= CPU_FEATURE_CX8;
944         if(regs2[3] & (1 << 11)) info->FeatureSet |= CPU_FEATURE_SEP;
945         if(regs2[3] & (1 << 12)) info->FeatureSet |= CPU_FEATURE_MTRR;
946         if(regs2[3] & (1 << 15)) info->FeatureSet |= CPU_FEATURE_CMOV;
947         if(regs2[3] & (1 << 16)) info->FeatureSet |= CPU_FEATURE_PAT;
948         if(regs2[3] & (1 << 23)) info->FeatureSet |= CPU_FEATURE_MMX;
949         if(regs2[3] & (1 << 24)) info->FeatureSet |= CPU_FEATURE_FXSR;
950         if(regs2[3] & (1 << 25)) info->FeatureSet |= CPU_FEATURE_SSE;
951         if(regs2[3] & (1 << 26)) info->FeatureSet |= CPU_FEATURE_SSE2;
952
953         user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED]       = !(regs2[3] & 1);
954         user_shared_data->ProcessorFeatures[PF_RDTSC_INSTRUCTION_AVAILABLE]   = (regs2[3] & (1 << 4 )) >> 4;
955         user_shared_data->ProcessorFeatures[PF_PAE_ENABLED]                   = (regs2[3] & (1 << 6 )) >> 6;
956         user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE_DOUBLE]       = (regs2[3] & (1 << 8 )) >> 8;
957         user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE]    = (regs2[3] & (1 << 23)) >> 23;
958         user_shared_data->ProcessorFeatures[PF_XMMI_INSTRUCTIONS_AVAILABLE]   = (regs2[3] & (1 << 25)) >> 25;
959         user_shared_data->ProcessorFeatures[PF_XMMI64_INSTRUCTIONS_AVAILABLE] = (regs2[3] & (1 << 26)) >> 26;
960         user_shared_data->ProcessorFeatures[PF_SSE3_INSTRUCTIONS_AVAILABLE]   = regs2[2] & 1;
961         user_shared_data->ProcessorFeatures[PF_XSAVE_ENABLED]                 = (regs2[2] & (1 << 27)) >> 27;
962         user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE128]           = (regs2[2] & (1 << 13)) >> 13;
963
964         if((regs2[3] & (1 << 26)) && (regs2[3] & (1 << 24))) /* has SSE2 and FXSAVE/FXRSTOR */
965             user_shared_data->ProcessorFeatures[PF_SSE_DAZ_MODE_AVAILABLE] = have_sse_daz_mode();
966
967         if (regs[1] == AUTH && regs[3] == ENTI && regs[2] == CAMD)
968         {
969             info->Level = (regs2[0] >> 8) & 0xf; /* family */
970             if (info->Level == 0xf)  /* AMD says to add the extended family to the family if family is 0xf */
971                 info->Level += (regs2[0] >> 20) & 0xff;
972
973             /* repack model and stepping to make a "revision" */
974             info->Revision  = ((regs2[0] >> 16) & 0xf) << 12; /* extended model */
975             info->Revision |= ((regs2[0] >> 4 ) & 0xf) << 8;  /* model          */
976             info->Revision |= regs2[0] & 0xf;                 /* stepping       */
977
978             do_cpuid(0x80000000, regs);  /* get vendor cpuid level */
979             if (regs[0] >= 0x80000001)
980             {
981                 do_cpuid(0x80000001, regs2);  /* get vendor features */
982                 user_shared_data->ProcessorFeatures[PF_VIRT_FIRMWARE_ENABLED]        = (regs2[2] & (1 << 2  )) >> 2;
983                 user_shared_data->ProcessorFeatures[PF_NX_ENABLED]                   = (regs2[3] & (1 << 20 )) >> 20;
984                 user_shared_data->ProcessorFeatures[PF_3DNOW_INSTRUCTIONS_AVAILABLE] = (regs2[3] & (1 << 31 )) >> 31;
985                 if(regs2[3] & (1 << 31)) info->FeatureSet |= CPU_FEATURE_3DNOW;
986             }
987         }
988         else if (regs[1] == GENU && regs[3] == INEI && regs[2] == NTEL)
989         {
990             info->Level = ((regs2[0] >> 8) & 0xf) + ((regs2[0] >> 20) & 0xff); /* family + extended family */
991             if(info->Level == 15) info->Level = 6;
992
993             /* repack model and stepping to make a "revision" */
994             info->Revision  = ((regs2[0] >> 16) & 0xf) << 12; /* extended model */
995             info->Revision |= ((regs2[0] >> 4 ) & 0xf) << 8;  /* model          */
996             info->Revision |= regs2[0] & 0xf;                 /* stepping       */
997
998             if(regs2[3] & (1 << 21)) info->FeatureSet |= CPU_FEATURE_DS;
999             user_shared_data->ProcessorFeatures[PF_VIRT_FIRMWARE_ENABLED] = (regs2[2] & (1 << 5 )) >> 5;
1000
1001             do_cpuid(0x80000000, regs);  /* get vendor cpuid level */
1002             if (regs[0] >= 0x80000001)
1003             {
1004                 do_cpuid(0x80000001, regs2);  /* get vendor features */
1005                 user_shared_data->ProcessorFeatures[PF_NX_ENABLED] = (regs2[3] & (1 << 20 )) >> 20;
1006             }
1007         }
1008         else
1009         {
1010             info->Level = (regs2[0] >> 8) & 0xf; /* family */
1011
1012             /* repack model and stepping to make a "revision" */
1013             info->Revision = ((regs2[0] >> 4 ) & 0xf) << 8;  /* model    */
1014             info->Revision |= regs2[0] & 0xf;                /* stepping */
1015         }
1016     }
1017 }
1018
1019 #elif defined(__powerpc__) || defined(__ppc__)
1020
1021 static inline void get_cpuinfo(SYSTEM_CPU_INFORMATION* info)
1022 {
1023 #ifdef __APPLE__
1024     size_t valSize;
1025     int value;
1026
1027     valSize = sizeof(value);
1028     if (sysctlbyname("hw.optional.floatingpoint", &value, &valSize, NULL, 0) == 0)
1029         user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED] = !value;
1030
1031     valSize = sizeof(value);
1032     if (sysctlbyname("hw.cpusubtype", &value, &valSize, NULL, 0) == 0)
1033     {
1034         switch (value)
1035         {
1036             case CPU_SUBTYPE_POWERPC_601:
1037             case CPU_SUBTYPE_POWERPC_602:       info->Level = 1;   break;
1038             case CPU_SUBTYPE_POWERPC_603:       info->Level = 3;   break;
1039             case CPU_SUBTYPE_POWERPC_603e:
1040             case CPU_SUBTYPE_POWERPC_603ev:     info->Level = 6;   break;
1041             case CPU_SUBTYPE_POWERPC_604:       info->Level = 4;   break;
1042             case CPU_SUBTYPE_POWERPC_604e:      info->Level = 9;   break;
1043             case CPU_SUBTYPE_POWERPC_620:       info->Level = 20;  break;
1044             case CPU_SUBTYPE_POWERPC_750:       /* G3/G4 derive from 603 so ... */
1045             case CPU_SUBTYPE_POWERPC_7400:
1046             case CPU_SUBTYPE_POWERPC_7450:      info->Level = 6;   break;
1047             case CPU_SUBTYPE_POWERPC_970:       info->Level = 9;
1048                 /* :o) user_shared_data->ProcessorFeatures[PF_ALTIVEC_INSTRUCTIONS_AVAILABLE] ;-) */
1049                 break;
1050             default: break;
1051         }
1052     }
1053 #else
1054     FIXME("CPU Feature detection not implemented.\n");
1055 #endif
1056     info->Architecture = PROCESSOR_ARCHITECTURE_PPC;
1057 }
1058
1059 #elif defined(__arm__)
1060
1061 static inline void get_cpuinfo(SYSTEM_CPU_INFORMATION* info)
1062 {
1063 #ifdef linux
1064     char line[512];
1065     char *s, *value;
1066     FILE *f = fopen("/proc/cpuinfo", "r");
1067     if (f)
1068     {
1069         while (fgets(line, sizeof(line), f) != NULL)
1070         {
1071             /* NOTE: the ':' is the only character we can rely on */
1072             if (!(value = strchr(line,':')))
1073                 continue;
1074             /* terminate the valuename */
1075             s = value - 1;
1076             while ((s >= line) && isspace(*s)) s--;
1077             *(s + 1) = '\0';
1078             /* and strip leading spaces from value */
1079             value += 1;
1080             while (isspace(*value)) value++;
1081             if ((s = strchr(value,'\n')))
1082                 *s='\0';
1083             if (!strcasecmp(line, "CPU architecture"))
1084             {
1085                 if (isdigit(value[0]))
1086                     info->Level = atoi(value);
1087                 continue;
1088             }
1089             if (!strcasecmp(line, "features"))
1090             {
1091                 if (strstr(value, "vfpv3"))
1092                     user_shared_data->ProcessorFeatures[PF_ARM_VFP_32_REGISTERS_AVAILABLE] = TRUE;
1093                 if (strstr(value, "neon"))
1094                     user_shared_data->ProcessorFeatures[PF_ARM_NEON_INSTRUCTIONS_AVAILABLE] = TRUE;
1095                 continue;
1096             }
1097         }
1098         fclose(f);
1099     }
1100 #else
1101     FIXME("CPU Feature detection not implemented.\n");
1102 #endif
1103     info->Architecture = PROCESSOR_ARCHITECTURE_ARM;
1104 }
1105
1106 #elif defined(__aarch64__)
1107
1108 static inline void get_cpuinfo(SYSTEM_CPU_INFORMATION* info)
1109 {
1110     info->Level = 8;
1111     info->Architecture = PROCESSOR_ARCHITECTURE_ARM;
1112 }
1113
1114 #endif /* End architecture specific feature detection for CPUs */
1115
1116 /******************************************************************
1117  *              fill_cpu_info
1118  *
1119  * inits a couple of places with CPU related information:
1120  * - cached_sci in this file
1121  * - Peb->NumberOfProcessors
1122  * - SharedUserData->ProcessFeatures[] array
1123  */
1124 void fill_cpu_info(void)
1125 {
1126     long num;
1127
1128 #ifdef _SC_NPROCESSORS_ONLN
1129     num = sysconf(_SC_NPROCESSORS_ONLN);
1130     if (num < 1)
1131     {
1132         num = 1;
1133         WARN("Failed to detect the number of processors.\n");
1134     }
1135 #elif defined(CTL_HW) && defined(HW_NCPU)
1136     int mib[2];
1137     size_t len = sizeof(num);
1138     mib[0] = CTL_HW;
1139     mib[1] = HW_NCPU;
1140     if (sysctl(mib, 2, &num, &len, NULL, 0) != 0)
1141     {
1142         num = 1;
1143         WARN("Failed to detect the number of processors.\n");
1144     }
1145 #else
1146     num = 1;
1147     FIXME("Detecting the number of processors is not supported.\n");
1148 #endif
1149     NtCurrentTeb()->Peb->NumberOfProcessors = num;
1150
1151     memset(&cached_sci, 0, sizeof(cached_sci));
1152     get_cpuinfo(&cached_sci);
1153
1154     TRACE("<- CPU arch %d, level %d, rev %d, features 0x%x\n",
1155           cached_sci.Architecture, cached_sci.Level, cached_sci.Revision, cached_sci.FeatureSet);
1156 }
1157
1158 #ifdef linux
1159 static inline BOOL logical_proc_info_add_by_id(SYSTEM_LOGICAL_PROCESSOR_INFORMATION *data,
1160         DWORD *len, DWORD max_len, LOGICAL_PROCESSOR_RELATIONSHIP rel, DWORD id, DWORD proc)
1161 {
1162     DWORD i;
1163
1164     for(i=0; i<*len; i++)
1165     {
1166         if(data[i].Relationship!=rel || data[i].u.Reserved[1]!=id)
1167             continue;
1168
1169         data[i].ProcessorMask |= (ULONG_PTR)1<<proc;
1170         return TRUE;
1171     }
1172
1173     if(*len == max_len)
1174         return FALSE;
1175
1176     data[i].Relationship = rel;
1177     data[i].ProcessorMask = (ULONG_PTR)1<<proc;
1178     /* TODO: set processor core flags */
1179     data[i].u.Reserved[0] = 0;
1180     data[i].u.Reserved[1] = id;
1181     *len = i+1;
1182     return TRUE;
1183 }
1184
1185 static inline BOOL logical_proc_info_add_cache(SYSTEM_LOGICAL_PROCESSOR_INFORMATION *data,
1186         DWORD *len, DWORD max_len, ULONG_PTR mask, CACHE_DESCRIPTOR *cache)
1187 {
1188     DWORD i;
1189
1190     for(i=0; i<*len; i++)
1191     {
1192         if(data[i].Relationship==RelationCache && data[i].ProcessorMask==mask
1193                 && data[i].u.Cache.Level==cache->Level && data[i].u.Cache.Type==cache->Type)
1194             return TRUE;
1195     }
1196
1197     if(*len == max_len)
1198         return FALSE;
1199
1200     data[i].Relationship = RelationCache;
1201     data[i].ProcessorMask = mask;
1202     data[i].u.Cache = *cache;
1203     *len = i+1;
1204     return TRUE;
1205 }
1206
1207 static inline BOOL logical_proc_info_add_numa_node(SYSTEM_LOGICAL_PROCESSOR_INFORMATION *data,
1208         DWORD *len, DWORD max_len, ULONG_PTR mask, DWORD node_id)
1209 {
1210     if(*len == max_len)
1211         return FALSE;
1212
1213     data[*len].Relationship = RelationNumaNode;
1214     data[*len].ProcessorMask = mask;
1215     data[*len].u.NumaNode.NodeNumber = node_id;
1216     (*len)++;
1217     return TRUE;
1218 }
1219
1220 static NTSTATUS create_logical_proc_info(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data, DWORD *max_len)
1221 {
1222     static const char core_info[] = "/sys/devices/system/cpu/cpu%d/%s";
1223     static const char cache_info[] = "/sys/devices/system/cpu/cpu%d/cache/index%d/%s";
1224     static const char numa_info[] = "/sys/devices/system/node/node%d/cpumap";
1225
1226     FILE *fcpu_list, *fnuma_list, *f;
1227     DWORD len = 0, beg, end, i, j, r;
1228     char op, name[MAX_PATH];
1229
1230     fcpu_list = fopen("/sys/devices/system/cpu/online", "r");
1231     if(!fcpu_list)
1232         return STATUS_NOT_IMPLEMENTED;
1233
1234     while(!feof(fcpu_list))
1235     {
1236         if(!fscanf(fcpu_list, "%u%c ", &beg, &op))
1237             break;
1238         if(op == '-') fscanf(fcpu_list, "%u%c ", &end, &op);
1239         else end = beg;
1240
1241         for(i=beg; i<=end; i++)
1242         {
1243             if(i > 8*sizeof(ULONG_PTR))
1244             {
1245                 FIXME("skipping logical processor %d\n", i);
1246                 continue;
1247             }
1248
1249             sprintf(name, core_info, i, "core_id");
1250             f = fopen(name, "r");
1251             if(f)
1252             {
1253                 fscanf(f, "%u", &r);
1254                 fclose(f);
1255             }
1256             else r = i;
1257             if(!logical_proc_info_add_by_id(*data, &len, *max_len, RelationProcessorCore, r, i))
1258             {
1259                 SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;
1260
1261                 *max_len *= 2;
1262                 new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *data, *max_len*sizeof(*new_data));
1263                 if(!new_data)
1264                 {
1265                     fclose(fcpu_list);
1266                     return STATUS_NO_MEMORY;
1267                 }
1268
1269                 *data = new_data;
1270                 logical_proc_info_add_by_id(*data, &len, *max_len, RelationProcessorCore, r, i);
1271             }
1272
1273             sprintf(name, core_info, i, "physical_package_id");
1274             f = fopen(name, "r");
1275             if(f)
1276             {
1277                 fscanf(f, "%u", &r);
1278                 fclose(f);
1279             }
1280             else r = 0;
1281             if(!logical_proc_info_add_by_id(*data, &len, *max_len, RelationProcessorPackage, r, i))
1282             {
1283                 SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;
1284
1285                 *max_len *= 2;
1286                 new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *data, *max_len*sizeof(*new_data));
1287                 if(!new_data)
1288                 {
1289                     fclose(fcpu_list);
1290                     return STATUS_NO_MEMORY;
1291                 }
1292
1293                 *data = new_data;
1294                 logical_proc_info_add_by_id(*data, &len, *max_len, RelationProcessorPackage, r, i);
1295             }
1296
1297             for(j=0; j<4; j++)
1298             {
1299                 CACHE_DESCRIPTOR cache;
1300                 ULONG_PTR mask = 0;
1301
1302                 sprintf(name, cache_info, i, j, "shared_cpu_map");
1303                 f = fopen(name, "r");
1304                 if(!f) continue;
1305                 while(!feof(f))
1306                 {
1307                     if(!fscanf(f, "%x%c ", &r, &op))
1308                         break;
1309                     mask = (sizeof(ULONG_PTR)>sizeof(int) ? mask<<(8*sizeof(DWORD)) : 0) + r;
1310                 }
1311                 fclose(f);
1312
1313                 sprintf(name, cache_info, i, j, "level");
1314                 f = fopen(name, "r");
1315                 if(!f) continue;
1316                 fscanf(f, "%u", &r);
1317                 fclose(f);
1318                 cache.Level = r;
1319
1320                 sprintf(name, cache_info, i, j, "ways_of_associativity");
1321                 f = fopen(name, "r");
1322                 if(!f) continue;
1323                 fscanf(f, "%u", &r);
1324                 fclose(f);
1325                 cache.Associativity = r;
1326
1327                 sprintf(name, cache_info, i, j, "coherency_line_size");
1328                 f = fopen(name, "r");
1329                 if(!f) continue;
1330                 fscanf(f, "%u", &r);
1331                 fclose(f);
1332                 cache.LineSize = r;
1333
1334                 sprintf(name, cache_info, i, j, "size");
1335                 f = fopen(name, "r");
1336                 if(!f) continue;
1337                 fscanf(f, "%u%c", &r, &op);
1338                 fclose(f);
1339                 if(op != 'K')
1340                     WARN("unknown cache size %u%c\n", r, op);
1341                 cache.Size = (op=='K' ? r*1024 : r);
1342
1343                 sprintf(name, cache_info, i, j, "type");
1344                 f = fopen(name, "r");
1345                 if(!f) continue;
1346                 fscanf(f, "%s", name);
1347                 fclose(f);
1348                 if(!memcmp(name, "Data", 5))
1349                     cache.Type = CacheData;
1350                 else if(!memcmp(name, "Instruction", 11))
1351                     cache.Type = CacheInstruction;
1352                 else
1353                     cache.Type = CacheUnified;
1354
1355                 if(!logical_proc_info_add_cache(*data, &len, *max_len, mask, &cache))
1356                 {
1357                     SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;
1358
1359                     *max_len *= 2;
1360                     new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *data, *max_len*sizeof(*new_data));
1361                     if(!new_data)
1362                     {
1363                         fclose(fcpu_list);
1364                         return STATUS_NO_MEMORY;
1365                     }
1366
1367                     *data = new_data;
1368                     logical_proc_info_add_cache(*data, &len, *max_len, mask, &cache);
1369                 }
1370             }
1371         }
1372     }
1373     fclose(fcpu_list);
1374
1375     fnuma_list = fopen("/sys/devices/system/node/online", "r");
1376     if(!fnuma_list)
1377     {
1378         ULONG_PTR mask = 0;
1379
1380         for(i=0; i<len; i++)
1381             if((*data)[i].Relationship == RelationProcessorCore)
1382                 mask |= (*data)[i].ProcessorMask;
1383
1384         if(len == *max_len)
1385         {
1386             SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;
1387
1388             *max_len *= 2;
1389             new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *data, *max_len*sizeof(*new_data));
1390             if(!new_data)
1391                 return STATUS_NO_MEMORY;
1392
1393             *data = new_data;
1394         }
1395         logical_proc_info_add_numa_node(*data, &len, *max_len, mask, 0);
1396     }
1397     else
1398     {
1399         while(!feof(fnuma_list))
1400         {
1401             if(!fscanf(fnuma_list, "%u%c ", &beg, &op))
1402                 break;
1403             if(op == '-') fscanf(fnuma_list, "%u%c ", &end, &op);
1404             else end = beg;
1405
1406             for(i=beg; i<=end; i++)
1407             {
1408                 ULONG_PTR mask = 0;
1409
1410                 sprintf(name, numa_info, i);
1411                 f = fopen(name, "r");
1412                 if(!f) continue;
1413                 while(!feof(f))
1414                 {
1415                     if(!fscanf(f, "%x%c ", &r, &op))
1416                         break;
1417                     mask = (sizeof(ULONG_PTR)>sizeof(int) ? mask<<(8*sizeof(DWORD)) : 0) + r;
1418                 }
1419                 fclose(f);
1420
1421                 if(len == *max_len)
1422                 {
1423                     SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;
1424
1425                     *max_len *= 2;
1426                     new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *data, *max_len*sizeof(*new_data));
1427                     if(!new_data)
1428                     {
1429                         fclose(fnuma_list);
1430                         return STATUS_NO_MEMORY;
1431                     }
1432
1433                     *data = new_data;
1434                 }
1435                 logical_proc_info_add_numa_node(*data, &len, *max_len, mask, i);
1436             }
1437         }
1438         fclose(fnuma_list);
1439     }
1440
1441     *max_len = len * sizeof(**data);
1442     return STATUS_SUCCESS;
1443 }
1444 #elif defined(__APPLE__)
1445 static NTSTATUS create_logical_proc_info(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data, DWORD *max_len)
1446 {
1447     DWORD len = 0, i, j, k;
1448     DWORD cores_no, lcpu_no, lcpu_per_core, cores_per_package, assoc;
1449     size_t size;
1450     ULONG_PTR mask;
1451     LONGLONG cache_size, cache_line_size, cache_sharing[10];
1452     CACHE_DESCRIPTOR cache[4];
1453
1454     lcpu_no = NtCurrentTeb()->Peb->NumberOfProcessors;
1455
1456     size = sizeof(cores_no);
1457     if(sysctlbyname("machdep.cpu.core_count", &cores_no, &size, NULL, 0))
1458         cores_no = lcpu_no;
1459
1460     lcpu_per_core = lcpu_no/cores_no;
1461     for(i=0; i<cores_no; i++)
1462     {
1463         mask = 0;
1464         for(j=lcpu_per_core*i; j<lcpu_per_core*(i+1); j++)
1465             mask |= (ULONG_PTR)1<<j;
1466
1467         (*data)[len].Relationship = RelationProcessorCore;
1468         (*data)[len].ProcessorMask = mask;
1469         (*data)[len].u.ProcessorCore.Flags = 0; /* TODO */
1470         len++;
1471     }
1472
1473     size = sizeof(cores_per_package);
1474     if(sysctlbyname("machdep.cpu.cores_per_package", &cores_per_package, &size, NULL, 0))
1475         cores_per_package = lcpu_no;
1476
1477     for(i=0; i<(lcpu_no+cores_per_package-1)/cores_per_package; i++)
1478     {
1479         mask = 0;
1480         for(j=cores_per_package*i; j<cores_per_package*(i+1) && j<lcpu_no; j++)
1481             mask |= (ULONG_PTR)1<<j;
1482
1483         (*data)[len].Relationship = RelationProcessorPackage;
1484         (*data)[len].ProcessorMask = mask;
1485         len++;
1486     }
1487
1488     memset(cache, 0, sizeof(cache));
1489     cache[0].Level = 1;
1490     cache[0].Type = CacheInstruction;
1491     cache[1].Level = 1;
1492     cache[1].Type = CacheData;
1493     cache[2].Level = 2;
1494     cache[2].Type = CacheUnified;
1495     cache[3].Level = 3;
1496     cache[3].Type = CacheUnified;
1497
1498     size = sizeof(cache_line_size);
1499     if(!sysctlbyname("hw.cachelinesize", &cache_line_size, &size, NULL, 0))
1500     {
1501         for(i=0; i<4; i++)
1502             cache[i].LineSize = cache_line_size;
1503     }
1504
1505     /* TODO: set associativity for all caches */
1506     size = sizeof(assoc);
1507     if(!sysctlbyname("machdep.cpu.cache.L2_associativity", &assoc, &size, NULL, 0))
1508         cache[2].Associativity = assoc;
1509
1510     size = sizeof(cache_size);
1511     if(!sysctlbyname("hw.l1icachesize", &cache_size, &size, NULL, 0))
1512         cache[0].Size = cache_size;
1513     size = sizeof(cache_size);
1514     if(!sysctlbyname("hw.l1dcachesize", &cache_size, &size, NULL, 0))
1515         cache[1].Size = cache_size;
1516     size = sizeof(cache_size);
1517     if(!sysctlbyname("hw.l2cachesize", &cache_size, &size, NULL, 0))
1518         cache[2].Size = cache_size;
1519     size = sizeof(cache_size);
1520     if(!sysctlbyname("hw.l3cachesize", &cache_size, &size, NULL, 0))
1521         cache[3].Size = cache_size;
1522
1523     size = sizeof(cache_sharing);
1524     if(!sysctlbyname("hw.cacheconfig", cache_sharing, &size, NULL, 0))
1525     {
1526         for(i=1; i<4 && i<size/sizeof(*cache_sharing); i++)
1527         {
1528             if(!cache_sharing[i] || !cache[i].Size)
1529                 continue;
1530
1531             for(j=0; j<lcpu_no/cache_sharing[i]; j++)
1532             {
1533                 mask = 0;
1534                 for(k=j*cache_sharing[i]; k<lcpu_no && k<(j+1)*cache_sharing[i]; k++)
1535                     mask |= (ULONG_PTR)1<<k;
1536
1537                 if(i==1 && cache[0].Size)
1538                 {
1539                     (*data)[len].Relationship = RelationCache;
1540                     (*data)[len].ProcessorMask = mask;
1541                     (*data)[len].u.Cache = cache[0];
1542                     len++;
1543                 }
1544
1545                 (*data)[len].Relationship = RelationCache;
1546                 (*data)[len].ProcessorMask = mask;
1547                 (*data)[len].u.Cache = cache[i];
1548                 len++;
1549             }
1550         }
1551     }
1552
1553     mask = 0;
1554     for(i=0; i<lcpu_no; i++)
1555         mask |= (ULONG_PTR)1<<i;
1556     (*data)[len].Relationship = RelationNumaNode;
1557     (*data)[len].ProcessorMask = mask;
1558     (*data)[len].u.NumaNode.NodeNumber = 0;
1559     len++;
1560
1561     *max_len = len * sizeof(**data);
1562     return STATUS_SUCCESS;
1563 }
1564 #else
1565 static NTSTATUS create_logical_proc_info(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data, DWORD *max_len)
1566 {
1567     FIXME("stub\n");
1568     return STATUS_NOT_IMPLEMENTED;
1569 }
1570 #endif
1571
1572 /******************************************************************************
1573  * NtQuerySystemInformation [NTDLL.@]
1574  * ZwQuerySystemInformation [NTDLL.@]
1575  *
1576  * ARGUMENTS:
1577  *  SystemInformationClass      Index to a certain information structure
1578  *      SystemTimeAdjustmentInformation SYSTEM_TIME_ADJUSTMENT
1579  *      SystemCacheInformation          SYSTEM_CACHE_INFORMATION
1580  *      SystemConfigurationInformation  CONFIGURATION_INFORMATION
1581  *      observed (class/len):
1582  *              0x0/0x2c
1583  *              0x12/0x18
1584  *              0x2/0x138
1585  *              0x8/0x600
1586  *              0x25/0xc
1587  *  SystemInformation   caller supplies storage for the information structure
1588  *  Length              size of the structure
1589  *  ResultLength        Data written
1590  */
1591 NTSTATUS WINAPI NtQuerySystemInformation(
1592         IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
1593         OUT PVOID SystemInformation,
1594         IN ULONG Length,
1595         OUT PULONG ResultLength)
1596 {
1597     NTSTATUS    ret = STATUS_SUCCESS;
1598     ULONG       len = 0;
1599
1600     TRACE("(0x%08x,%p,0x%08x,%p)\n",
1601           SystemInformationClass,SystemInformation,Length,ResultLength);
1602
1603     switch (SystemInformationClass)
1604     {
1605     case SystemBasicInformation:
1606         {
1607             SYSTEM_BASIC_INFORMATION sbi;
1608
1609             virtual_get_system_info( &sbi );
1610             len = sizeof(sbi);
1611
1612             if ( Length == len)
1613             {
1614                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1615                 else memcpy( SystemInformation, &sbi, len);
1616             }
1617             else ret = STATUS_INFO_LENGTH_MISMATCH;
1618         }
1619         break;
1620     case SystemCpuInformation:
1621         if (Length >= (len = sizeof(cached_sci)))
1622         {
1623             if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1624             else memcpy(SystemInformation, &cached_sci, len);
1625         }
1626         else ret = STATUS_INFO_LENGTH_MISMATCH;
1627         break;
1628     case SystemPerformanceInformation:
1629         {
1630             SYSTEM_PERFORMANCE_INFORMATION spi;
1631             static BOOL fixme_written = FALSE;
1632             FILE *fp;
1633
1634             memset(&spi, 0 , sizeof(spi));
1635             len = sizeof(spi);
1636
1637             spi.Reserved3 = 0x7fffffff; /* Available paged pool memory? */
1638
1639             if ((fp = fopen("/proc/uptime", "r")))
1640             {
1641                 double uptime, idle_time;
1642
1643                 fscanf(fp, "%lf %lf", &uptime, &idle_time);
1644                 fclose(fp);
1645                 spi.IdleTime.QuadPart = 10000000 * idle_time;
1646             }
1647             else
1648             {
1649                 static ULONGLONG idle;
1650                 /* many programs expect IdleTime to change so fake change */
1651                 spi.IdleTime.QuadPart = ++idle;
1652             }
1653
1654             if (Length >= len)
1655             {
1656                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1657                 else memcpy( SystemInformation, &spi, len);
1658             }
1659             else ret = STATUS_INFO_LENGTH_MISMATCH;
1660             if(!fixme_written) {
1661                 FIXME("info_class SYSTEM_PERFORMANCE_INFORMATION\n");
1662                 fixme_written = TRUE;
1663             }
1664         }
1665         break;
1666     case SystemTimeOfDayInformation:
1667         {
1668             SYSTEM_TIMEOFDAY_INFORMATION sti;
1669
1670             memset(&sti, 0 , sizeof(sti));
1671
1672             /* liKeSystemTime, liExpTimeZoneBias, uCurrentTimeZoneId */
1673             sti.liKeBootTime.QuadPart = server_start_time;
1674
1675             if (Length <= sizeof(sti))
1676             {
1677                 len = Length;
1678                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1679                 else memcpy( SystemInformation, &sti, Length);
1680             }
1681             else ret = STATUS_INFO_LENGTH_MISMATCH;
1682         }
1683         break;
1684     case SystemProcessInformation:
1685         {
1686             SYSTEM_PROCESS_INFORMATION* spi = SystemInformation;
1687             SYSTEM_PROCESS_INFORMATION* last = NULL;
1688             HANDLE hSnap = 0;
1689             WCHAR procname[1024];
1690             WCHAR* exename;
1691             DWORD wlen = 0;
1692             DWORD procstructlen = 0;
1693
1694             SERVER_START_REQ( create_snapshot )
1695             {
1696                 req->flags      = SNAP_PROCESS | SNAP_THREAD;
1697                 req->attributes = 0;
1698                 if (!(ret = wine_server_call( req )))
1699                     hSnap = wine_server_ptr_handle( reply->handle );
1700             }
1701             SERVER_END_REQ;
1702             len = 0;
1703             while (ret == STATUS_SUCCESS)
1704             {
1705                 SERVER_START_REQ( next_process )
1706                 {
1707                     req->handle = wine_server_obj_handle( hSnap );
1708                     req->reset = (len == 0);
1709                     wine_server_set_reply( req, procname, sizeof(procname)-sizeof(WCHAR) );
1710                     if (!(ret = wine_server_call( req )))
1711                     {
1712                         /* Make sure procname is 0 terminated */
1713                         procname[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
1714
1715                         /* Get only the executable name, not the path */
1716                         if ((exename = strrchrW(procname, '\\')) != NULL) exename++;
1717                         else exename = procname;
1718
1719                         wlen = (strlenW(exename) + 1) * sizeof(WCHAR);
1720
1721                         procstructlen = sizeof(*spi) + wlen + ((reply->threads - 1) * sizeof(SYSTEM_THREAD_INFORMATION));
1722
1723                         if (Length >= len + procstructlen)
1724                         {
1725                             /* ftCreationTime, ftUserTime, ftKernelTime;
1726                              * vmCounters, ioCounters
1727                              */
1728  
1729                             memset(spi, 0, sizeof(*spi));
1730
1731                             spi->NextEntryOffset = procstructlen - wlen;
1732                             spi->dwThreadCount = reply->threads;
1733
1734                             /* spi->pszProcessName will be set later on */
1735
1736                             spi->dwBasePriority = reply->priority;
1737                             spi->UniqueProcessId = UlongToHandle(reply->pid);
1738                             spi->ParentProcessId = UlongToHandle(reply->ppid);
1739                             spi->HandleCount = reply->handles;
1740
1741                             /* spi->ti will be set later on */
1742
1743                         }
1744                         len += procstructlen;
1745                     }
1746                 }
1747                 SERVER_END_REQ;
1748  
1749                 if (ret != STATUS_SUCCESS)
1750                 {
1751                     if (ret == STATUS_NO_MORE_FILES) ret = STATUS_SUCCESS;
1752                     break;
1753                 }
1754
1755                 if (Length >= len)
1756                 {
1757                     int     i, j;
1758
1759                     /* set thread info */
1760                     i = j = 0;
1761                     while (ret == STATUS_SUCCESS)
1762                     {
1763                         SERVER_START_REQ( next_thread )
1764                         {
1765                             req->handle = wine_server_obj_handle( hSnap );
1766                             req->reset = (j == 0);
1767                             if (!(ret = wine_server_call( req )))
1768                             {
1769                                 j++;
1770                                 if (UlongToHandle(reply->pid) == spi->UniqueProcessId)
1771                                 {
1772                                     /* ftKernelTime, ftUserTime, ftCreateTime;
1773                                      * dwTickCount, dwStartAddress
1774                                      */
1775
1776                                     memset(&spi->ti[i], 0, sizeof(spi->ti));
1777
1778                                     spi->ti[i].CreateTime.QuadPart = 0xdeadbeef;
1779                                     spi->ti[i].ClientId.UniqueProcess = UlongToHandle(reply->pid);
1780                                     spi->ti[i].ClientId.UniqueThread  = UlongToHandle(reply->tid);
1781                                     spi->ti[i].dwCurrentPriority = reply->base_pri + reply->delta_pri;
1782                                     spi->ti[i].dwBasePriority = reply->base_pri;
1783                                     i++;
1784                                 }
1785                             }
1786                         }
1787                         SERVER_END_REQ;
1788                     }
1789                     if (ret == STATUS_NO_MORE_FILES) ret = STATUS_SUCCESS;
1790
1791                     /* now append process name */
1792                     spi->ProcessName.Buffer = (WCHAR*)((char*)spi + spi->NextEntryOffset);
1793                     spi->ProcessName.Length = wlen - sizeof(WCHAR);
1794                     spi->ProcessName.MaximumLength = wlen;
1795                     memcpy( spi->ProcessName.Buffer, exename, wlen );
1796                     spi->NextEntryOffset += wlen;
1797
1798                     last = spi;
1799                     spi = (SYSTEM_PROCESS_INFORMATION*)((char*)spi + spi->NextEntryOffset);
1800                 }
1801             }
1802             if (ret == STATUS_SUCCESS && last) last->NextEntryOffset = 0;
1803             if (len > Length) ret = STATUS_INFO_LENGTH_MISMATCH;
1804             if (hSnap) NtClose(hSnap);
1805         }
1806         break;
1807     case SystemProcessorPerformanceInformation:
1808         {
1809             SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *sppi = NULL;
1810             unsigned int cpus = 0;
1811             int out_cpus = Length / sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION);
1812
1813             if (out_cpus == 0)
1814             {
1815                 len = 0;
1816                 ret = STATUS_INFO_LENGTH_MISMATCH;
1817                 break;
1818             }
1819             else
1820 #ifdef __APPLE__
1821             {
1822                 processor_cpu_load_info_data_t *pinfo;
1823                 mach_msg_type_number_t info_count;
1824
1825                 if (host_processor_info (mach_host_self (),
1826                                          PROCESSOR_CPU_LOAD_INFO,
1827                                          &cpus,
1828                                          (processor_info_array_t*)&pinfo,
1829                                          &info_count) == 0)
1830                 {
1831                     int i;
1832                     cpus = min(cpus,out_cpus);
1833                     len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
1834                     sppi = RtlAllocateHeap(GetProcessHeap(), 0,len);
1835                     for (i = 0; i < cpus; i++)
1836                     {
1837                         sppi[i].IdleTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_IDLE];
1838                         sppi[i].KernelTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_SYSTEM];
1839                         sppi[i].UserTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_USER];
1840                     }
1841                     vm_deallocate (mach_task_self (), (vm_address_t) pinfo, info_count * sizeof(natural_t));
1842                 }
1843             }
1844 #else
1845             {
1846                 FILE *cpuinfo = fopen("/proc/stat", "r");
1847                 if (cpuinfo)
1848                 {
1849                     unsigned long clk_tck = sysconf(_SC_CLK_TCK);
1850                     unsigned long usr,nice,sys,idle,remainder[8];
1851                     int i, count;
1852                     char name[32];
1853                     char line[255];
1854
1855                     /* first line is combined usage */
1856                     while (fgets(line,255,cpuinfo))
1857                     {
1858                         count = sscanf(line, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
1859                                        name, &usr, &nice, &sys, &idle,
1860                                        &remainder[0], &remainder[1], &remainder[2], &remainder[3],
1861                                        &remainder[4], &remainder[5], &remainder[6], &remainder[7]);
1862
1863                         if (count < 5 || strncmp( name, "cpu", 3 )) break;
1864                         for (i = 0; i + 5 < count; ++i) sys += remainder[i];
1865                         sys += idle;
1866                         usr += nice;
1867                         cpus = atoi( name + 3 ) + 1;
1868                         if (cpus > out_cpus) break;
1869                         len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
1870                         if (sppi)
1871                             sppi = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sppi, len );
1872                         else
1873                             sppi = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, len );
1874
1875                         sppi[cpus-1].IdleTime.QuadPart   = (ULONGLONG)idle * 10000000 / clk_tck;
1876                         sppi[cpus-1].KernelTime.QuadPart = (ULONGLONG)sys * 10000000 / clk_tck;
1877                         sppi[cpus-1].UserTime.QuadPart   = (ULONGLONG)usr * 10000000 / clk_tck;
1878                     }
1879                     fclose(cpuinfo);
1880                 }
1881             }
1882 #endif
1883
1884             if (cpus == 0)
1885             {
1886                 static int i = 1;
1887                 unsigned int n;
1888                 cpus = min(NtCurrentTeb()->Peb->NumberOfProcessors, out_cpus);
1889                 len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
1890                 sppi = RtlAllocateHeap(GetProcessHeap(), 0, len);
1891                 FIXME("stub info_class SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION\n");
1892                 /* many programs expect these values to change so fake change */
1893                 for (n = 0; n < cpus; n++)
1894                 {
1895                     sppi[n].KernelTime.QuadPart = 1 * i;
1896                     sppi[n].UserTime.QuadPart   = 2 * i;
1897                     sppi[n].IdleTime.QuadPart   = 3 * i;
1898                 }
1899                 i++;
1900             }
1901
1902             if (Length >= len)
1903             {
1904                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1905                 else memcpy( SystemInformation, sppi, len);
1906             }
1907             else ret = STATUS_INFO_LENGTH_MISMATCH;
1908
1909             RtlFreeHeap(GetProcessHeap(),0,sppi);
1910         }
1911         break;
1912     case SystemModuleInformation:
1913         /* FIXME: should be system-wide */
1914         if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1915         else ret = LdrQueryProcessModuleInformation( SystemInformation, Length, &len );
1916         break;
1917     case SystemHandleInformation:
1918         {
1919             SYSTEM_HANDLE_INFORMATION shi;
1920
1921             memset(&shi, 0, sizeof(shi));
1922             len = sizeof(shi);
1923
1924             if ( Length >= len)
1925             {
1926                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1927                 else memcpy( SystemInformation, &shi, len);
1928             }
1929             else ret = STATUS_INFO_LENGTH_MISMATCH;
1930             FIXME("info_class SYSTEM_HANDLE_INFORMATION\n");
1931         }
1932         break;
1933     case SystemCacheInformation:
1934         {
1935             SYSTEM_CACHE_INFORMATION sci;
1936
1937             memset(&sci, 0, sizeof(sci)); /* FIXME */
1938             len = sizeof(sci);
1939
1940             if ( Length >= len)
1941             {
1942                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1943                 else memcpy( SystemInformation, &sci, len);
1944             }
1945             else ret = STATUS_INFO_LENGTH_MISMATCH;
1946             FIXME("info_class SYSTEM_CACHE_INFORMATION\n");
1947         }
1948         break;
1949     case SystemInterruptInformation:
1950         {
1951             SYSTEM_INTERRUPT_INFORMATION sii;
1952
1953             memset(&sii, 0, sizeof(sii));
1954             len = sizeof(sii);
1955
1956             if ( Length >= len)
1957             {
1958                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1959                 else memcpy( SystemInformation, &sii, len);
1960             }
1961             else ret = STATUS_INFO_LENGTH_MISMATCH;
1962             FIXME("info_class SYSTEM_INTERRUPT_INFORMATION\n");
1963         }
1964         break;
1965     case SystemKernelDebuggerInformation:
1966         {
1967             SYSTEM_KERNEL_DEBUGGER_INFORMATION skdi;
1968
1969             skdi.DebuggerEnabled = FALSE;
1970             skdi.DebuggerNotPresent = TRUE;
1971             len = sizeof(skdi);
1972
1973             if ( Length >= len)
1974             {
1975                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1976                 else memcpy( SystemInformation, &skdi, len);
1977             }
1978             else ret = STATUS_INFO_LENGTH_MISMATCH;
1979         }
1980         break;
1981     case SystemRegistryQuotaInformation:
1982         {
1983             /* Something to do with the size of the registry             *
1984              * Since we don't have a size limitation, fake it            *
1985              * This is almost certainly wrong.                           *
1986              * This sets each of the three words in the struct to 32 MB, *
1987              * which is enough to make the IE 5 installer happy.         */
1988             SYSTEM_REGISTRY_QUOTA_INFORMATION srqi;
1989
1990             srqi.RegistryQuotaAllowed = 0x2000000;
1991             srqi.RegistryQuotaUsed = 0x200000;
1992             srqi.Reserved1 = (void*)0x200000;
1993             len = sizeof(srqi);
1994
1995             if ( Length >= len)
1996             {
1997                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1998                 else
1999                 {
2000                     FIXME("SystemRegistryQuotaInformation: faking max registry size of 32 MB\n");
2001                     memcpy( SystemInformation, &srqi, len);
2002                 }
2003             }
2004             else ret = STATUS_INFO_LENGTH_MISMATCH;
2005         }
2006         break;
2007     case SystemLogicalProcessorInformation:
2008         {
2009             SYSTEM_LOGICAL_PROCESSOR_INFORMATION *buf;
2010
2011             /* Each logical processor may use up to 7 entries in returned table:
2012              * core, numa node, package, L1i, L1d, L2, L3 */
2013             len = 7 * NtCurrentTeb()->Peb->NumberOfProcessors;
2014             buf = RtlAllocateHeap(GetProcessHeap(), 0, len * sizeof(*buf));
2015             if(!buf)
2016             {
2017                 ret = STATUS_NO_MEMORY;
2018                 break;
2019             }
2020
2021             ret = create_logical_proc_info(&buf, &len);
2022             if( ret != STATUS_SUCCESS )
2023             {
2024                 RtlFreeHeap(GetProcessHeap(), 0, buf);
2025                 break;
2026             }
2027
2028             if( Length >= len)
2029             {
2030                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2031                 else memcpy( SystemInformation, buf, len);
2032             }
2033             else ret = STATUS_INFO_LENGTH_MISMATCH;
2034             RtlFreeHeap(GetProcessHeap(), 0, buf);
2035         }
2036         break;
2037     default:
2038         FIXME("(0x%08x,%p,0x%08x,%p) stub\n",
2039               SystemInformationClass,SystemInformation,Length,ResultLength);
2040
2041         /* Several Information Classes are not implemented on Windows and return 2 different values 
2042          * STATUS_NOT_IMPLEMENTED or STATUS_INVALID_INFO_CLASS
2043          * in 95% of the cases it's STATUS_INVALID_INFO_CLASS, so use this as the default
2044         */
2045         ret = STATUS_INVALID_INFO_CLASS;
2046     }
2047
2048     if (ResultLength) *ResultLength = len;
2049
2050     return ret;
2051 }
2052
2053 /******************************************************************************
2054  * NtSetSystemInformation [NTDLL.@]
2055  * ZwSetSystemInformation [NTDLL.@]
2056  */
2057 NTSTATUS WINAPI NtSetSystemInformation(SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG Length)
2058 {
2059     FIXME("(0x%08x,%p,0x%08x) stub\n",SystemInformationClass,SystemInformation,Length);
2060     return STATUS_SUCCESS;
2061 }
2062
2063 /******************************************************************************
2064  *  NtCreatePagingFile          [NTDLL.@]
2065  *  ZwCreatePagingFile          [NTDLL.@]
2066  */
2067 NTSTATUS WINAPI NtCreatePagingFile(
2068         PUNICODE_STRING PageFileName,
2069         PLARGE_INTEGER MinimumSize,
2070         PLARGE_INTEGER MaximumSize,
2071         PLARGE_INTEGER ActualSize)
2072 {
2073     FIXME("(%p %p %p %p) stub\n", PageFileName, MinimumSize, MaximumSize, ActualSize);
2074     return STATUS_SUCCESS;
2075 }
2076
2077 /******************************************************************************
2078  *  NtDisplayString                             [NTDLL.@]
2079  *
2080  * writes a string to the nt-textmode screen eg. during startup
2081  */
2082 NTSTATUS WINAPI NtDisplayString ( PUNICODE_STRING string )
2083 {
2084     STRING stringA;
2085     NTSTATUS ret;
2086
2087     if (!(ret = RtlUnicodeStringToAnsiString( &stringA, string, TRUE )))
2088     {
2089         MESSAGE( "%.*s", stringA.Length, stringA.Buffer );
2090         RtlFreeAnsiString( &stringA );
2091     }
2092     return ret;
2093 }
2094
2095 /******************************************************************************
2096  *  NtInitiatePowerAction                       [NTDLL.@]
2097  *
2098  */
2099 NTSTATUS WINAPI NtInitiatePowerAction(
2100         IN POWER_ACTION SystemAction,
2101         IN SYSTEM_POWER_STATE MinSystemState,
2102         IN ULONG Flags,
2103         IN BOOLEAN Asynchronous)
2104 {
2105         FIXME("(%d,%d,0x%08x,%d),stub\n",
2106                 SystemAction,MinSystemState,Flags,Asynchronous);
2107         return STATUS_NOT_IMPLEMENTED;
2108 }
2109
2110 #ifdef linux
2111 /* Fallback using /proc/cpuinfo for Linux systems without cpufreq. For
2112  * most distributions on recent enough hardware, this is only likely to
2113  * happen while running in virtualized environments such as QEMU. */
2114 static ULONG mhz_from_cpuinfo(void)
2115 {
2116     char line[512];
2117     char *s, *value;
2118     double cmz = 0;
2119     FILE* f = fopen("/proc/cpuinfo", "r");
2120     if(f) {
2121         while (fgets(line, sizeof(line), f) != NULL) {
2122             if (!(value = strchr(line,':')))
2123                 continue;
2124             s = value - 1;
2125             while ((s >= line) && isspace(*s)) s--;
2126             *(s + 1) = '\0';
2127             value++;
2128             if (!strcasecmp(line, "cpu MHz")) {
2129                 sscanf(value, " %lf", &cmz);
2130                 break;
2131             }
2132         }
2133         fclose(f);
2134     }
2135     return cmz;
2136 }
2137 #endif
2138
2139 /******************************************************************************
2140  *  NtPowerInformation                          [NTDLL.@]
2141  *
2142  */
2143 NTSTATUS WINAPI NtPowerInformation(
2144         IN POWER_INFORMATION_LEVEL InformationLevel,
2145         IN PVOID lpInputBuffer,
2146         IN ULONG nInputBufferSize,
2147         IN PVOID lpOutputBuffer,
2148         IN ULONG nOutputBufferSize)
2149 {
2150         TRACE("(%d,%p,%d,%p,%d)\n",
2151                 InformationLevel,lpInputBuffer,nInputBufferSize,lpOutputBuffer,nOutputBufferSize);
2152         switch(InformationLevel) {
2153                 case SystemPowerCapabilities: {
2154                         PSYSTEM_POWER_CAPABILITIES PowerCaps = lpOutputBuffer;
2155                         FIXME("semi-stub: SystemPowerCapabilities\n");
2156                         if (nOutputBufferSize < sizeof(SYSTEM_POWER_CAPABILITIES))
2157                                 return STATUS_BUFFER_TOO_SMALL;
2158                         /* FIXME: These values are based off a native XP desktop, should probably use APM/ACPI to get the 'real' values */
2159                         PowerCaps->PowerButtonPresent = TRUE;
2160                         PowerCaps->SleepButtonPresent = FALSE;
2161                         PowerCaps->LidPresent = FALSE;
2162                         PowerCaps->SystemS1 = TRUE;
2163                         PowerCaps->SystemS2 = FALSE;
2164                         PowerCaps->SystemS3 = FALSE;
2165                         PowerCaps->SystemS4 = TRUE;
2166                         PowerCaps->SystemS5 = TRUE;
2167                         PowerCaps->HiberFilePresent = TRUE;
2168                         PowerCaps->FullWake = TRUE;
2169                         PowerCaps->VideoDimPresent = FALSE;
2170                         PowerCaps->ApmPresent = FALSE;
2171                         PowerCaps->UpsPresent = FALSE;
2172                         PowerCaps->ThermalControl = FALSE;
2173                         PowerCaps->ProcessorThrottle = FALSE;
2174                         PowerCaps->ProcessorMinThrottle = 100;
2175                         PowerCaps->ProcessorMaxThrottle = 100;
2176                         PowerCaps->DiskSpinDown = TRUE;
2177                         PowerCaps->SystemBatteriesPresent = FALSE;
2178                         PowerCaps->BatteriesAreShortTerm = FALSE;
2179                         PowerCaps->BatteryScale[0].Granularity = 0;
2180                         PowerCaps->BatteryScale[0].Capacity = 0;
2181                         PowerCaps->BatteryScale[1].Granularity = 0;
2182                         PowerCaps->BatteryScale[1].Capacity = 0;
2183                         PowerCaps->BatteryScale[2].Granularity = 0;
2184                         PowerCaps->BatteryScale[2].Capacity = 0;
2185                         PowerCaps->AcOnLineWake = PowerSystemUnspecified;
2186                         PowerCaps->SoftLidWake = PowerSystemUnspecified;
2187                         PowerCaps->RtcWake = PowerSystemSleeping1;
2188                         PowerCaps->MinDeviceWakeState = PowerSystemUnspecified;
2189                         PowerCaps->DefaultLowLatencyWake = PowerSystemUnspecified;
2190                         return STATUS_SUCCESS;
2191                 }
2192                 case SystemExecutionState: {
2193                         PULONG ExecutionState = lpOutputBuffer;
2194                         WARN("semi-stub: SystemExecutionState\n"); /* Needed for .NET Framework, but using a FIXME is really noisy. */
2195                         if (lpInputBuffer != NULL)
2196                                 return STATUS_INVALID_PARAMETER;
2197                         /* FIXME: The actual state should be the value set by SetThreadExecutionState which is not currently implemented. */
2198                         *ExecutionState = ES_USER_PRESENT;
2199                         return STATUS_SUCCESS;
2200                 }
2201                 case ProcessorInformation: {
2202                         const int cannedMHz = 1000; /* We fake a 1GHz processor if we can't conjure up real values */
2203                         PROCESSOR_POWER_INFORMATION* cpu_power = lpOutputBuffer;
2204                         int i, out_cpus;
2205
2206                         if ((lpOutputBuffer == NULL) || (nOutputBufferSize == 0))
2207                                 return STATUS_INVALID_PARAMETER;
2208                         out_cpus = NtCurrentTeb()->Peb->NumberOfProcessors;
2209                         if ((nOutputBufferSize / sizeof(PROCESSOR_POWER_INFORMATION)) < out_cpus)
2210                                 return STATUS_BUFFER_TOO_SMALL;
2211 #if defined(linux)
2212                         {
2213                                 char filename[128];
2214                                 FILE* f;
2215
2216                                 for(i = 0; i < out_cpus; i++) {
2217                                         sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq", i);
2218                                         f = fopen(filename, "r");
2219                                         if (f && (fscanf(f, "%d", &cpu_power[i].CurrentMhz) == 1)) {
2220                                                 cpu_power[i].CurrentMhz /= 1000;
2221                                                 fclose(f);
2222                                         }
2223                                         else {
2224                                                 if(i == 0) {
2225                                                         cpu_power[0].CurrentMhz = mhz_from_cpuinfo();
2226                                                         if(cpu_power[0].CurrentMhz == 0)
2227                                                                 cpu_power[0].CurrentMhz = cannedMHz;
2228                                                 }
2229                                                 else
2230                                                         cpu_power[i].CurrentMhz = cpu_power[0].CurrentMhz;
2231                                                 if(f) fclose(f);
2232                                         }
2233
2234                                         sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", i);
2235                                         f = fopen(filename, "r");
2236                                         if (f && (fscanf(f, "%d", &cpu_power[i].MaxMhz) == 1)) {
2237                                                 cpu_power[i].MaxMhz /= 1000;
2238                                                 fclose(f);
2239                                         }
2240                                         else {
2241                                                 cpu_power[i].MaxMhz = cpu_power[i].CurrentMhz;
2242                                                 if(f) fclose(f);
2243                                         }
2244
2245                                         sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_max_freq", i);
2246                                         f = fopen(filename, "r");
2247                                         if(f && (fscanf(f, "%d", &cpu_power[i].MhzLimit) == 1)) {
2248                                                 cpu_power[i].MhzLimit /= 1000;
2249                                                 fclose(f);
2250                                         }
2251                                         else
2252                                         {
2253                                                 cpu_power[i].MhzLimit = cpu_power[i].MaxMhz;
2254                                                 if(f) fclose(f);
2255                                         }
2256
2257                                         cpu_power[i].Number = i;
2258                                         cpu_power[i].MaxIdleState = 0;     /* FIXME */
2259                                         cpu_power[i].CurrentIdleState = 0; /* FIXME */
2260                                 }
2261                         }
2262 #elif defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__DragonFly__)
2263                         {
2264                                 int num;
2265                                 size_t valSize = sizeof(num);
2266                                 if (sysctlbyname("hw.clockrate", &num, &valSize, NULL, 0))
2267                                         num = cannedMHz;
2268                                 for(i = 0; i < out_cpus; i++) {
2269                                         cpu_power[i].CurrentMhz = num;
2270                                         cpu_power[i].MaxMhz = num;
2271                                         cpu_power[i].MhzLimit = num;
2272                                         cpu_power[i].Number = i;
2273                                         cpu_power[i].MaxIdleState = 0;     /* FIXME */
2274                                         cpu_power[i].CurrentIdleState = 0; /* FIXME */
2275                                 }
2276                         }
2277 #elif defined (__APPLE__)
2278                         {
2279                                 size_t valSize;
2280                                 unsigned long long currentMhz;
2281                                 unsigned long long maxMhz;
2282
2283                                 valSize = sizeof(currentMhz);
2284                                 if (!sysctlbyname("hw.cpufrequency", &currentMhz, &valSize, NULL, 0))
2285                                         currentMhz /= 1000000;
2286                                 else
2287                                         currentMhz = cannedMHz;
2288
2289                                 valSize = sizeof(maxMhz);
2290                                 if (!sysctlbyname("hw.cpufrequency_max", &maxMhz, &valSize, NULL, 0))
2291                                         maxMhz /= 1000000;
2292                                 else
2293                                         maxMhz = currentMhz;
2294
2295                                 for(i = 0; i < out_cpus; i++) {
2296                                         cpu_power[i].CurrentMhz = currentMhz;
2297                                         cpu_power[i].MaxMhz = maxMhz;
2298                                         cpu_power[i].MhzLimit = maxMhz;
2299                                         cpu_power[i].Number = i;
2300                                         cpu_power[i].MaxIdleState = 0;     /* FIXME */
2301                                         cpu_power[i].CurrentIdleState = 0; /* FIXME */
2302                                 }
2303                         }
2304 #else
2305                         for(i = 0; i < out_cpus; i++) {
2306                                 cpu_power[i].CurrentMhz = cannedMHz;
2307                                 cpu_power[i].MaxMhz = cannedMHz;
2308                                 cpu_power[i].MhzLimit = cannedMHz;
2309                                 cpu_power[i].Number = i;
2310                                 cpu_power[i].MaxIdleState = 0; /* FIXME */
2311                                 cpu_power[i].CurrentIdleState = 0; /* FIXME */
2312                         }
2313                         WARN("Unable to detect CPU MHz for this platform. Reporting %d MHz.\n", cannedMHz);
2314 #endif
2315                         for(i = 0; i < out_cpus; i++) {
2316                                 TRACE("cpu_power[%d] = %u %u %u %u %u %u\n", i, cpu_power[i].Number,
2317                                           cpu_power[i].MaxMhz, cpu_power[i].CurrentMhz, cpu_power[i].MhzLimit,
2318                                           cpu_power[i].MaxIdleState, cpu_power[i].CurrentIdleState);
2319                         }
2320                         return STATUS_SUCCESS;
2321                 }
2322                 default:
2323                         /* FIXME: Needed by .NET Framework */
2324                         WARN("Unimplemented NtPowerInformation action: %d\n", InformationLevel);
2325                         return STATUS_NOT_IMPLEMENTED;
2326         }
2327 }
2328
2329 /******************************************************************************
2330  *  NtShutdownSystem                            [NTDLL.@]
2331  *
2332  */
2333 NTSTATUS WINAPI NtShutdownSystem(SHUTDOWN_ACTION Action)
2334 {
2335     FIXME("%d\n",Action);
2336     return STATUS_SUCCESS;
2337 }
2338
2339 /******************************************************************************
2340  *  NtAllocateLocallyUniqueId (NTDLL.@)
2341  */
2342 NTSTATUS WINAPI NtAllocateLocallyUniqueId(PLUID Luid)
2343 {
2344     NTSTATUS status;
2345
2346     TRACE("%p\n", Luid);
2347
2348     if (!Luid)
2349         return STATUS_ACCESS_VIOLATION;
2350
2351     SERVER_START_REQ( allocate_locally_unique_id )
2352     {
2353         status = wine_server_call( req );
2354         if (!status)
2355         {
2356             Luid->LowPart = reply->luid.low_part;
2357             Luid->HighPart = reply->luid.high_part;
2358         }
2359     }
2360     SERVER_END_REQ;
2361
2362     return status;
2363 }
2364
2365 /******************************************************************************
2366  *        VerSetConditionMask   (NTDLL.@)
2367  */
2368 ULONGLONG WINAPI VerSetConditionMask( ULONGLONG dwlConditionMask, DWORD dwTypeBitMask,
2369                                       BYTE dwConditionMask)
2370 {
2371     if(dwTypeBitMask == 0)
2372         return dwlConditionMask;
2373     dwConditionMask &= 0x07;
2374     if(dwConditionMask == 0)
2375         return dwlConditionMask;
2376
2377     if(dwTypeBitMask & VER_PRODUCT_TYPE)
2378         dwlConditionMask |= dwConditionMask << 7*3;
2379     else if (dwTypeBitMask & VER_SUITENAME)
2380         dwlConditionMask |= dwConditionMask << 6*3;
2381     else if (dwTypeBitMask & VER_SERVICEPACKMAJOR)
2382         dwlConditionMask |= dwConditionMask << 5*3;
2383     else if (dwTypeBitMask & VER_SERVICEPACKMINOR)
2384         dwlConditionMask |= dwConditionMask << 4*3;
2385     else if (dwTypeBitMask & VER_PLATFORMID)
2386         dwlConditionMask |= dwConditionMask << 3*3;
2387     else if (dwTypeBitMask & VER_BUILDNUMBER)
2388         dwlConditionMask |= dwConditionMask << 2*3;
2389     else if (dwTypeBitMask & VER_MAJORVERSION)
2390         dwlConditionMask |= dwConditionMask << 1*3;
2391     else if (dwTypeBitMask & VER_MINORVERSION)
2392         dwlConditionMask |= dwConditionMask << 0*3;
2393     return dwlConditionMask;
2394 }
2395
2396 /******************************************************************************
2397  *  NtAccessCheckAndAuditAlarm   (NTDLL.@)
2398  *  ZwAccessCheckAndAuditAlarm   (NTDLL.@)
2399  */
2400 NTSTATUS WINAPI NtAccessCheckAndAuditAlarm(PUNICODE_STRING SubsystemName, HANDLE HandleId, PUNICODE_STRING ObjectTypeName,
2401                                            PUNICODE_STRING ObjectName, PSECURITY_DESCRIPTOR SecurityDescriptor,
2402                                            ACCESS_MASK DesiredAccess, PGENERIC_MAPPING GenericMapping, BOOLEAN ObjectCreation,
2403                                            PACCESS_MASK GrantedAccess, PBOOLEAN AccessStatus, PBOOLEAN GenerateOnClose)
2404 {
2405     FIXME("(%s, %p, %s, %p, 0x%08x, %p, %d, %p, %p, %p), stub\n", debugstr_us(SubsystemName), HandleId,
2406           debugstr_us(ObjectTypeName), SecurityDescriptor, DesiredAccess, GenericMapping, ObjectCreation,
2407           GrantedAccess, AccessStatus, GenerateOnClose);
2408
2409     return STATUS_NOT_IMPLEMENTED;
2410 }
2411
2412 /******************************************************************************
2413  *  NtSystemDebugControl   (NTDLL.@)
2414  *  ZwSystemDebugControl   (NTDLL.@)
2415  */
2416 NTSTATUS WINAPI NtSystemDebugControl(SYSDBG_COMMAND command, PVOID inbuffer, ULONG inbuflength, PVOID outbuffer,
2417                                      ULONG outbuflength, PULONG retlength)
2418 {
2419     FIXME("(%d, %p, %d, %p, %d, %p), stub\n", command, inbuffer, inbuflength, outbuffer, outbuflength, retlength);
2420
2421     return STATUS_NOT_IMPLEMENTED;
2422 }