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