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