d3drm: Fix wrong condition.
[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 #define AUTH    0x68747541      /* "Auth" */
815 #define ENTI    0x69746e65      /* "enti" */
816 #define CAMD    0x444d4163      /* "cAMD" */
817
818 #define GENU    0x756e6547      /* "Genu" */
819 #define INEI    0x49656e69      /* "ineI" */
820 #define NTEL    0x6c65746e      /* "ntel" */
821
822 /* Calls cpuid with an eax of 'ax' and returns the 16 bytes in *p
823  * We are compiled with -fPIC, so we can't clobber ebx.
824  */
825 static inline void do_cpuid(unsigned int ax, unsigned int *p)
826 {
827 #ifdef __i386__
828         __asm__("pushl %%ebx\n\t"
829                 "cpuid\n\t"
830                 "movl %%ebx, %%esi\n\t"
831                 "popl %%ebx"
832                 : "=a" (p[0]), "=S" (p[1]), "=c" (p[2]), "=d" (p[3])
833                 :  "0" (ax));
834 #elif defined(__x86_64__)
835         __asm__("push %%rbx\n\t"
836                 "cpuid\n\t"
837                 "movq %%rbx, %%rsi\n\t"
838                 "pop %%rbx"
839                 : "=a" (p[0]), "=S" (p[1]), "=c" (p[2]), "=d" (p[3])
840                 :  "0" (ax));
841 #endif
842 }
843
844 /* From xf86info havecpuid.c 1.11 */
845 static inline int have_cpuid(void)
846 {
847 #ifdef __i386__
848         unsigned int f1, f2;
849         __asm__("pushfl\n\t"
850                 "pushfl\n\t"
851                 "popl %0\n\t"
852                 "movl %0,%1\n\t"
853                 "xorl %2,%0\n\t"
854                 "pushl %0\n\t"
855                 "popfl\n\t"
856                 "pushfl\n\t"
857                 "popl %0\n\t"
858                 "popfl"
859                 : "=&r" (f1), "=&r" (f2)
860                 : "ir" (0x00200000));
861         return ((f1^f2) & 0x00200000) != 0;
862 #elif defined(__x86_64__)
863         return 1;
864 #else
865         return 0;
866 #endif
867 }
868
869 /* Detect if a SSE2 processor is capable of Denormals Are Zero (DAZ) mode.
870  *
871  * This function assumes you have already checked for SSE2/FXSAVE support. */
872 static inline int have_sse_daz_mode(void)
873 {
874 #ifdef __i386__
875     typedef struct DECLSPEC_ALIGN(16) _M128A {
876         ULONGLONG Low;
877         LONGLONG High;
878     } M128A;
879
880     typedef struct _XMM_SAVE_AREA32 {
881         WORD ControlWord;
882         WORD StatusWord;
883         BYTE TagWord;
884         BYTE Reserved1;
885         WORD ErrorOpcode;
886         DWORD ErrorOffset;
887         WORD ErrorSelector;
888         WORD Reserved2;
889         DWORD DataOffset;
890         WORD DataSelector;
891         WORD Reserved3;
892         DWORD MxCsr;
893         DWORD MxCsr_Mask;
894         M128A FloatRegisters[8];
895         M128A XmmRegisters[16];
896         BYTE Reserved4[96];
897     } XMM_SAVE_AREA32;
898
899     /* Intel says we need a zeroed 16-byte aligned buffer */
900     char buffer[512 + 16];
901     XMM_SAVE_AREA32 *state = (XMM_SAVE_AREA32 *)(((ULONG_PTR)buffer + 15) & ~15);
902     memset(buffer, 0, sizeof(buffer));
903
904     __asm__ __volatile__( "fxsave %0" : "=m" (*state) : "m" (*state) );
905
906     return (state->MxCsr_Mask & (1 << 6)) >> 6;
907 #else /* all x86_64 processors include SSE2 with DAZ mode */
908     return 1;
909 #endif
910 }
911
912 static inline void get_cpuinfo(SYSTEM_CPU_INFORMATION* info)
913 {
914     unsigned int regs[4], regs2[4];
915
916     /* We're at least a 386 */
917     info->FeatureSet = CPU_FEATURE_VME | CPU_FEATURE_X86 | CPU_FEATURE_PGE;
918     info->Level = 3;
919
920     if (!have_cpuid()) return;
921
922     do_cpuid(0x00000000, regs);  /* get standard cpuid level and vendor name */
923     if (regs[0]>=0x00000001)   /* Check for supported cpuid version */
924     {
925         do_cpuid(0x00000001, regs2); /* get cpu features */
926
927         if(regs2[3] & (1 << 3 )) info->FeatureSet |= CPU_FEATURE_PSE;
928         if(regs2[3] & (1 << 4 )) info->FeatureSet |= CPU_FEATURE_TSC;
929         if(regs2[3] & (1 << 8 )) info->FeatureSet |= CPU_FEATURE_CX8;
930         if(regs2[3] & (1 << 11)) info->FeatureSet |= CPU_FEATURE_SEP;
931         if(regs2[3] & (1 << 12)) info->FeatureSet |= CPU_FEATURE_MTRR;
932         if(regs2[3] & (1 << 15)) info->FeatureSet |= CPU_FEATURE_CMOV;
933         if(regs2[3] & (1 << 16)) info->FeatureSet |= CPU_FEATURE_PAT;
934         if(regs2[3] & (1 << 23)) info->FeatureSet |= CPU_FEATURE_MMX;
935         if(regs2[3] & (1 << 24)) info->FeatureSet |= CPU_FEATURE_FXSR;
936         if(regs2[3] & (1 << 25)) info->FeatureSet |= CPU_FEATURE_SSE;
937         if(regs2[3] & (1 << 26)) info->FeatureSet |= CPU_FEATURE_SSE2;
938
939         user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED]       = !(regs2[3] & 1);
940         user_shared_data->ProcessorFeatures[PF_RDTSC_INSTRUCTION_AVAILABLE]   = (regs2[3] & (1 << 4 )) >> 4;
941         user_shared_data->ProcessorFeatures[PF_PAE_ENABLED]                   = (regs2[3] & (1 << 6 )) >> 6;
942         user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE_DOUBLE]       = (regs2[3] & (1 << 8 )) >> 8;
943         user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE]    = (regs2[3] & (1 << 23)) >> 23;
944         user_shared_data->ProcessorFeatures[PF_XMMI_INSTRUCTIONS_AVAILABLE]   = (regs2[3] & (1 << 25)) >> 25;
945         user_shared_data->ProcessorFeatures[PF_XMMI64_INSTRUCTIONS_AVAILABLE] = (regs2[3] & (1 << 26)) >> 26;
946         user_shared_data->ProcessorFeatures[PF_SSE3_INSTRUCTIONS_AVAILABLE]   = regs2[2] & 1;
947         user_shared_data->ProcessorFeatures[PF_XSAVE_ENABLED]                 = (regs2[2] & (1 << 27)) >> 27;
948         user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE128]           = (regs2[2] & (1 << 13)) >> 13;
949
950         if((regs2[3] & (1 << 26)) && (regs2[3] & (1 << 24))) /* has SSE2 and FXSAVE/FXRSTOR */
951             user_shared_data->ProcessorFeatures[PF_SSE_DAZ_MODE_AVAILABLE] = have_sse_daz_mode();
952
953         if (regs[1] == AUTH && regs[3] == ENTI && regs[2] == CAMD)
954         {
955             info->Level = (regs2[0] >> 8) & 0xf; /* family */
956             if (info->Level == 0xf)  /* AMD says to add the extended family to the family if family is 0xf */
957                 info->Level += (regs2[0] >> 20) & 0xff;
958
959             /* repack model and stepping to make a "revision" */
960             info->Revision  = ((regs2[0] >> 16) & 0xf) << 12; /* extended model */
961             info->Revision |= ((regs2[0] >> 4 ) & 0xf) << 8;  /* model          */
962             info->Revision |= regs2[0] & 0xf;                 /* stepping       */
963
964             do_cpuid(0x80000000, regs);  /* get vendor cpuid level */
965             if (regs[0] >= 0x80000001)
966             {
967                 do_cpuid(0x80000001, regs2);  /* get vendor features */
968                 user_shared_data->ProcessorFeatures[PF_VIRT_FIRMWARE_ENABLED]        = (regs2[2] & (1 << 2  )) >> 2;
969                 user_shared_data->ProcessorFeatures[PF_NX_ENABLED]                   = (regs2[3] & (1 << 20 )) >> 20;
970                 user_shared_data->ProcessorFeatures[PF_3DNOW_INSTRUCTIONS_AVAILABLE] = (regs2[3] & (1 << 31 )) >> 31;
971                 if(regs2[3] & (1 << 31)) info->FeatureSet |= CPU_FEATURE_3DNOW;
972             }
973         }
974         else if (regs[1] == GENU && regs[3] == INEI && regs[2] == NTEL)
975         {
976             info->Level = ((regs2[0] >> 8) & 0xf) + ((regs2[0] >> 20) & 0xff); /* family + extended family */
977             if(info->Level == 15) info->Level = 6;
978
979             /* repack model and stepping to make a "revision" */
980             info->Revision  = ((regs2[0] >> 16) & 0xf) << 12; /* extended model */
981             info->Revision |= ((regs2[0] >> 4 ) & 0xf) << 8;  /* model          */
982             info->Revision |= regs2[0] & 0xf;                 /* stepping       */
983
984             if(regs2[3] & (1 << 21)) info->FeatureSet |= CPU_FEATURE_DS;
985             user_shared_data->ProcessorFeatures[PF_VIRT_FIRMWARE_ENABLED] = (regs2[2] & (1 << 5 )) >> 5;
986
987             do_cpuid(0x80000000, regs);  /* get vendor cpuid level */
988             if (regs[0] >= 0x80000001)
989             {
990                 do_cpuid(0x80000001, regs2);  /* get vendor features */
991                 user_shared_data->ProcessorFeatures[PF_NX_ENABLED] = (regs2[3] & (1 << 20 )) >> 20;
992             }
993         }
994         else
995         {
996             info->Level = (regs2[0] >> 8) & 0xf; /* family */
997
998             /* repack model and stepping to make a "revision" */
999             info->Revision = ((regs2[0] >> 4 ) & 0xf) << 8;  /* model    */
1000             info->Revision |= regs2[0] & 0xf;                /* stepping */
1001         }
1002     }
1003 }
1004
1005 /******************************************************************
1006  *              fill_cpu_info
1007  *
1008  * inits a couple of places with CPU related information:
1009  * - cached_sci in this file
1010  * - Peb->NumberOfProcessors
1011  * - SharedUserData->ProcessFeatures[] array
1012  */
1013 void fill_cpu_info(void)
1014 {
1015     memset(&cached_sci, 0, sizeof(cached_sci));
1016     /* choose sensible defaults ...
1017      * FIXME: perhaps overridable with precompiler flags?
1018      */
1019 #ifdef __i386__
1020     cached_sci.Architecture     = PROCESSOR_ARCHITECTURE_INTEL;
1021     cached_sci.Level            = 5; /* 586 */
1022 #elif defined(__x86_64__)
1023     cached_sci.Architecture     = PROCESSOR_ARCHITECTURE_AMD64;
1024 #elif defined(__powerpc__)
1025     cached_sci.Architecture     = PROCESSOR_ARCHITECTURE_PPC;
1026 #elif defined(__arm__)
1027     cached_sci.Architecture     = PROCESSOR_ARCHITECTURE_ARM;
1028 #elif defined(__sparc__)
1029     cached_sci.Architecture     = PROCESSOR_ARCHITECTURE_SPARC;
1030 #else
1031 #error Unknown CPU
1032 #endif
1033     cached_sci.Revision   = 0;
1034     cached_sci.Reserved   = 0;
1035     cached_sci.FeatureSet = 0x1fff;
1036
1037     NtCurrentTeb()->Peb->NumberOfProcessors = 1;
1038
1039     /* Hmm, reasonable processor feature defaults? */
1040
1041 #ifdef linux
1042     {
1043         char line[200];
1044         FILE *f = fopen ("/proc/cpuinfo", "r");
1045
1046         if (!f)
1047                 return;
1048         while (fgets(line,200,f) != NULL)
1049         {
1050             char        *s,*value;
1051
1052             /* NOTE: the ':' is the only character we can rely on */
1053             if (!(value = strchr(line,':')))
1054                 continue;
1055
1056             /* terminate the valuename */
1057             s = value - 1;
1058             while ((s >= line) && ((*s == ' ') || (*s == '\t'))) s--;
1059             *(s + 1) = '\0';
1060
1061             /* and strip leading spaces from value */
1062             value += 1;
1063             while (*value==' ') value++;
1064             if ((s = strchr(value,'\n')))
1065                 *s='\0';
1066
1067             if (!strcasecmp(line, "processor"))
1068             {
1069                 /* processor number counts up... */
1070                 unsigned int x;
1071
1072                 if (sscanf(value, "%d",&x))
1073                     if (x + 1 > NtCurrentTeb()->Peb->NumberOfProcessors)
1074                         NtCurrentTeb()->Peb->NumberOfProcessors = x + 1;
1075
1076                 continue;
1077             }
1078             if (!strcasecmp(line, "model"))
1079             {
1080                 /* First part of Revision */
1081                 int     x;
1082
1083                 if (sscanf(value, "%d",&x))
1084                     cached_sci.Revision = cached_sci.Revision | (x << 8);
1085
1086                 continue;
1087             }
1088
1089             /* 2.1 and ARM method */
1090             if (!strcasecmp(line, "cpu family") || !strcasecmp(line, "CPU architecture"))
1091             {
1092                 if (isdigit(value[0]))
1093                 {
1094                     cached_sci.Level = atoi(value);
1095                 }
1096                 continue;
1097             }
1098             /* old 2.0 method */
1099             if (!strcasecmp(line, "cpu"))
1100             {
1101                 if (isdigit(value[0]) && value[1] == '8' && value[2] == '6' && value[3] == 0)
1102                 {
1103                     switch (cached_sci.Level = value[0] - '0')
1104                     {
1105                     case 3:
1106                     case 4:
1107                     case 5:
1108                     case 6:
1109                         break;
1110                     default:
1111                         FIXME("unknown Linux 2.0 cpu family '%s', please report ! (-> setting to 386)\n", value);
1112                         cached_sci.Level = 3;
1113                         break;
1114                     }
1115                 }
1116                 continue;
1117             }
1118             if (!strcasecmp(line, "stepping"))
1119             {
1120                 /* Second part of Revision */
1121                 int     x;
1122
1123                 if (sscanf(value, "%d",&x))
1124                     cached_sci.Revision = cached_sci.Revision | x;
1125                 continue;
1126             }
1127             if (!strcasecmp(line, "fdiv_bug"))
1128             {
1129                 if (!strncasecmp(value, "yes",3))
1130                     user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_PRECISION_ERRATA] = TRUE;
1131                 continue;
1132             }
1133             if (!strcasecmp(line, "fpu"))
1134             {
1135                 if (!strncasecmp(value, "no",2))
1136                     user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED] = TRUE;
1137                 continue;
1138             }
1139             if (!strcasecmp(line, "flags") || !strcasecmp(line, "features"))
1140             {
1141                 if (strstr(value, "cx8"))
1142                     user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE_DOUBLE] = TRUE;
1143                 if (strstr(value, "cx16"))
1144                     user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE128] = TRUE;
1145                 if (strstr(value, "mmx"))
1146                     user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE] = TRUE;
1147                 if (strstr(value, "nx"))
1148                     user_shared_data->ProcessorFeatures[PF_NX_ENABLED] = TRUE;
1149                 if (strstr(value, "tsc"))
1150                     user_shared_data->ProcessorFeatures[PF_RDTSC_INSTRUCTION_AVAILABLE] = TRUE;
1151                 if (strstr(value, "3dnow"))
1152                 {
1153                     user_shared_data->ProcessorFeatures[PF_3DNOW_INSTRUCTIONS_AVAILABLE] = TRUE;
1154                     cached_sci.FeatureSet |= CPU_FEATURE_3DNOW;
1155                 }
1156                 /* This will also catch sse2, but we have sse itself
1157                  * if we have sse2, so no problem */
1158                 if (strstr(value, "sse"))
1159                 {
1160                     user_shared_data->ProcessorFeatures[PF_XMMI_INSTRUCTIONS_AVAILABLE] = TRUE;
1161                     cached_sci.FeatureSet |= CPU_FEATURE_SSE;
1162                 }
1163                 if (strstr(value, "sse2"))
1164                 {
1165                     user_shared_data->ProcessorFeatures[PF_XMMI64_INSTRUCTIONS_AVAILABLE] = TRUE;
1166                     cached_sci.FeatureSet |= CPU_FEATURE_SSE2;
1167                 }
1168                 if (strstr(value, "pni"))
1169                     user_shared_data->ProcessorFeatures[PF_SSE3_INSTRUCTIONS_AVAILABLE] = TRUE;
1170                 if (strstr(value, "pae"))
1171                     user_shared_data->ProcessorFeatures[PF_PAE_ENABLED] = TRUE;
1172                 if (strstr(value, "ht"))
1173                     cached_sci.FeatureSet |= CPU_FEATURE_HTT;
1174                 continue;
1175             }
1176         }
1177         fclose(f);
1178     }
1179 #elif defined (__NetBSD__)
1180     {
1181         int mib[2];
1182         int value;
1183         size_t val_len;
1184         char model[256];
1185         char *cpuclass;
1186         FILE *f = fopen("/var/run/dmesg.boot", "r");
1187
1188         /* first deduce as much as possible from the sysctls */
1189         mib[0] = CTL_MACHDEP;
1190 #ifdef CPU_FPU_PRESENT
1191         mib[1] = CPU_FPU_PRESENT;
1192         val_len = sizeof(value);
1193         if (sysctl(mib, 2, &value, &val_len, NULL, 0) >= 0)
1194             user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED] = !value;
1195 #endif
1196 #ifdef CPU_SSE
1197         mib[1] = CPU_SSE;   /* this should imply MMX */
1198         val_len = sizeof(value);
1199         if (sysctl(mib, 2, &value, &val_len, NULL, 0) >= 0)
1200             if (value) user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE] = TRUE;
1201 #endif
1202 #ifdef CPU_SSE2
1203         mib[1] = CPU_SSE2;  /* this should imply MMX */
1204         val_len = sizeof(value);
1205         if (sysctl(mib, 2, &value, &val_len, NULL, 0) >= 0)
1206             if (value) user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE] = TRUE;
1207 #endif
1208         mib[0] = CTL_HW;
1209         mib[1] = HW_NCPU;
1210         val_len = sizeof(value);
1211         if (sysctl(mib, 2, &value, &val_len, NULL, 0) >= 0)
1212             if (value > NtCurrentTeb()->Peb->NumberOfProcessors)
1213                 NtCurrentTeb()->Peb->NumberOfProcessors = value;
1214         mib[1] = HW_MODEL;
1215         val_len = sizeof(model)-1;
1216         if (sysctl(mib, 2, model, &val_len, NULL, 0) >= 0)
1217         {
1218             model[val_len] = '\0'; /* just in case */
1219             cpuclass = strstr(model, "-class");
1220             if (cpuclass != NULL) {
1221                 while(cpuclass > model && cpuclass[0] != '(') cpuclass--;
1222                 if (!strncmp(cpuclass+1, "386", 3))
1223                 {
1224                     cached_sci.Level= 3;
1225                 }
1226                 if (!strncmp(cpuclass+1, "486", 3))
1227                 {
1228                     cached_sci.Level= 4;
1229                 }
1230                 if (!strncmp(cpuclass+1, "586", 3))
1231                 {
1232                     cached_sci.Level= 5;
1233                 }
1234                 if (!strncmp(cpuclass+1, "686", 3))
1235                 {
1236                     cached_sci.Level= 6;
1237                     /* this should imply MMX */
1238                     user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE] = TRUE;
1239                 }
1240             }
1241         }
1242
1243         /* it may be worth reading from /var/run/dmesg.boot for
1244            additional information such as CX8, MMX and TSC
1245            (however this information should be considered less
1246            reliable than that from the sysctl calls) */
1247         if (f != NULL)
1248         {
1249             while (fgets(model, 255, f) != NULL)
1250             {
1251                 int cpu, features;
1252                 if (sscanf(model, "cpu%d: features %x<", &cpu, &features) == 2)
1253                 {
1254                     /* we could scan the string but it is easier
1255                        to test the bits directly */
1256                     if (features & 0x1)
1257                         user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED] = TRUE;
1258                     if (features & 0x10)
1259                         user_shared_data->ProcessorFeatures[PF_RDTSC_INSTRUCTION_AVAILABLE] = TRUE;
1260                     if (features & 0x100)
1261                         user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE_DOUBLE] = TRUE;
1262                     if (features & 0x800000)
1263                         user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE] = TRUE;
1264
1265                     break;
1266                 }
1267             }
1268             fclose(f);
1269         }
1270     }
1271 #elif defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__DragonFly__)
1272     {
1273         int ret, num;
1274         size_t len;
1275
1276         get_cpuinfo( &cached_sci );
1277
1278         /* Check for OS support of SSE -- Is this used, and should it be sse1 or sse2? */
1279         /*len = sizeof(num);
1280           ret = sysctlbyname("hw.instruction_sse", &num, &len, NULL, 0);
1281           if (!ret)
1282           user_shared_data->ProcessorFeatures[PF_XMMI_INSTRUCTIONS_AVAILABLE] = num;*/
1283
1284         len = sizeof(num);
1285         ret = sysctlbyname("hw.ncpu", &num, &len, NULL, 0);
1286         if (!ret)
1287             NtCurrentTeb()->Peb->NumberOfProcessors = num;
1288     }
1289 #elif defined(__sun)
1290     {
1291         int num = sysconf( _SC_NPROCESSORS_ONLN );
1292
1293         if (num == -1) num = 1;
1294         get_cpuinfo( &cached_sci );
1295         NtCurrentTeb()->Peb->NumberOfProcessors = num;
1296     }
1297 #elif defined (__OpenBSD__)
1298     {
1299         int mib[2], num, ret;
1300         size_t len;
1301
1302         mib[0] = CTL_HW;
1303         mib[1] = HW_NCPU;
1304         len = sizeof(num);
1305
1306         ret = sysctl(mib, 2, &num, &len, NULL, 0);
1307         if (!ret)
1308             NtCurrentTeb()->Peb->NumberOfProcessors = num;
1309     }
1310 #elif defined (__APPLE__)
1311     {
1312         size_t valSize;
1313         int value;
1314         int cputype;
1315         char buffer[1024];
1316
1317         valSize = sizeof(int);
1318         if (sysctlbyname ("hw.optional.floatingpoint", &value, &valSize, NULL, 0) == 0)
1319         {
1320             if (value)
1321                 user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED] = FALSE;
1322             else
1323                 user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED] = TRUE;
1324         }
1325         valSize = sizeof(int);
1326         if (sysctlbyname ("hw.ncpu", &value, &valSize, NULL, 0) == 0)
1327             NtCurrentTeb()->Peb->NumberOfProcessors = value;
1328
1329         /* FIXME: we don't use the "hw.activecpu" value... but the cached one */
1330
1331         valSize = sizeof(int);
1332         if (sysctlbyname ("hw.cputype", &cputype, &valSize, NULL, 0) == 0)
1333         {
1334             switch (cputype)
1335             {
1336             case CPU_TYPE_POWERPC:
1337                 cached_sci.Architecture = PROCESSOR_ARCHITECTURE_PPC;
1338                 valSize = sizeof(int);
1339                 if (sysctlbyname ("hw.cpusubtype", &value, &valSize, NULL, 0) == 0)
1340                 {
1341                     switch (value)
1342                     {
1343                     case CPU_SUBTYPE_POWERPC_601:
1344                     case CPU_SUBTYPE_POWERPC_602:       cached_sci.Level = 1;   break;
1345                     case CPU_SUBTYPE_POWERPC_603:       cached_sci.Level = 3;   break;
1346                     case CPU_SUBTYPE_POWERPC_603e:
1347                     case CPU_SUBTYPE_POWERPC_603ev:     cached_sci.Level = 6;   break;
1348                     case CPU_SUBTYPE_POWERPC_604:       cached_sci.Level = 4;   break;
1349                     case CPU_SUBTYPE_POWERPC_604e:      cached_sci.Level = 9;   break;
1350                     case CPU_SUBTYPE_POWERPC_620:       cached_sci.Level = 20;  break;
1351                     case CPU_SUBTYPE_POWERPC_750:       /* G3/G4 derive from 603 so ... */
1352                     case CPU_SUBTYPE_POWERPC_7400:
1353                     case CPU_SUBTYPE_POWERPC_7450:      cached_sci.Level = 6;   break;
1354                     case CPU_SUBTYPE_POWERPC_970:       cached_sci.Level = 9;
1355                         /* :o) user_shared_data->ProcessorFeatures[PF_ALTIVEC_INSTRUCTIONS_AVAILABLE] ;-) */
1356                         break;
1357                     default: break;
1358                     }
1359                 }
1360                 break; /* CPU_TYPE_POWERPC */
1361             case CPU_TYPE_I386:
1362                 cached_sci.Architecture = PROCESSOR_ARCHITECTURE_INTEL;
1363                 valSize = sizeof(int);
1364                 if (sysctlbyname ("machdep.cpu.family", &value, &valSize, NULL, 0) == 0)
1365                 {
1366                     cached_sci.Level = value;
1367                 }
1368                 valSize = sizeof(int);
1369                 if (sysctlbyname ("machdep.cpu.model", &value, &valSize, NULL, 0) == 0)
1370                     cached_sci.Revision = (value << 8);
1371                 valSize = sizeof(int);
1372                 if (sysctlbyname ("machdep.cpu.stepping", &value, &valSize, NULL, 0) == 0)
1373                     cached_sci.Revision |= value;
1374                 valSize = sizeof(buffer);
1375                 if (sysctlbyname ("machdep.cpu.features", buffer, &valSize, NULL, 0) == 0)
1376                 {
1377                     if (!valSize) FIXME("Buffer not large enough, please increase\n");
1378                     if (strstr(buffer, "CX8"))   user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE_DOUBLE] = TRUE;
1379                     if (strstr(buffer, "CX16"))  user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE128] = TRUE;
1380                     if (strstr(buffer, "MMX"))   user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE] = TRUE;
1381                     if (strstr(buffer, "TSC"))   user_shared_data->ProcessorFeatures[PF_RDTSC_INSTRUCTION_AVAILABLE] = TRUE;
1382                     if (strstr(buffer, "3DNOW")) user_shared_data->ProcessorFeatures[PF_3DNOW_INSTRUCTIONS_AVAILABLE] = TRUE;
1383                     if (strstr(buffer, "SSE"))   user_shared_data->ProcessorFeatures[PF_XMMI_INSTRUCTIONS_AVAILABLE] = TRUE;
1384                     if (strstr(buffer, "SSE2"))  user_shared_data->ProcessorFeatures[PF_XMMI64_INSTRUCTIONS_AVAILABLE] = TRUE;
1385                     if (strstr(buffer, "SSE3"))  user_shared_data->ProcessorFeatures[PF_SSE3_INSTRUCTIONS_AVAILABLE] = TRUE;
1386                     if (strstr(buffer, "PAE"))   user_shared_data->ProcessorFeatures[PF_PAE_ENABLED] = TRUE;
1387                     if (strstr(buffer, "HTT"))   cached_sci.FeatureSet |= CPU_FEATURE_HTT;
1388                 }
1389                 break; /* CPU_TYPE_I386 */
1390             default: break;
1391             } /* switch (cputype) */
1392         }
1393     }
1394 #else
1395     FIXME("not yet supported on this system\n");
1396 #endif
1397     TRACE("<- CPU arch %d, level %d, rev %d, features 0x%x\n",
1398           cached_sci.Architecture, cached_sci.Level, cached_sci.Revision, cached_sci.FeatureSet);
1399 }
1400
1401 #ifdef linux
1402 static inline BOOL logical_proc_info_add_by_id(SYSTEM_LOGICAL_PROCESSOR_INFORMATION *data,
1403         DWORD *len, DWORD max_len, LOGICAL_PROCESSOR_RELATIONSHIP rel, DWORD id, DWORD proc)
1404 {
1405     int i;
1406
1407     for(i=0; i<*len; i++)
1408     {
1409         if(data[i].Relationship!=rel || data[i].u.Reserved[1]!=id)
1410             continue;
1411
1412         data[i].ProcessorMask |= (ULONG_PTR)1<<proc;
1413         return TRUE;
1414     }
1415
1416     if(*len == max_len)
1417         return FALSE;
1418
1419     data[i].Relationship = rel;
1420     data[i].ProcessorMask = (ULONG_PTR)1<<proc;
1421     /* TODO: set processor core flags */
1422     data[i].u.Reserved[0] = 0;
1423     data[i].u.Reserved[1] = id;
1424     *len = i+1;
1425     return TRUE;
1426 }
1427
1428 static inline BOOL logical_proc_info_add_cache(SYSTEM_LOGICAL_PROCESSOR_INFORMATION *data,
1429         DWORD *len, DWORD max_len, ULONG_PTR mask, CACHE_DESCRIPTOR *cache)
1430 {
1431     int i;
1432
1433     for(i=0; i<*len; i++)
1434     {
1435         if(data[i].Relationship==RelationCache && data[i].ProcessorMask==mask
1436                 && data[i].u.Cache.Level==cache->Level && data[i].u.Cache.Type==cache->Type)
1437             return TRUE;
1438     }
1439
1440     if(*len == max_len)
1441         return FALSE;
1442
1443     data[i].Relationship = RelationCache;
1444     data[i].ProcessorMask = mask;
1445     data[i].u.Cache = *cache;
1446     *len = i+1;
1447     return TRUE;
1448 }
1449
1450 static inline BOOL logical_proc_info_add_numa_node(SYSTEM_LOGICAL_PROCESSOR_INFORMATION *data,
1451         DWORD *len, DWORD max_len, ULONG_PTR mask, DWORD node_id)
1452 {
1453     if(*len == max_len)
1454         return FALSE;
1455
1456     data[*len].Relationship = RelationNumaNode;
1457     data[*len].ProcessorMask = mask;
1458     data[*len].u.NumaNode.NodeNumber = node_id;
1459     (*len)++;
1460     return TRUE;
1461 }
1462
1463 static NTSTATUS create_logical_proc_info(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data, DWORD *max_len)
1464 {
1465     static const char core_info[] = "/sys/devices/system/cpu/cpu%d/%s";
1466     static const char cache_info[] = "/sys/devices/system/cpu/cpu%d/cache/index%d/%s";
1467     static const char numa_info[] = "/sys/devices/system/node/node%d/cpumap";
1468
1469     FILE *fcpu_list, *fnuma_list, *f;
1470     DWORD len = 0, beg, end, i, j, r;
1471     char op, name[MAX_PATH];
1472
1473     fcpu_list = fopen("/sys/devices/system/cpu/online", "r");
1474     if(!fcpu_list)
1475         return STATUS_NOT_IMPLEMENTED;
1476
1477     while(!feof(fcpu_list))
1478     {
1479         if(!fscanf(fcpu_list, "%u%c ", &beg, &op))
1480             break;
1481         if(op == '-') fscanf(fcpu_list, "%u%c ", &end, &op);
1482         else end = beg;
1483
1484         for(i=beg; i<=end; i++)
1485         {
1486             if(i > 8*sizeof(ULONG_PTR))
1487             {
1488                 FIXME("skipping logical processor %d\n", i);
1489                 continue;
1490             }
1491
1492             sprintf(name, core_info, i, "core_id");
1493             f = fopen(name, "r");
1494             if(f)
1495             {
1496                 fscanf(f, "%u", &r);
1497                 fclose(f);
1498             }
1499             else r = i;
1500             if(!logical_proc_info_add_by_id(*data, &len, *max_len, RelationProcessorCore, r, i))
1501             {
1502                 SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;
1503
1504                 *max_len *= 2;
1505                 new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *data, *max_len*sizeof(*new_data));
1506                 if(!new_data)
1507                 {
1508                     fclose(fcpu_list);
1509                     return STATUS_NO_MEMORY;
1510                 }
1511
1512                 *data = new_data;
1513                 logical_proc_info_add_by_id(*data, &len, *max_len, RelationProcessorCore, r, i);
1514             }
1515
1516             sprintf(name, core_info, i, "physical_package_id");
1517             f = fopen(name, "r");
1518             if(f)
1519             {
1520                 fscanf(f, "%u", &r);
1521                 fclose(f);
1522             }
1523             else r = 0;
1524             if(!logical_proc_info_add_by_id(*data, &len, *max_len, RelationProcessorPackage, r, i))
1525             {
1526                 SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;
1527
1528                 *max_len *= 2;
1529                 new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *data, *max_len*sizeof(*new_data));
1530                 if(!new_data)
1531                 {
1532                     fclose(fcpu_list);
1533                     return STATUS_NO_MEMORY;
1534                 }
1535
1536                 *data = new_data;
1537                 logical_proc_info_add_by_id(*data, &len, *max_len, RelationProcessorPackage, r, i);
1538             }
1539
1540             for(j=0; j<4; j++)
1541             {
1542                 CACHE_DESCRIPTOR cache;
1543                 ULONG_PTR mask = 0;
1544
1545                 sprintf(name, cache_info, i, j, "shared_cpu_map");
1546                 f = fopen(name, "r");
1547                 if(!f) continue;
1548                 while(!feof(f))
1549                 {
1550                     if(!fscanf(f, "%x%c ", &r, &op))
1551                         break;
1552                     mask = (sizeof(ULONG_PTR)>sizeof(int) ? mask<<(8*sizeof(DWORD)) : 0) + r;
1553                 }
1554                 fclose(f);
1555
1556                 sprintf(name, cache_info, i, j, "level");
1557                 f = fopen(name, "r");
1558                 if(!f) continue;
1559                 fscanf(f, "%u", &r);
1560                 fclose(f);
1561                 cache.Level = r;
1562
1563                 sprintf(name, cache_info, i, j, "ways_of_associativity");
1564                 f = fopen(name, "r");
1565                 if(!f) continue;
1566                 fscanf(f, "%u", &r);
1567                 fclose(f);
1568                 cache.Associativity = r;
1569
1570                 sprintf(name, cache_info, i, j, "coherency_line_size");
1571                 f = fopen(name, "r");
1572                 if(!f) continue;
1573                 fscanf(f, "%u", &r);
1574                 fclose(f);
1575                 cache.LineSize = r;
1576
1577                 sprintf(name, cache_info, i, j, "size");
1578                 f = fopen(name, "r");
1579                 if(!f) continue;
1580                 fscanf(f, "%u%c", &r, &op);
1581                 fclose(f);
1582                 if(op != 'K')
1583                     WARN("unknown cache size %u%c\n", r, op);
1584                 cache.Size = (op=='K' ? r*1024 : r);
1585
1586                 sprintf(name, cache_info, i, j, "type");
1587                 f = fopen(name, "r");
1588                 if(!f) continue;
1589                 fscanf(f, "%s", name);
1590                 fclose(f);
1591                 if(!memcmp(name, "Data", 5))
1592                     cache.Type = CacheData;
1593                 else if(!memcmp(name, "Instruction", 11))
1594                     cache.Type = CacheInstruction;
1595                 else
1596                     cache.Type = CacheUnified;
1597
1598                 if(!logical_proc_info_add_cache(*data, &len, *max_len, mask, &cache))
1599                 {
1600                     SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;
1601
1602                     *max_len *= 2;
1603                     new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *data, *max_len*sizeof(*new_data));
1604                     if(!new_data)
1605                     {
1606                         fclose(fcpu_list);
1607                         return STATUS_NO_MEMORY;
1608                     }
1609
1610                     *data = new_data;
1611                     logical_proc_info_add_cache(*data, &len, *max_len, mask, &cache);
1612                 }
1613             }
1614         }
1615     }
1616     fclose(fcpu_list);
1617
1618     fnuma_list = fopen("/sys/devices/system/node/online", "r");
1619     if(!fnuma_list)
1620     {
1621         ULONG_PTR mask = 0;
1622
1623         for(i=0; i<len; i++)
1624             if((*data)[i].Relationship == RelationProcessorCore)
1625                 mask |= (*data)[i].ProcessorMask;
1626
1627         if(len == *max_len)
1628         {
1629             SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;
1630
1631             *max_len *= 2;
1632             new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *data, *max_len*sizeof(*new_data));
1633             if(!new_data)
1634                 return STATUS_NO_MEMORY;
1635
1636             *data = new_data;
1637         }
1638         logical_proc_info_add_numa_node(*data, &len, *max_len, mask, 0);
1639     }
1640     else
1641     {
1642         while(!feof(fnuma_list))
1643         {
1644             if(!fscanf(fnuma_list, "%u%c ", &beg, &op))
1645                 break;
1646             if(op == '-') fscanf(fnuma_list, "%u%c ", &end, &op);
1647             else end = beg;
1648
1649             for(i=beg; i<=end; i++)
1650             {
1651                 ULONG_PTR mask = 0;
1652
1653                 sprintf(name, numa_info, i);
1654                 f = fopen(name, "r");
1655                 if(!f) continue;
1656                 while(!feof(f))
1657                 {
1658                     if(!fscanf(f, "%x%c ", &r, &op))
1659                         break;
1660                     mask = (sizeof(ULONG_PTR)>sizeof(int) ? mask<<(8*sizeof(DWORD)) : 0) + r;
1661                 }
1662                 fclose(f);
1663
1664                 if(len == *max_len)
1665                 {
1666                     SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;
1667
1668                     *max_len *= 2;
1669                     new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *data, *max_len*sizeof(*new_data));
1670                     if(!new_data)
1671                     {
1672                         fclose(fnuma_list);
1673                         return STATUS_NO_MEMORY;
1674                     }
1675
1676                     *data = new_data;
1677                 }
1678                 logical_proc_info_add_numa_node(*data, &len, *max_len, mask, i);
1679             }
1680         }
1681         fclose(fnuma_list);
1682     }
1683
1684     *max_len = len * sizeof(**data);
1685     return STATUS_SUCCESS;
1686 }
1687 #elif defined(__APPLE__)
1688 static NTSTATUS create_logical_proc_info(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data, DWORD *max_len)
1689 {
1690     DWORD len = 0, i, j, k;
1691     DWORD cores_no, lcpu_no, lcpu_per_core, cores_per_package, assoc;
1692     size_t size;
1693     ULONG_PTR mask;
1694     LONGLONG cache_size, cache_line_size, cache_sharing[10];
1695     CACHE_DESCRIPTOR cache[4];
1696
1697     lcpu_no = NtCurrentTeb()->Peb->NumberOfProcessors;
1698
1699     size = sizeof(cores_no);
1700     if(sysctlbyname("machdep.cpu.core_count", &cores_no, &size, NULL, 0))
1701         cores_no = lcpu_no;
1702
1703     lcpu_per_core = lcpu_no/cores_no;
1704     for(i=0; i<cores_no; i++)
1705     {
1706         mask = 0;
1707         for(j=lcpu_per_core*i; j<lcpu_per_core*(i+1); j++)
1708             mask |= (ULONG_PTR)1<<j;
1709
1710         (*data)[len].Relationship = RelationProcessorCore;
1711         (*data)[len].ProcessorMask = mask;
1712         (*data)[len].u.ProcessorCore.Flags = 0; /* TODO */
1713         len++;
1714     }
1715
1716     size = sizeof(cores_per_package);
1717     if(sysctlbyname("machdep.cpu.cores_per_package", &cores_per_package, &size, NULL, 0))
1718         cores_per_package = lcpu_no;
1719
1720     for(i=0; i<(lcpu_no+cores_per_package-1)/cores_per_package; i++)
1721     {
1722         mask = 0;
1723         for(j=cores_per_package*i; j<cores_per_package*(i+1) && j<lcpu_no; j++)
1724             mask |= (ULONG_PTR)1<<j;
1725
1726         (*data)[len].Relationship = RelationProcessorPackage;
1727         (*data)[len].ProcessorMask = mask;
1728         len++;
1729     }
1730
1731     memset(cache, 0, sizeof(cache));
1732     cache[0].Level = 1;
1733     cache[0].Type = CacheInstruction;
1734     cache[1].Level = 1;
1735     cache[1].Type = CacheData;
1736     cache[2].Level = 2;
1737     cache[2].Type = CacheUnified;
1738     cache[3].Level = 3;
1739     cache[3].Type = CacheUnified;
1740
1741     size = sizeof(cache_line_size);
1742     if(!sysctlbyname("hw.cachelinesize", &cache_line_size, &size, NULL, 0))
1743     {
1744         for(i=0; i<4; i++)
1745             cache[i].LineSize = cache_line_size;
1746     }
1747
1748     /* TODO: set associativity for all caches */
1749     size = sizeof(assoc);
1750     if(!sysctlbyname("machdep.cpu.cache.L2_associativity", &assoc, &size, NULL, 0))
1751         cache[2].Associativity = assoc;
1752
1753     size = sizeof(cache_size);
1754     if(!sysctlbyname("hw.l1icachesize", &cache_size, &size, NULL, 0))
1755         cache[0].Size = cache_size;
1756     size = sizeof(cache_size);
1757     if(!sysctlbyname("hw.l1dcachesize", &cache_size, &size, NULL, 0))
1758         cache[1].Size = cache_size;
1759     size = sizeof(cache_size);
1760     if(!sysctlbyname("hw.l2cachesize", &cache_size, &size, NULL, 0))
1761         cache[2].Size = cache_size;
1762     size = sizeof(cache_size);
1763     if(!sysctlbyname("hw.l3cachesize", &cache_size, &size, NULL, 0))
1764         cache[3].Size = cache_size;
1765
1766     size = sizeof(cache_sharing);
1767     if(!sysctlbyname("hw.cacheconfig", cache_sharing, &size, NULL, 0))
1768     {
1769         for(i=1; i<4 && i<size/sizeof(*cache_sharing); i++)
1770         {
1771             if(!cache_sharing[i] || !cache[i].Size)
1772                 continue;
1773
1774             for(j=0; j<lcpu_no/cache_sharing[i]; j++)
1775             {
1776                 mask = 0;
1777                 for(k=j*cache_sharing[i]; k<lcpu_no && k<(j+1)*cache_sharing[i]; k++)
1778                     mask |= (ULONG_PTR)1<<k;
1779
1780                 if(i==1 && cache[0].Size)
1781                 {
1782                     (*data)[len].Relationship = RelationCache;
1783                     (*data)[len].ProcessorMask = mask;
1784                     (*data)[len].u.Cache = cache[0];
1785                     len++;
1786                 }
1787
1788                 (*data)[len].Relationship = RelationCache;
1789                 (*data)[len].ProcessorMask = mask;
1790                 (*data)[len].u.Cache = cache[i];
1791                 len++;
1792             }
1793         }
1794     }
1795
1796     mask = 0;
1797     for(i=0; i<lcpu_no; i++)
1798         mask |= (ULONG_PTR)1<<i;
1799     (*data)[len].Relationship = RelationNumaNode;
1800     (*data)[len].ProcessorMask = mask;
1801     (*data)[len].u.NumaNode.NodeNumber = 0;
1802     len++;
1803
1804     *max_len = len * sizeof(**data);
1805     return STATUS_SUCCESS;
1806 }
1807 #else
1808 static NTSTATUS create_logical_proc_info(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data, DWORD *max_len)
1809 {
1810     FIXME("stub\n");
1811     return STATUS_NOT_IMPLEMENTED;
1812 }
1813 #endif
1814
1815 /******************************************************************************
1816  * NtQuerySystemInformation [NTDLL.@]
1817  * ZwQuerySystemInformation [NTDLL.@]
1818  *
1819  * ARGUMENTS:
1820  *  SystemInformationClass      Index to a certain information structure
1821  *      SystemTimeAdjustmentInformation SYSTEM_TIME_ADJUSTMENT
1822  *      SystemCacheInformation          SYSTEM_CACHE_INFORMATION
1823  *      SystemConfigurationInformation  CONFIGURATION_INFORMATION
1824  *      observed (class/len):
1825  *              0x0/0x2c
1826  *              0x12/0x18
1827  *              0x2/0x138
1828  *              0x8/0x600
1829  *              0x25/0xc
1830  *  SystemInformation   caller supplies storage for the information structure
1831  *  Length              size of the structure
1832  *  ResultLength        Data written
1833  */
1834 NTSTATUS WINAPI NtQuerySystemInformation(
1835         IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
1836         OUT PVOID SystemInformation,
1837         IN ULONG Length,
1838         OUT PULONG ResultLength)
1839 {
1840     NTSTATUS    ret = STATUS_SUCCESS;
1841     ULONG       len = 0;
1842
1843     TRACE("(0x%08x,%p,0x%08x,%p)\n",
1844           SystemInformationClass,SystemInformation,Length,ResultLength);
1845
1846     switch (SystemInformationClass)
1847     {
1848     case SystemBasicInformation:
1849         {
1850             SYSTEM_BASIC_INFORMATION sbi;
1851
1852             virtual_get_system_info( &sbi );
1853             len = sizeof(sbi);
1854
1855             if ( Length == len)
1856             {
1857                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1858                 else memcpy( SystemInformation, &sbi, len);
1859             }
1860             else ret = STATUS_INFO_LENGTH_MISMATCH;
1861         }
1862         break;
1863     case SystemCpuInformation:
1864         if (Length >= (len = sizeof(cached_sci)))
1865         {
1866             if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1867             else memcpy(SystemInformation, &cached_sci, len);
1868         }
1869         else ret = STATUS_INFO_LENGTH_MISMATCH;
1870         break;
1871     case SystemPerformanceInformation:
1872         {
1873             SYSTEM_PERFORMANCE_INFORMATION spi;
1874             static BOOL fixme_written = FALSE;
1875             FILE *fp;
1876
1877             memset(&spi, 0 , sizeof(spi));
1878             len = sizeof(spi);
1879
1880             spi.Reserved3 = 0x7fffffff; /* Available paged pool memory? */
1881
1882             if ((fp = fopen("/proc/uptime", "r")))
1883             {
1884                 double uptime, idle_time;
1885
1886                 fscanf(fp, "%lf %lf", &uptime, &idle_time);
1887                 fclose(fp);
1888                 spi.IdleTime.QuadPart = 10000000 * idle_time;
1889             }
1890             else
1891             {
1892                 static ULONGLONG idle;
1893                 /* many programs expect IdleTime to change so fake change */
1894                 spi.IdleTime.QuadPart = ++idle;
1895             }
1896
1897             if (Length >= len)
1898             {
1899                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1900                 else memcpy( SystemInformation, &spi, len);
1901             }
1902             else ret = STATUS_INFO_LENGTH_MISMATCH;
1903             if(!fixme_written) {
1904                 FIXME("info_class SYSTEM_PERFORMANCE_INFORMATION\n");
1905                 fixme_written = TRUE;
1906             }
1907         }
1908         break;
1909     case SystemTimeOfDayInformation:
1910         {
1911             SYSTEM_TIMEOFDAY_INFORMATION sti;
1912
1913             memset(&sti, 0 , sizeof(sti));
1914
1915             /* liKeSystemTime, liExpTimeZoneBias, uCurrentTimeZoneId */
1916             sti.liKeBootTime.QuadPart = server_start_time;
1917
1918             if (Length <= sizeof(sti))
1919             {
1920                 len = Length;
1921                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1922                 else memcpy( SystemInformation, &sti, Length);
1923             }
1924             else ret = STATUS_INFO_LENGTH_MISMATCH;
1925         }
1926         break;
1927     case SystemProcessInformation:
1928         {
1929             SYSTEM_PROCESS_INFORMATION* spi = SystemInformation;
1930             SYSTEM_PROCESS_INFORMATION* last = NULL;
1931             HANDLE hSnap = 0;
1932             WCHAR procname[1024];
1933             WCHAR* exename;
1934             DWORD wlen = 0;
1935             DWORD procstructlen = 0;
1936
1937             SERVER_START_REQ( create_snapshot )
1938             {
1939                 req->flags      = SNAP_PROCESS | SNAP_THREAD;
1940                 req->attributes = 0;
1941                 if (!(ret = wine_server_call( req )))
1942                     hSnap = wine_server_ptr_handle( reply->handle );
1943             }
1944             SERVER_END_REQ;
1945             len = 0;
1946             while (ret == STATUS_SUCCESS)
1947             {
1948                 SERVER_START_REQ( next_process )
1949                 {
1950                     req->handle = wine_server_obj_handle( hSnap );
1951                     req->reset = (len == 0);
1952                     wine_server_set_reply( req, procname, sizeof(procname)-sizeof(WCHAR) );
1953                     if (!(ret = wine_server_call( req )))
1954                     {
1955                         /* Make sure procname is 0 terminated */
1956                         procname[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
1957
1958                         /* Get only the executable name, not the path */
1959                         if ((exename = strrchrW(procname, '\\')) != NULL) exename++;
1960                         else exename = procname;
1961
1962                         wlen = (strlenW(exename) + 1) * sizeof(WCHAR);
1963
1964                         procstructlen = sizeof(*spi) + wlen + ((reply->threads - 1) * sizeof(SYSTEM_THREAD_INFORMATION));
1965
1966                         if (Length >= len + procstructlen)
1967                         {
1968                             /* ftCreationTime, ftUserTime, ftKernelTime;
1969                              * vmCounters, ioCounters
1970                              */
1971  
1972                             memset(spi, 0, sizeof(*spi));
1973
1974                             spi->NextEntryOffset = procstructlen - wlen;
1975                             spi->dwThreadCount = reply->threads;
1976
1977                             /* spi->pszProcessName will be set later on */
1978
1979                             spi->dwBasePriority = reply->priority;
1980                             spi->UniqueProcessId = UlongToHandle(reply->pid);
1981                             spi->ParentProcessId = UlongToHandle(reply->ppid);
1982                             spi->HandleCount = reply->handles;
1983
1984                             /* spi->ti will be set later on */
1985
1986                             len += procstructlen;
1987                         }
1988                         else ret = STATUS_INFO_LENGTH_MISMATCH;
1989                     }
1990                 }
1991                 SERVER_END_REQ;
1992  
1993                 if (ret != STATUS_SUCCESS)
1994                 {
1995                     if (ret == STATUS_NO_MORE_FILES) ret = STATUS_SUCCESS;
1996                     break;
1997                 }
1998                 else /* Length is already checked for */
1999                 {
2000                     int     i, j;
2001
2002                     /* set thread info */
2003                     i = j = 0;
2004                     while (ret == STATUS_SUCCESS)
2005                     {
2006                         SERVER_START_REQ( next_thread )
2007                         {
2008                             req->handle = wine_server_obj_handle( hSnap );
2009                             req->reset = (j == 0);
2010                             if (!(ret = wine_server_call( req )))
2011                             {
2012                                 j++;
2013                                 if (UlongToHandle(reply->pid) == spi->UniqueProcessId)
2014                                 {
2015                                     /* ftKernelTime, ftUserTime, ftCreateTime;
2016                                      * dwTickCount, dwStartAddress
2017                                      */
2018
2019                                     memset(&spi->ti[i], 0, sizeof(spi->ti));
2020
2021                                     spi->ti[i].CreateTime.QuadPart = 0xdeadbeef;
2022                                     spi->ti[i].ClientId.UniqueProcess = UlongToHandle(reply->pid);
2023                                     spi->ti[i].ClientId.UniqueThread  = UlongToHandle(reply->tid);
2024                                     spi->ti[i].dwCurrentPriority = reply->base_pri + reply->delta_pri;
2025                                     spi->ti[i].dwBasePriority = reply->base_pri;
2026                                     i++;
2027                                 }
2028                             }
2029                         }
2030                         SERVER_END_REQ;
2031                     }
2032                     if (ret == STATUS_NO_MORE_FILES) ret = STATUS_SUCCESS;
2033
2034                     /* now append process name */
2035                     spi->ProcessName.Buffer = (WCHAR*)((char*)spi + spi->NextEntryOffset);
2036                     spi->ProcessName.Length = wlen - sizeof(WCHAR);
2037                     spi->ProcessName.MaximumLength = wlen;
2038                     memcpy( spi->ProcessName.Buffer, exename, wlen );
2039                     spi->NextEntryOffset += wlen;
2040
2041                     last = spi;
2042                     spi = (SYSTEM_PROCESS_INFORMATION*)((char*)spi + spi->NextEntryOffset);
2043                 }
2044             }
2045             if (ret == STATUS_SUCCESS && last) last->NextEntryOffset = 0;
2046             if (hSnap) NtClose(hSnap);
2047         }
2048         break;
2049     case SystemProcessorPerformanceInformation:
2050         {
2051             SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *sppi = NULL;
2052             unsigned int cpus = 0;
2053             int out_cpus = Length / sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION);
2054
2055             if (out_cpus == 0)
2056             {
2057                 len = 0;
2058                 ret = STATUS_INFO_LENGTH_MISMATCH;
2059                 break;
2060             }
2061             else
2062 #ifdef __APPLE__
2063             {
2064                 processor_cpu_load_info_data_t *pinfo;
2065                 mach_msg_type_number_t info_count;
2066
2067                 if (host_processor_info (mach_host_self (),
2068                                          PROCESSOR_CPU_LOAD_INFO,
2069                                          &cpus,
2070                                          (processor_info_array_t*)&pinfo,
2071                                          &info_count) == 0)
2072                 {
2073                     int i;
2074                     cpus = min(cpus,out_cpus);
2075                     len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
2076                     sppi = RtlAllocateHeap(GetProcessHeap(), 0,len);
2077                     for (i = 0; i < cpus; i++)
2078                     {
2079                         sppi[i].IdleTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_IDLE];
2080                         sppi[i].KernelTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_SYSTEM];
2081                         sppi[i].UserTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_USER];
2082                     }
2083                     vm_deallocate (mach_task_self (), (vm_address_t) pinfo, info_count * sizeof(natural_t));
2084                 }
2085             }
2086 #else
2087             {
2088                 FILE *cpuinfo = fopen("/proc/stat", "r");
2089                 if (cpuinfo)
2090                 {
2091                     unsigned long clk_tck = sysconf(_SC_CLK_TCK);
2092                     unsigned long usr,nice,sys,idle,remainder[8];
2093                     int i, count;
2094                     char name[32];
2095                     char line[255];
2096
2097                     /* first line is combined usage */
2098                     while (fgets(line,255,cpuinfo))
2099                     {
2100                         count = sscanf(line, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
2101                                        name, &usr, &nice, &sys, &idle,
2102                                        &remainder[0], &remainder[1], &remainder[2], &remainder[3],
2103                                        &remainder[4], &remainder[5], &remainder[6], &remainder[7]);
2104
2105                         if (count < 5 || strncmp( name, "cpu", 3 )) break;
2106                         for (i = 0; i + 5 < count; ++i) sys += remainder[i];
2107                         sys += idle;
2108                         usr += nice;
2109                         cpus = atoi( name + 3 ) + 1;
2110                         if (cpus > out_cpus) break;
2111                         len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
2112                         if (sppi)
2113                             sppi = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sppi, len );
2114                         else
2115                             sppi = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, len );
2116
2117                         sppi[cpus-1].IdleTime.QuadPart   = (ULONGLONG)idle * 10000000 / clk_tck;
2118                         sppi[cpus-1].KernelTime.QuadPart = (ULONGLONG)sys * 10000000 / clk_tck;
2119                         sppi[cpus-1].UserTime.QuadPart   = (ULONGLONG)usr * 10000000 / clk_tck;
2120                     }
2121                     fclose(cpuinfo);
2122                 }
2123             }
2124 #endif
2125
2126             if (cpus == 0)
2127             {
2128                 static int i = 1;
2129                 int n;
2130                 cpus = min(NtCurrentTeb()->Peb->NumberOfProcessors, out_cpus);
2131                 len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
2132                 sppi = RtlAllocateHeap(GetProcessHeap(), 0, len);
2133                 FIXME("stub info_class SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION\n");
2134                 /* many programs expect these values to change so fake change */
2135                 for (n = 0; n < cpus; n++)
2136                 {
2137                     sppi[n].KernelTime.QuadPart = 1 * i;
2138                     sppi[n].UserTime.QuadPart   = 2 * i;
2139                     sppi[n].IdleTime.QuadPart   = 3 * i;
2140                 }
2141                 i++;
2142             }
2143
2144             if (Length >= len)
2145             {
2146                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2147                 else memcpy( SystemInformation, sppi, len);
2148             }
2149             else ret = STATUS_INFO_LENGTH_MISMATCH;
2150
2151             RtlFreeHeap(GetProcessHeap(),0,sppi);
2152         }
2153         break;
2154     case SystemModuleInformation:
2155         /* FIXME: should be system-wide */
2156         if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2157         else ret = LdrQueryProcessModuleInformation( SystemInformation, Length, &len );
2158         break;
2159     case SystemHandleInformation:
2160         {
2161             SYSTEM_HANDLE_INFORMATION shi;
2162
2163             memset(&shi, 0, sizeof(shi));
2164             len = sizeof(shi);
2165
2166             if ( Length >= len)
2167             {
2168                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2169                 else memcpy( SystemInformation, &shi, len);
2170             }
2171             else ret = STATUS_INFO_LENGTH_MISMATCH;
2172             FIXME("info_class SYSTEM_HANDLE_INFORMATION\n");
2173         }
2174         break;
2175     case SystemCacheInformation:
2176         {
2177             SYSTEM_CACHE_INFORMATION sci;
2178
2179             memset(&sci, 0, sizeof(sci)); /* FIXME */
2180             len = sizeof(sci);
2181
2182             if ( Length >= len)
2183             {
2184                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2185                 else memcpy( SystemInformation, &sci, len);
2186             }
2187             else ret = STATUS_INFO_LENGTH_MISMATCH;
2188             FIXME("info_class SYSTEM_CACHE_INFORMATION\n");
2189         }
2190         break;
2191     case SystemInterruptInformation:
2192         {
2193             SYSTEM_INTERRUPT_INFORMATION sii;
2194
2195             memset(&sii, 0, sizeof(sii));
2196             len = sizeof(sii);
2197
2198             if ( Length >= len)
2199             {
2200                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2201                 else memcpy( SystemInformation, &sii, len);
2202             }
2203             else ret = STATUS_INFO_LENGTH_MISMATCH;
2204             FIXME("info_class SYSTEM_INTERRUPT_INFORMATION\n");
2205         }
2206         break;
2207     case SystemKernelDebuggerInformation:
2208         {
2209             SYSTEM_KERNEL_DEBUGGER_INFORMATION skdi;
2210
2211             skdi.DebuggerEnabled = FALSE;
2212             skdi.DebuggerNotPresent = TRUE;
2213             len = sizeof(skdi);
2214
2215             if ( Length >= len)
2216             {
2217                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2218                 else memcpy( SystemInformation, &skdi, len);
2219             }
2220             else ret = STATUS_INFO_LENGTH_MISMATCH;
2221         }
2222         break;
2223     case SystemRegistryQuotaInformation:
2224         {
2225             /* Something to do with the size of the registry             *
2226              * Since we don't have a size limitation, fake it            *
2227              * This is almost certainly wrong.                           *
2228              * This sets each of the three words in the struct to 32 MB, *
2229              * which is enough to make the IE 5 installer happy.         */
2230             SYSTEM_REGISTRY_QUOTA_INFORMATION srqi;
2231
2232             srqi.RegistryQuotaAllowed = 0x2000000;
2233             srqi.RegistryQuotaUsed = 0x200000;
2234             srqi.Reserved1 = (void*)0x200000;
2235             len = sizeof(srqi);
2236
2237             if ( Length >= len)
2238             {
2239                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2240                 else
2241                 {
2242                     FIXME("SystemRegistryQuotaInformation: faking max registry size of 32 MB\n");
2243                     memcpy( SystemInformation, &srqi, len);
2244                 }
2245             }
2246             else ret = STATUS_INFO_LENGTH_MISMATCH;
2247         }
2248         break;
2249     case SystemLogicalProcessorInformation:
2250         {
2251             SYSTEM_LOGICAL_PROCESSOR_INFORMATION *buf;
2252
2253             /* Each logical processor may use up to 7 entries in returned table:
2254              * core, numa node, package, L1i, L1d, L2, L3 */
2255             len = 7 * NtCurrentTeb()->Peb->NumberOfProcessors;
2256             buf = RtlAllocateHeap(GetProcessHeap(), 0, len * sizeof(*buf));
2257             if(!buf)
2258             {
2259                 ret = STATUS_NO_MEMORY;
2260                 break;
2261             }
2262
2263             ret = create_logical_proc_info(&buf, &len);
2264             if( ret != STATUS_SUCCESS )
2265             {
2266                 RtlFreeHeap(GetProcessHeap(), 0, buf);
2267                 break;
2268             }
2269
2270             if( Length >= len)
2271             {
2272                 if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
2273                 else memcpy( SystemInformation, buf, len);
2274             }
2275             else ret = STATUS_INFO_LENGTH_MISMATCH;
2276             RtlFreeHeap(GetProcessHeap(), 0, buf);
2277         }
2278         break;
2279     default:
2280         FIXME("(0x%08x,%p,0x%08x,%p) stub\n",
2281               SystemInformationClass,SystemInformation,Length,ResultLength);
2282
2283         /* Several Information Classes are not implemented on Windows and return 2 different values 
2284          * STATUS_NOT_IMPLEMENTED or STATUS_INVALID_INFO_CLASS
2285          * in 95% of the cases it's STATUS_INVALID_INFO_CLASS, so use this as the default
2286         */
2287         ret = STATUS_INVALID_INFO_CLASS;
2288     }
2289
2290     if (ResultLength) *ResultLength = len;
2291
2292     return ret;
2293 }
2294
2295 /******************************************************************************
2296  * NtSetSystemInformation [NTDLL.@]
2297  * ZwSetSystemInformation [NTDLL.@]
2298  */
2299 NTSTATUS WINAPI NtSetSystemInformation(SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG Length)
2300 {
2301     FIXME("(0x%08x,%p,0x%08x) stub\n",SystemInformationClass,SystemInformation,Length);
2302     return STATUS_SUCCESS;
2303 }
2304
2305 /******************************************************************************
2306  *  NtCreatePagingFile          [NTDLL.@]
2307  *  ZwCreatePagingFile          [NTDLL.@]
2308  */
2309 NTSTATUS WINAPI NtCreatePagingFile(
2310         PUNICODE_STRING PageFileName,
2311         PLARGE_INTEGER MinimumSize,
2312         PLARGE_INTEGER MaximumSize,
2313         PLARGE_INTEGER ActualSize)
2314 {
2315     FIXME("(%p %p %p %p) stub\n", PageFileName, MinimumSize, MaximumSize, ActualSize);
2316     return STATUS_SUCCESS;
2317 }
2318
2319 /******************************************************************************
2320  *  NtDisplayString                             [NTDLL.@]
2321  *
2322  * writes a string to the nt-textmode screen eg. during startup
2323  */
2324 NTSTATUS WINAPI NtDisplayString ( PUNICODE_STRING string )
2325 {
2326     STRING stringA;
2327     NTSTATUS ret;
2328
2329     if (!(ret = RtlUnicodeStringToAnsiString( &stringA, string, TRUE )))
2330     {
2331         MESSAGE( "%.*s", stringA.Length, stringA.Buffer );
2332         RtlFreeAnsiString( &stringA );
2333     }
2334     return ret;
2335 }
2336
2337 /******************************************************************************
2338  *  NtInitiatePowerAction                       [NTDLL.@]
2339  *
2340  */
2341 NTSTATUS WINAPI NtInitiatePowerAction(
2342         IN POWER_ACTION SystemAction,
2343         IN SYSTEM_POWER_STATE MinSystemState,
2344         IN ULONG Flags,
2345         IN BOOLEAN Asynchronous)
2346 {
2347         FIXME("(%d,%d,0x%08x,%d),stub\n",
2348                 SystemAction,MinSystemState,Flags,Asynchronous);
2349         return STATUS_NOT_IMPLEMENTED;
2350 }
2351
2352 #ifdef linux
2353 /* Fallback using /proc/cpuinfo for Linux systems without cpufreq. For
2354  * most distributions on recent enough hardware, this is only likely to
2355  * happen while running in virtualized environments such as QEMU. */
2356 static ULONG mhz_from_cpuinfo(void)
2357 {
2358     char line[512];
2359     char *s, *value;
2360     double cmz = 0;
2361     FILE* f = fopen("/proc/cpuinfo", "r");
2362     if(f) {
2363         while (fgets(line, sizeof(line), f) != NULL) {
2364             if (!(value = strchr(line,':')))
2365                 continue;
2366             s = value - 1;
2367             while ((s >= line) && isspace(*s)) s--;
2368             *(s + 1) = '\0';
2369             value++;
2370             if (!strcasecmp(line, "cpu MHz")) {
2371                 sscanf(value, " %lf", &cmz);
2372                 break;
2373             }
2374         }
2375         fclose(f);
2376     }
2377     return cmz;
2378 }
2379 #endif
2380
2381 /******************************************************************************
2382  *  NtPowerInformation                          [NTDLL.@]
2383  *
2384  */
2385 NTSTATUS WINAPI NtPowerInformation(
2386         IN POWER_INFORMATION_LEVEL InformationLevel,
2387         IN PVOID lpInputBuffer,
2388         IN ULONG nInputBufferSize,
2389         IN PVOID lpOutputBuffer,
2390         IN ULONG nOutputBufferSize)
2391 {
2392         TRACE("(%d,%p,%d,%p,%d)\n",
2393                 InformationLevel,lpInputBuffer,nInputBufferSize,lpOutputBuffer,nOutputBufferSize);
2394         switch(InformationLevel) {
2395                 case SystemPowerCapabilities: {
2396                         PSYSTEM_POWER_CAPABILITIES PowerCaps = lpOutputBuffer;
2397                         FIXME("semi-stub: SystemPowerCapabilities\n");
2398                         if (nOutputBufferSize < sizeof(SYSTEM_POWER_CAPABILITIES))
2399                                 return STATUS_BUFFER_TOO_SMALL;
2400                         /* FIXME: These values are based off a native XP desktop, should probably use APM/ACPI to get the 'real' values */
2401                         PowerCaps->PowerButtonPresent = TRUE;
2402                         PowerCaps->SleepButtonPresent = FALSE;
2403                         PowerCaps->LidPresent = FALSE;
2404                         PowerCaps->SystemS1 = TRUE;
2405                         PowerCaps->SystemS2 = FALSE;
2406                         PowerCaps->SystemS3 = FALSE;
2407                         PowerCaps->SystemS4 = TRUE;
2408                         PowerCaps->SystemS5 = TRUE;
2409                         PowerCaps->HiberFilePresent = TRUE;
2410                         PowerCaps->FullWake = TRUE;
2411                         PowerCaps->VideoDimPresent = FALSE;
2412                         PowerCaps->ApmPresent = FALSE;
2413                         PowerCaps->UpsPresent = FALSE;
2414                         PowerCaps->ThermalControl = FALSE;
2415                         PowerCaps->ProcessorThrottle = FALSE;
2416                         PowerCaps->ProcessorMinThrottle = 100;
2417                         PowerCaps->ProcessorMaxThrottle = 100;
2418                         PowerCaps->DiskSpinDown = TRUE;
2419                         PowerCaps->SystemBatteriesPresent = FALSE;
2420                         PowerCaps->BatteriesAreShortTerm = FALSE;
2421                         PowerCaps->BatteryScale[0].Granularity = 0;
2422                         PowerCaps->BatteryScale[0].Capacity = 0;
2423                         PowerCaps->BatteryScale[1].Granularity = 0;
2424                         PowerCaps->BatteryScale[1].Capacity = 0;
2425                         PowerCaps->BatteryScale[2].Granularity = 0;
2426                         PowerCaps->BatteryScale[2].Capacity = 0;
2427                         PowerCaps->AcOnLineWake = PowerSystemUnspecified;
2428                         PowerCaps->SoftLidWake = PowerSystemUnspecified;
2429                         PowerCaps->RtcWake = PowerSystemSleeping1;
2430                         PowerCaps->MinDeviceWakeState = PowerSystemUnspecified;
2431                         PowerCaps->DefaultLowLatencyWake = PowerSystemUnspecified;
2432                         return STATUS_SUCCESS;
2433                 }
2434                 case SystemExecutionState: {
2435                         PULONG ExecutionState = lpOutputBuffer;
2436                         WARN("semi-stub: SystemExecutionState\n"); /* Needed for .NET Framework, but using a FIXME is really noisy. */
2437                         if (lpInputBuffer != NULL)
2438                                 return STATUS_INVALID_PARAMETER;
2439                         /* FIXME: The actual state should be the value set by SetThreadExecutionState which is not currently implemented. */
2440                         *ExecutionState = ES_USER_PRESENT;
2441                         return STATUS_SUCCESS;
2442                 }
2443                 case ProcessorInformation: {
2444                         const int cannedMHz = 1000; /* We fake a 1GHz processor if we can't conjure up real values */
2445                         PROCESSOR_POWER_INFORMATION* cpu_power = lpOutputBuffer;
2446                         int i, out_cpus;
2447
2448                         if ((lpOutputBuffer == NULL) || (nOutputBufferSize == 0))
2449                                 return STATUS_INVALID_PARAMETER;
2450                         out_cpus = NtCurrentTeb()->Peb->NumberOfProcessors;
2451                         if ((nOutputBufferSize / sizeof(PROCESSOR_POWER_INFORMATION)) < out_cpus)
2452                                 return STATUS_BUFFER_TOO_SMALL;
2453 #if defined(linux)
2454                         {
2455                                 char filename[128];
2456                                 FILE* f;
2457
2458                                 for(i = 0; i < out_cpus; i++) {
2459                                         sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq", i);
2460                                         f = fopen(filename, "r");
2461                                         if (f && (fscanf(f, "%d", &cpu_power[i].CurrentMhz) == 1)) {
2462                                                 cpu_power[i].CurrentMhz /= 1000;
2463                                                 fclose(f);
2464                                         }
2465                                         else {
2466                                                 if(i == 0) {
2467                                                         cpu_power[0].CurrentMhz = mhz_from_cpuinfo();
2468                                                         if(cpu_power[0].CurrentMhz == 0)
2469                                                                 cpu_power[0].CurrentMhz = cannedMHz;
2470                                                 }
2471                                                 else
2472                                                         cpu_power[i].CurrentMhz = cpu_power[0].CurrentMhz;
2473                                                 if(f) fclose(f);
2474                                         }
2475
2476                                         sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", i);
2477                                         f = fopen(filename, "r");
2478                                         if (f && (fscanf(f, "%d", &cpu_power[i].MaxMhz) == 1)) {
2479                                                 cpu_power[i].MaxMhz /= 1000;
2480                                                 fclose(f);
2481                                         }
2482                                         else {
2483                                                 cpu_power[i].MaxMhz = cpu_power[i].CurrentMhz;
2484                                                 if(f) fclose(f);
2485                                         }
2486
2487                                         sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_max_freq", i);
2488                                         f = fopen(filename, "r");
2489                                         if(f && (fscanf(f, "%d", &cpu_power[i].MhzLimit) == 1)) {
2490                                                 cpu_power[i].MhzLimit /= 1000;
2491                                                 fclose(f);
2492                                         }
2493                                         else
2494                                         {
2495                                                 cpu_power[i].MhzLimit = cpu_power[i].MaxMhz;
2496                                                 if(f) fclose(f);
2497                                         }
2498
2499                                         cpu_power[i].Number = i;
2500                                         cpu_power[i].MaxIdleState = 0;     /* FIXME */
2501                                         cpu_power[i].CurrentIdleState = 0; /* FIXME */
2502                                 }
2503                         }
2504 #elif defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__DragonFly__)
2505                         {
2506                                 int num;
2507                                 size_t valSize = sizeof(num);
2508                                 if (sysctlbyname("hw.clockrate", &num, &valSize, NULL, 0))
2509                                         num = cannedMHz;
2510                                 for(i = 0; i < out_cpus; i++) {
2511                                         cpu_power[i].CurrentMhz = num;
2512                                         cpu_power[i].MaxMhz = num;
2513                                         cpu_power[i].MhzLimit = num;
2514                                         cpu_power[i].Number = i;
2515                                         cpu_power[i].MaxIdleState = 0;     /* FIXME */
2516                                         cpu_power[i].CurrentIdleState = 0; /* FIXME */
2517                                 }
2518                         }
2519 #elif defined (__APPLE__)
2520                         {
2521                                 size_t valSize;
2522                                 unsigned long long currentMhz;
2523                                 unsigned long long maxMhz;
2524
2525                                 valSize = sizeof(currentMhz);
2526                                 if (!sysctlbyname("hw.cpufrequency", &currentMhz, &valSize, NULL, 0))
2527                                         currentMhz /= 1000000;
2528                                 else
2529                                         currentMhz = cannedMHz;
2530
2531                                 valSize = sizeof(maxMhz);
2532                                 if (!sysctlbyname("hw.cpufrequency_max", &maxMhz, &valSize, NULL, 0))
2533                                         maxMhz /= 1000000;
2534                                 else
2535                                         maxMhz = currentMhz;
2536
2537                                 for(i = 0; i < out_cpus; i++) {
2538                                         cpu_power[i].CurrentMhz = currentMhz;
2539                                         cpu_power[i].MaxMhz = maxMhz;
2540                                         cpu_power[i].MhzLimit = maxMhz;
2541                                         cpu_power[i].Number = i;
2542                                         cpu_power[i].MaxIdleState = 0;     /* FIXME */
2543                                         cpu_power[i].CurrentIdleState = 0; /* FIXME */
2544                                 }
2545                         }
2546 #else
2547                         for(i = 0; i < out_cpus; i++) {
2548                                 cpu_power[i].CurrentMhz = cannedMHz;
2549                                 cpu_power[i].MaxMhz = cannedMHz;
2550                                 cpu_power[i].MhzLimit = cannedMHz;
2551                                 cpu_power[i].Number = i;
2552                                 cpu_power[i].MaxIdleState = 0; /* FIXME */
2553                                 cpu_power[i].CurrentIdleState = 0; /* FIXME */
2554                         }
2555                         WARN("Unable to detect CPU MHz for this platform. Reporting %d MHz.\n", cannedMHz);
2556 #endif
2557                         for(i = 0; i < out_cpus; i++) {
2558                                 TRACE("cpu_power[%d] = %u %u %u %u %u %u\n", i, cpu_power[i].Number,
2559                                           cpu_power[i].MaxMhz, cpu_power[i].CurrentMhz, cpu_power[i].MhzLimit,
2560                                           cpu_power[i].MaxIdleState, cpu_power[i].CurrentIdleState);
2561                         }
2562                         return STATUS_SUCCESS;
2563                 }
2564                 default:
2565                         /* FIXME: Needed by .NET Framework */
2566                         WARN("Unimplemented NtPowerInformation action: %d\n", InformationLevel);
2567                         return STATUS_NOT_IMPLEMENTED;
2568         }
2569 }
2570
2571 /******************************************************************************
2572  *  NtShutdownSystem                            [NTDLL.@]
2573  *
2574  */
2575 NTSTATUS WINAPI NtShutdownSystem(SHUTDOWN_ACTION Action)
2576 {
2577     FIXME("%d\n",Action);
2578     return STATUS_SUCCESS;
2579 }
2580
2581 /******************************************************************************
2582  *  NtAllocateLocallyUniqueId (NTDLL.@)
2583  */
2584 NTSTATUS WINAPI NtAllocateLocallyUniqueId(PLUID Luid)
2585 {
2586     NTSTATUS status;
2587
2588     TRACE("%p\n", Luid);
2589
2590     if (!Luid)
2591         return STATUS_ACCESS_VIOLATION;
2592
2593     SERVER_START_REQ( allocate_locally_unique_id )
2594     {
2595         status = wine_server_call( req );
2596         if (!status)
2597         {
2598             Luid->LowPart = reply->luid.low_part;
2599             Luid->HighPart = reply->luid.high_part;
2600         }
2601     }
2602     SERVER_END_REQ;
2603
2604     return status;
2605 }
2606
2607 /******************************************************************************
2608  *        VerSetConditionMask   (NTDLL.@)
2609  */
2610 ULONGLONG WINAPI VerSetConditionMask( ULONGLONG dwlConditionMask, DWORD dwTypeBitMask,
2611                                       BYTE dwConditionMask)
2612 {
2613     if(dwTypeBitMask == 0)
2614         return dwlConditionMask;
2615     dwConditionMask &= 0x07;
2616     if(dwConditionMask == 0)
2617         return dwlConditionMask;
2618
2619     if(dwTypeBitMask & VER_PRODUCT_TYPE)
2620         dwlConditionMask |= dwConditionMask << 7*3;
2621     else if (dwTypeBitMask & VER_SUITENAME)
2622         dwlConditionMask |= dwConditionMask << 6*3;
2623     else if (dwTypeBitMask & VER_SERVICEPACKMAJOR)
2624         dwlConditionMask |= dwConditionMask << 5*3;
2625     else if (dwTypeBitMask & VER_SERVICEPACKMINOR)
2626         dwlConditionMask |= dwConditionMask << 4*3;
2627     else if (dwTypeBitMask & VER_PLATFORMID)
2628         dwlConditionMask |= dwConditionMask << 3*3;
2629     else if (dwTypeBitMask & VER_BUILDNUMBER)
2630         dwlConditionMask |= dwConditionMask << 2*3;
2631     else if (dwTypeBitMask & VER_MAJORVERSION)
2632         dwlConditionMask |= dwConditionMask << 1*3;
2633     else if (dwTypeBitMask & VER_MINORVERSION)
2634         dwlConditionMask |= dwConditionMask << 0*3;
2635     return dwlConditionMask;
2636 }
2637
2638 /******************************************************************************
2639  *  NtAccessCheckAndAuditAlarm   (NTDLL.@)
2640  *  ZwAccessCheckAndAuditAlarm   (NTDLL.@)
2641  */
2642 NTSTATUS WINAPI NtAccessCheckAndAuditAlarm(PUNICODE_STRING SubsystemName, HANDLE HandleId, PUNICODE_STRING ObjectTypeName,
2643                                            PUNICODE_STRING ObjectName, PSECURITY_DESCRIPTOR SecurityDescriptor,
2644                                            ACCESS_MASK DesiredAccess, PGENERIC_MAPPING GenericMapping, BOOLEAN ObjectCreation,
2645                                            PACCESS_MASK GrantedAccess, PBOOLEAN AccessStatus, PBOOLEAN GenerateOnClose)
2646 {
2647     FIXME("(%s, %p, %s, %p, 0x%08x, %p, %d, %p, %p, %p), stub\n", debugstr_us(SubsystemName), HandleId,
2648           debugstr_us(ObjectTypeName), SecurityDescriptor, DesiredAccess, GenericMapping, ObjectCreation,
2649           GrantedAccess, AccessStatus, GenerateOnClose);
2650
2651     return STATUS_NOT_IMPLEMENTED;
2652 }
2653
2654 /******************************************************************************
2655  *  NtSystemDebugControl   (NTDLL.@)
2656  *  ZwSystemDebugControl   (NTDLL.@)
2657  */
2658 NTSTATUS WINAPI NtSystemDebugControl(SYSDBG_COMMAND command, PVOID inbuffer, ULONG inbuflength, PVOID outbuffer,
2659                                      ULONG outbuflength, PULONG retlength)
2660 {
2661     FIXME("(%d, %p, %d, %p, %d, %p), stub\n", command, inbuffer, inbuflength, outbuffer, outbuflength, retlength);
2662
2663     return STATUS_NOT_IMPLEMENTED;
2664 }