nt.c 85.7 KB
Newer Older
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 10 11 12 13 14 15 16 17 18 19 20
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include "config.h"
#include "wine/port.h"

#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#ifdef HAVE_SYS_SYSCTL_H
# include <sys/sysctl.h>
#endif
#ifdef HAVE_MACHINE_CPU_H
# include <machine/cpu.h>
#endif
#ifdef HAVE_MACH_MACHINE_H
# include <mach/machine.h>
#endif

#include <ctype.h>
#include <string.h>
42
#include <stdarg.h>
43
#include <stdio.h>
44
#include <stdlib.h>
45 46 47
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
48
#include <time.h>
49

50
#define NONAMELESSUNION
51 52
#include "ntstatus.h"
#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"
Juergen Schmied's avatar
Juergen Schmied committed
60

61 62 63 64 65 66
#ifdef __APPLE__
#include <mach/mach_init.h>
#include <mach/mach_host.h>
#include <mach/vm_map.h>
#endif

67
WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
68

Juergen Schmied's avatar
Juergen Schmied committed
69 70 71 72
/*
 *	Token
 */

73
/******************************************************************************
74
 *  NtDuplicateToken		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
75
 *  ZwDuplicateToken		[NTDLL.@]
76
 */
Juergen Schmied's avatar
Juergen Schmied committed
77 78 79 80 81 82 83
NTSTATUS WINAPI NtDuplicateToken(
        IN HANDLE ExistingToken,
        IN ACCESS_MASK DesiredAccess,
        IN POBJECT_ATTRIBUTES ObjectAttributes,
        IN SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
        IN TOKEN_TYPE TokenType,
        OUT PHANDLE NewToken)
84
{
85 86
    NTSTATUS status;

87 88 89
    TRACE("(%p,0x%08x,%s,0x%08x,0x%08x,%p)\n",
          ExistingToken, DesiredAccess, debugstr_ObjectAttributes(ObjectAttributes),
          ImpersonationLevel, TokenType, NewToken);
90

91 92 93 94 95 96 97 98 99 100
    if (ObjectAttributes && ObjectAttributes->SecurityQualityOfService)
    {
        SECURITY_QUALITY_OF_SERVICE *SecurityQOS = ObjectAttributes->SecurityQualityOfService;
        TRACE("ObjectAttributes->SecurityQualityOfService = {%d, %d, %d, %s}\n",
            SecurityQOS->Length, SecurityQOS->ImpersonationLevel,
            SecurityQOS->ContextTrackingMode,
            SecurityQOS->EffectiveOnly ? "TRUE" : "FALSE");
        ImpersonationLevel = SecurityQOS->ImpersonationLevel;
    }

101 102
    SERVER_START_REQ( duplicate_token )
    {
103
        req->handle              = wine_server_obj_handle( ExistingToken );
104 105 106
        req->access              = DesiredAccess;
        req->attributes          = ObjectAttributes ? ObjectAttributes->Attributes : 0;
        req->primary             = (TokenType == TokenPrimary);
107 108
        req->impersonation_level = ImpersonationLevel;
        status = wine_server_call( req );
109
        if (!status) *NewToken = wine_server_ptr_handle( reply->new_handle );
110 111 112 113
    }
    SERVER_END_REQ;

    return status;
114 115 116
}

/******************************************************************************
117
 *  NtOpenProcessToken		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
118
 *  ZwOpenProcessToken		[NTDLL.@]
119
 */
Juergen Schmied's avatar
Juergen Schmied committed
120 121
NTSTATUS WINAPI NtOpenProcessToken(
	HANDLE ProcessHandle,
122 123
	DWORD DesiredAccess,
	HANDLE *TokenHandle)
124 125 126 127 128 129 130 131 132 133
{
    return NtOpenProcessTokenEx( ProcessHandle, DesiredAccess, 0, TokenHandle );
}

/******************************************************************************
 *  NtOpenProcessTokenEx   [NTDLL.@]
 *  ZwOpenProcessTokenEx   [NTDLL.@]
 */
NTSTATUS WINAPI NtOpenProcessTokenEx( HANDLE process, DWORD access, DWORD attributes,
                                      HANDLE *handle )
134
{
135 136
    NTSTATUS ret;

137
    TRACE("(%p,0x%08x,0x%08x,%p)\n", process, access, attributes, handle);
138 139 140

    SERVER_START_REQ( open_token )
    {
141
        req->handle     = wine_server_obj_handle( process );
142 143
        req->access     = access;
        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 149
    }
    SERVER_END_REQ;
    return ret;
150 151 152
}

/******************************************************************************
153
 *  NtOpenThreadToken		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
154
 *  ZwOpenThreadToken		[NTDLL.@]
155
 */
Juergen Schmied's avatar
Juergen Schmied committed
156 157
NTSTATUS WINAPI NtOpenThreadToken(
	HANDLE ThreadHandle,
158
	DWORD DesiredAccess,
Juergen Schmied's avatar
Juergen Schmied committed
159
	BOOLEAN OpenAsSelf,
160
	HANDLE *TokenHandle)
161 162 163 164 165 166 167 168 169 170
{
    return NtOpenThreadTokenEx( ThreadHandle, DesiredAccess, OpenAsSelf, 0, TokenHandle );
}

/******************************************************************************
 *  NtOpenThreadTokenEx   [NTDLL.@]
 *  ZwOpenThreadTokenEx   [NTDLL.@]
 */
NTSTATUS WINAPI NtOpenThreadTokenEx( HANDLE thread, DWORD access, BOOLEAN as_self, DWORD attributes,
                                     HANDLE *handle )
Juergen Schmied's avatar
Juergen Schmied committed
171
{
172 173
    NTSTATUS ret;

174
    TRACE("(%p,0x%08x,%u,0x%08x,%p)\n", thread, access, as_self, attributes, handle );
175 176 177

    SERVER_START_REQ( open_token )
    {
178
        req->handle     = wine_server_obj_handle( thread );
179 180
        req->access     = access;
        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 187 188
    }
    SERVER_END_REQ;

    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 201 202 203 204
	IN PTOKEN_PRIVILEGES NewState,
	IN DWORD BufferLength,
	OUT PTOKEN_PRIVILEGES PreviousState,
	OUT PDWORD ReturnLength)
{
205 206
    NTSTATUS ret;

207
    TRACE("(%p,0x%08x,%p,0x%08x,%p,%p)\n",
208 209 210 211
        TokenHandle, DisableAllPrivileges, NewState, BufferLength, PreviousState, ReturnLength);

    SERVER_START_REQ( adjust_token_privileges )
    {
212
        req->handle = wine_server_obj_handle( TokenHandle );
213 214 215 216
        req->disable_all = DisableAllPrivileges;
        req->get_modified_state = (PreviousState != NULL);
        if (!DisableAllPrivileges)
        {
217
            wine_server_add_data( req, NewState->Privileges,
218 219 220
                                  NewState->PrivilegeCount * sizeof(NewState->Privileges[0]) );
        }
        if (PreviousState && BufferLength >= FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ))
221
            wine_server_set_reply( req, PreviousState->Privileges,
222 223 224 225
                                   BufferLength - FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ) );
        ret = wine_server_call( req );
        if (PreviousState)
        {
226
            if (ReturnLength) *ReturnLength = reply->len + FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges );
227 228 229 230 231 232
            PreviousState->PrivilegeCount = reply->len / sizeof(LUID_AND_ATTRIBUTES);
        }
    }
    SERVER_END_REQ;

    return ret;
233 234 235
}

/******************************************************************************
236
*  NtQueryInformationToken		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
237
*  ZwQueryInformationToken		[NTDLL.@]
Juergen Schmied's avatar
Juergen Schmied committed
238
*
239 240 241 242 243
* NOTES
*  Buffer for TokenUser:
*   0x00 TOKEN_USER the PSID field points to the SID
*   0x08 SID
*
Juergen Schmied's avatar
Juergen Schmied committed
244 245 246
*/
NTSTATUS WINAPI NtQueryInformationToken(
	HANDLE token,
247 248 249 250
	TOKEN_INFORMATION_CLASS tokeninfoclass,
	PVOID tokeninfo,
	ULONG tokeninfolength,
	PULONG retlen )
251
{
252 253 254 255 256 257 258 259 260 261 262 263 264 265
    static const ULONG info_len [] =
    {
        0,
        0,    /* TokenUser */
        0,    /* TokenGroups */
        0,    /* TokenPrivileges */
        0,    /* TokenOwner */
        0,    /* TokenPrimaryGroup */
        0,    /* TokenDefaultDacl */
        sizeof(TOKEN_SOURCE), /* TokenSource */
        sizeof(TOKEN_TYPE),  /* TokenType */
        sizeof(SECURITY_IMPERSONATION_LEVEL), /* TokenImpersonationLevel */
        sizeof(TOKEN_STATISTICS), /* TokenStatistics */
        0,    /* TokenRestrictedSids */
266
        sizeof(DWORD), /* TokenSessionId */
267 268 269 270 271
        0,    /* TokenGroupsAndPrivileges */
        0,    /* TokenSessionReference */
        0,    /* TokenSandBoxInert */
        0,    /* TokenAuditPolicy */
        0,    /* TokenOrigin */
272
        sizeof(TOKEN_ELEVATION_TYPE), /* TokenElevationType */
273 274 275 276 277 278
        0,    /* TokenLinkedToken */
        sizeof(TOKEN_ELEVATION), /* TokenElevation */
        0,    /* TokenHasRestrictions */
        0,    /* TokenAccessInformation */
        0,    /* TokenVirtualizationAllowed */
        0,    /* TokenVirtualizationEnabled */
279
        sizeof(TOKEN_MANDATORY_LABEL) + sizeof(SID), /* TokenIntegrityLevel [sizeof(SID) includes one SubAuthority] */
280 281
        0,    /* TokenUIAccess */
        0,    /* TokenMandatoryPolicy */
282 283 284 285 286 287 288 289 290 291 292 293 294 295
        0,    /* TokenLogonSid */
        0,    /* TokenIsAppContainer */
        0,    /* TokenCapabilities */
        sizeof(TOKEN_APPCONTAINER_INFORMATION) + sizeof(SID), /* TokenAppContainerSid */
        0,    /* TokenAppContainerNumber */
        0,    /* TokenUserClaimAttributes*/
        0,    /* TokenDeviceClaimAttributes */
        0,    /* TokenRestrictedUserClaimAttributes */
        0,    /* TokenRestrictedDeviceClaimAttributes */
        0,    /* TokenDeviceGroups */
        0,    /* TokenRestrictedDeviceGroups */
        0,    /* TokenSecurityAttributes */
        0,    /* TokenIsRestricted */
        0     /* TokenProcessTrustLevel */
296 297 298
    };

    ULONG len = 0;
299
    NTSTATUS status = STATUS_SUCCESS;
300

301
    TRACE("(%p,%d,%p,%d,%p)\n",
302 303
          token,tokeninfoclass,tokeninfo,tokeninfolength,retlen);

304 305
    if (tokeninfoclass < MaxTokenInfoClass)
        len = info_len[tokeninfoclass];
306

307
    if (retlen) *retlen = len;
308 309

    if (tokeninfolength < len)
310
        return STATUS_BUFFER_TOO_SMALL;
311 312 313 314

    switch (tokeninfoclass)
    {
    case TokenUser:
315
        SERVER_START_REQ( get_token_sid )
316 317
        {
            TOKEN_USER * tuser = tokeninfo;
318
            PSID sid = tuser + 1;
319 320
            DWORD sid_len = tokeninfolength < sizeof(TOKEN_USER) ? 0 : tokeninfolength - sizeof(TOKEN_USER);

321
            req->handle = wine_server_obj_handle( token );
322
            req->which_sid = tokeninfoclass;
323 324
            wine_server_set_reply( req, sid, sid_len );
            status = wine_server_call( req );
325
            if (retlen) *retlen = reply->sid_len + sizeof(TOKEN_USER);
326 327 328 329 330
            if (status == STATUS_SUCCESS)
            {
                tuser->User.Sid = sid;
                tuser->User.Attributes = 0;
            }
331
        }
332
        SERVER_END_REQ;
333 334
        break;
    case TokenGroups:
335
    {
336 337 338 339 340 341
        void *buffer;

        /* reply buffer is always shorter than output one */
        buffer = tokeninfolength ? RtlAllocateHeap(GetProcessHeap(), 0, tokeninfolength) : NULL;

        SERVER_START_REQ( get_token_groups )
342
        {
343
            TOKEN_GROUPS *groups = tokeninfo;
344

345 346 347 348
            req->handle = wine_server_obj_handle( token );
            wine_server_set_reply( req, buffer, tokeninfolength );
            status = wine_server_call( req );
            if (status == STATUS_BUFFER_TOO_SMALL)
349
            {
350 351 352 353 354 355 356 357 358
                if (retlen) *retlen = reply->user_len;
            }
            else if (status == STATUS_SUCCESS)
            {
                struct token_groups *tg = buffer;
                unsigned int *attr = (unsigned int *)(tg + 1);
                ULONG i;
                const int non_sid_portion = (sizeof(struct token_groups) + tg->count * sizeof(unsigned int));
                SID *sids = (SID *)((char *)tokeninfo + FIELD_OFFSET( TOKEN_GROUPS, Groups[tg->count] ));
359

360 361 362 363
                if (retlen) *retlen = reply->user_len;

                groups->GroupCount = tg->count;
                memcpy( sids, (char *)buffer + non_sid_portion,
364
                        reply->user_len - FIELD_OFFSET( TOKEN_GROUPS, Groups[tg->count] ));
365 366

                for (i = 0; i < tg->count; i++)
367
                {
368 369 370
                    groups->Groups[i].Attributes = attr[i];
                    groups->Groups[i].Sid = sids;
                    sids = (SID *)((char *)sids + RtlLengthSid(sids));
371
                }
372 373 374 375 376 377
             }
             else if (retlen) *retlen = 0;
        }
        SERVER_END_REQ;

        RtlFreeHeap(GetProcessHeap(), 0, buffer);
378
        break;
379
    }
380
    case TokenPrimaryGroup:
381
        SERVER_START_REQ( get_token_sid )
382 383
        {
            TOKEN_PRIMARY_GROUP *tgroup = tokeninfo;
384 385 386 387 388 389 390 391 392 393
            PSID sid = tgroup + 1;
            DWORD sid_len = tokeninfolength < sizeof(TOKEN_PRIMARY_GROUP) ? 0 : tokeninfolength - sizeof(TOKEN_PRIMARY_GROUP);

            req->handle = wine_server_obj_handle( token );
            req->which_sid = tokeninfoclass;
            wine_server_set_reply( req, sid, sid_len );
            status = wine_server_call( req );
            if (retlen) *retlen = reply->sid_len + sizeof(TOKEN_PRIMARY_GROUP);
            if (status == STATUS_SUCCESS)
                tgroup->PrimaryGroup = sid;
394
        }
395
        SERVER_END_REQ;
396
        break;
397
    case TokenPrivileges:
398
        SERVER_START_REQ( get_token_privileges )
399 400
        {
            TOKEN_PRIVILEGES *tpriv = tokeninfo;
401
            req->handle = wine_server_obj_handle( token );
402
            if (tpriv && tokeninfolength > FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ))
403
                wine_server_set_reply( req, tpriv->Privileges, tokeninfolength - FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ) );
404
            status = wine_server_call( req );
405
            if (retlen) *retlen = FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ) + reply->len;
406
            if (tpriv) tpriv->PrivilegeCount = reply->len / sizeof(LUID_AND_ATTRIBUTES);
407
        }
408
        SERVER_END_REQ;
409
        break;
410
    case TokenOwner:
411
        SERVER_START_REQ( get_token_sid )
412
        {
413 414 415 416 417 418 419 420 421 422 423
            TOKEN_OWNER *towner = tokeninfo;
            PSID sid = towner + 1;
            DWORD sid_len = tokeninfolength < sizeof(TOKEN_OWNER) ? 0 : tokeninfolength - sizeof(TOKEN_OWNER);

            req->handle = wine_server_obj_handle( token );
            req->which_sid = tokeninfoclass;
            wine_server_set_reply( req, sid, sid_len );
            status = wine_server_call( req );
            if (retlen) *retlen = reply->sid_len + sizeof(TOKEN_OWNER);
            if (status == STATUS_SUCCESS)
                towner->Owner = sid;
424
        }
425
        SERVER_END_REQ;
426
        break;
427 428 429 430
    case TokenImpersonationLevel:
        SERVER_START_REQ( get_token_impersonation_level )
        {
            SECURITY_IMPERSONATION_LEVEL *impersonation_level = tokeninfo;
431
            req->handle = wine_server_obj_handle( token );
432 433 434 435 436 437
            status = wine_server_call( req );
            if (status == STATUS_SUCCESS)
                *impersonation_level = reply->impersonation_level;
        }
        SERVER_END_REQ;
        break;
438 439 440 441
    case TokenStatistics:
        SERVER_START_REQ( get_token_statistics )
        {
            TOKEN_STATISTICS *statistics = tokeninfo;
442
            req->handle = wine_server_obj_handle( token );
443 444 445 446 447 448 449
            status = wine_server_call( req );
            if (status == STATUS_SUCCESS)
            {
                statistics->TokenId.LowPart  = reply->token_id.low_part;
                statistics->TokenId.HighPart = reply->token_id.high_part;
                statistics->AuthenticationId.LowPart  = 0; /* FIXME */
                statistics->AuthenticationId.HighPart = 0; /* FIXME */
450 451
                statistics->ExpirationTime.u.HighPart = 0x7fffffff;
                statistics->ExpirationTime.u.LowPart  = 0xffffffff;
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
                statistics->TokenType = reply->primary ? TokenPrimary : TokenImpersonation;
                statistics->ImpersonationLevel = reply->impersonation_level;

                /* kernel information not relevant to us */
                statistics->DynamicCharged = 0;
                statistics->DynamicAvailable = 0;

                statistics->GroupCount = reply->group_count;
                statistics->PrivilegeCount = reply->privilege_count;
                statistics->ModifiedId.LowPart  = reply->modified_id.low_part;
                statistics->ModifiedId.HighPart = reply->modified_id.high_part;
            }
        }
        SERVER_END_REQ;
        break;
    case TokenType:
        SERVER_START_REQ( get_token_statistics )
        {
            TOKEN_TYPE *token_type = tokeninfo;
471
            req->handle = wine_server_obj_handle( token );
472 473 474 475 476 477
            status = wine_server_call( req );
            if (status == STATUS_SUCCESS)
                *token_type = reply->primary ? TokenPrimary : TokenImpersonation;
        }
        SERVER_END_REQ;
        break;
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    case TokenDefaultDacl:
        SERVER_START_REQ( get_token_default_dacl )
        {
            TOKEN_DEFAULT_DACL *default_dacl = tokeninfo;
            ACL *acl = (ACL *)(default_dacl + 1);
            DWORD acl_len;

            if (tokeninfolength < sizeof(TOKEN_DEFAULT_DACL)) acl_len = 0;
            else acl_len = tokeninfolength - sizeof(TOKEN_DEFAULT_DACL);

            req->handle = wine_server_obj_handle( token );
            wine_server_set_reply( req, acl, acl_len );
            status = wine_server_call( req );

            if (retlen) *retlen = reply->acl_len + sizeof(TOKEN_DEFAULT_DACL);
            if (status == STATUS_SUCCESS)
            {
                if (reply->acl_len)
                    default_dacl->DefaultDacl = acl;
                else
                    default_dacl->DefaultDacl = NULL;
            }
        }
        SERVER_END_REQ;
        break;
503 504 505 506 507 508 509
    case TokenElevationType:
        {
            TOKEN_ELEVATION_TYPE *elevation_type = tokeninfo;
            FIXME("QueryInformationToken( ..., TokenElevationType, ...) semi-stub\n");
            *elevation_type = TokenElevationTypeFull;
        }
        break;
510 511 512 513 514 515 516
    case TokenElevation:
        {
            TOKEN_ELEVATION *elevation = tokeninfo;
            FIXME("QueryInformationToken( ..., TokenElevation, ...) semi-stub\n");
            elevation->TokenIsElevated = TRUE;
        }
        break;
517 518 519 520 521 522
    case TokenSessionId:
        {
            *((DWORD*)tokeninfo) = 0;
            FIXME("QueryInformationToken( ..., TokenSessionId, ...) semi-stub\n");
        }
        break;
523 524 525 526 527 528 529 530 531 532 533 534 535 536
    case TokenIntegrityLevel:
        {
            /* report always "S-1-16-12288" (high mandatory level) for now */
            static const SID high_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
                                                            {SECURITY_MANDATORY_HIGH_RID}};

            TOKEN_MANDATORY_LABEL *tml = tokeninfo;
            PSID psid = tml + 1;

            tml->Label.Sid = psid;
            tml->Label.Attributes = SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED;
            memcpy(psid, &high_level, sizeof(SID));
        }
        break;
537 538 539 540 541 542 543
    case TokenAppContainerSid:
        {
            TOKEN_APPCONTAINER_INFORMATION *container = tokeninfo;
            FIXME("QueryInformationToken( ..., TokenAppContainerSid, ...) semi-stub\n");
            container->TokenAppContainer = NULL;
        }
        break;
544 545
    default:
        {
546
            ERR("Unhandled Token Information class %d!\n", tokeninfoclass);
547 548
            return STATUS_NOT_IMPLEMENTED;
        }
549
    }
550
    return status;
551 552
}

553 554 555 556 557 558 559 560 561 562
/******************************************************************************
*  NtSetInformationToken		[NTDLL.@]
*  ZwSetInformationToken		[NTDLL.@]
*/
NTSTATUS WINAPI NtSetInformationToken(
        HANDLE TokenHandle,
        TOKEN_INFORMATION_CLASS TokenInformationClass,
        PVOID TokenInformation,
        ULONG TokenInformationLength)
{
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
    NTSTATUS ret = STATUS_NOT_IMPLEMENTED;

    TRACE("%p %d %p %u\n", TokenHandle, TokenInformationClass,
           TokenInformation, TokenInformationLength);

    switch (TokenInformationClass)
    {
    case TokenDefaultDacl:
        if (TokenInformationLength < sizeof(TOKEN_DEFAULT_DACL))
        {
            ret = STATUS_INFO_LENGTH_MISMATCH;
            break;
        }
        if (!TokenInformation)
        {
            ret = STATUS_ACCESS_VIOLATION;
            break;
        }
        SERVER_START_REQ( set_token_default_dacl )
        {
            ACL *acl = ((TOKEN_DEFAULT_DACL *)TokenInformation)->DefaultDacl;
            WORD size;

            if (acl) size = acl->AclSize;
            else size = 0;

            req->handle = wine_server_obj_handle( TokenHandle );
            wine_server_add_data( req, acl, size );
            ret = wine_server_call( req );
        }
        SERVER_END_REQ;
        break;
    default:
        FIXME("unimplemented class %u\n", TokenInformationClass);
        break;
    }

    return ret;
601 602
}

603 604 605 606 607 608 609 610 611 612 613 614
/******************************************************************************
*  NtAdjustGroupsToken		[NTDLL.@]
*  ZwAdjustGroupsToken		[NTDLL.@]
*/
NTSTATUS WINAPI NtAdjustGroupsToken(
        HANDLE TokenHandle,
        BOOLEAN ResetToDefault,
        PTOKEN_GROUPS NewState,
        ULONG BufferLength,
        PTOKEN_GROUPS PreviousState,
        PULONG ReturnLength)
{
615
    FIXME("%p %d %p %u %p %p\n", TokenHandle, ResetToDefault,
616 617 618 619
          NewState, BufferLength, PreviousState, ReturnLength);
    return STATUS_NOT_IMPLEMENTED;
}

620 621 622 623 624 625 626 627 628 629 630 631
/******************************************************************************
*  NtPrivilegeCheck		[NTDLL.@]
*  ZwPrivilegeCheck		[NTDLL.@]
*/
NTSTATUS WINAPI NtPrivilegeCheck(
    HANDLE ClientToken,
    PPRIVILEGE_SET RequiredPrivileges,
    PBOOLEAN Result)
{
    NTSTATUS status;
    SERVER_START_REQ( check_token_privileges )
    {
632
        req->handle = wine_server_obj_handle( ClientToken );
633
        req->all_required = (RequiredPrivileges->Control & PRIVILEGE_SET_ALL_NECESSARY) != 0;
634
        wine_server_add_data( req, RequiredPrivileges->Privilege,
635
            RequiredPrivileges->PrivilegeCount * sizeof(RequiredPrivileges->Privilege[0]) );
636
        wine_server_set_reply( req, RequiredPrivileges->Privilege,
637 638 639 640 641
            RequiredPrivileges->PrivilegeCount * sizeof(RequiredPrivileges->Privilege[0]) );

        status = wine_server_call( req );

        if (status == STATUS_SUCCESS)
642
            *Result = reply->has_privileges != 0;
643 644 645 646 647
    }
    SERVER_END_REQ;
    return status;
}

Juergen Schmied's avatar
Juergen Schmied committed
648 649
/*
 *	Section
650
 */
651

652
/******************************************************************************
653
 *  NtQuerySection	[NTDLL.@]
654
 */
Juergen Schmied's avatar
Juergen Schmied committed
655 656
NTSTATUS WINAPI NtQuerySection(
	IN HANDLE SectionHandle,
657
	IN SECTION_INFORMATION_CLASS SectionInformationClass,
Juergen Schmied's avatar
Juergen Schmied committed
658 659 660
	OUT PVOID SectionInformation,
	IN ULONG Length,
	OUT PULONG ResultLength)
661
{
662
	FIXME("(%p,%d,%p,0x%08x,%p) stub!\n",
Juergen Schmied's avatar
Juergen Schmied committed
663
	SectionHandle,SectionInformationClass,SectionInformation,Length,ResultLength);
664 665 666
	return 0;
}

Juergen Schmied's avatar
Juergen Schmied committed
667 668
/*
 *	ports
669 670 671
 */

/******************************************************************************
672
 *  NtCreatePort		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
673
 *  ZwCreatePort		[NTDLL.@]
674
 */
675
NTSTATUS WINAPI NtCreatePort(PHANDLE PortHandle,POBJECT_ATTRIBUTES ObjectAttributes,
676
                             ULONG MaxConnectInfoLength,ULONG MaxDataLength,PULONG reserved)
677
{
678
  FIXME("(%p,%p,%u,%u,%p),stub!\n",PortHandle,ObjectAttributes,
679
        MaxConnectInfoLength,MaxDataLength,reserved);
680
  return STATUS_NOT_IMPLEMENTED;
681 682 683
}

/******************************************************************************
684
 *  NtConnectPort		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
685
 *  ZwConnectPort		[NTDLL.@]
686
 */
687 688 689 690 691 692 693 694 695
NTSTATUS WINAPI NtConnectPort(
        PHANDLE PortHandle,
        PUNICODE_STRING PortName,
        PSECURITY_QUALITY_OF_SERVICE SecurityQos,
        PLPC_SECTION_WRITE WriteSection,
        PLPC_SECTION_READ ReadSection,
        PULONG MaximumMessageLength,
        PVOID ConnectInfo,
        PULONG pConnectInfoLength)
696
{
697 698 699 700 701 702
    FIXME("(%p,%s,%p,%p,%p,%p,%p,%p),stub!\n",
          PortHandle,debugstr_w(PortName->Buffer),SecurityQos,
          WriteSection,ReadSection,MaximumMessageLength,ConnectInfo,
          pConnectInfoLength);
    if (ConnectInfo && pConnectInfoLength)
        TRACE("\tMessage = %s\n",debugstr_an(ConnectInfo,*pConnectInfoLength));
703
    return STATUS_NOT_IMPLEMENTED;
704 705
}

706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
/******************************************************************************
 *  NtSecureConnectPort                (NTDLL.@)
 *  ZwSecureConnectPort                (NTDLL.@)
 */
NTSTATUS WINAPI NtSecureConnectPort(
        PHANDLE PortHandle,
        PUNICODE_STRING PortName,
        PSECURITY_QUALITY_OF_SERVICE SecurityQos,
        PLPC_SECTION_WRITE WriteSection,
        PSID pSid,
        PLPC_SECTION_READ ReadSection,
        PULONG MaximumMessageLength,
        PVOID ConnectInfo,
        PULONG pConnectInfoLength)
{
    FIXME("(%p,%s,%p,%p,%p,%p,%p,%p,%p),stub!\n",
          PortHandle,debugstr_w(PortName->Buffer),SecurityQos,
          WriteSection,pSid,ReadSection,MaximumMessageLength,ConnectInfo,
          pConnectInfoLength);
    return STATUS_NOT_IMPLEMENTED;
}

728
/******************************************************************************
729
 *  NtListenPort		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
730
 *  ZwListenPort		[NTDLL.@]
731
 */
732
NTSTATUS WINAPI NtListenPort(HANDLE PortHandle,PLPC_MESSAGE pLpcMessage)
Juergen Schmied's avatar
Juergen Schmied committed
733
{
734
  FIXME("(%p,%p),stub!\n",PortHandle,pLpcMessage);
735
  return STATUS_NOT_IMPLEMENTED;
736 737 738
}

/******************************************************************************
739
 *  NtAcceptConnectPort	[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
740
 *  ZwAcceptConnectPort	[NTDLL.@]
741
 */
742 743 744 745 746 747 748
NTSTATUS WINAPI NtAcceptConnectPort(
        PHANDLE PortHandle,
        ULONG PortIdentifier,
        PLPC_MESSAGE pLpcMessage,
        BOOLEAN Accept,
        PLPC_SECTION_WRITE WriteSection,
        PLPC_SECTION_READ ReadSection)
Juergen Schmied's avatar
Juergen Schmied committed
749
{
750
  FIXME("(%p,%u,%p,%d,%p,%p),stub!\n",
751
        PortHandle,PortIdentifier,pLpcMessage,Accept,WriteSection,ReadSection);
752
  return STATUS_NOT_IMPLEMENTED;
753 754 755
}

/******************************************************************************
756
 *  NtCompleteConnectPort	[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
757
 *  ZwCompleteConnectPort	[NTDLL.@]
758
 */
759
NTSTATUS WINAPI NtCompleteConnectPort(HANDLE PortHandle)
Juergen Schmied's avatar
Juergen Schmied committed
760
{
761
  FIXME("(%p),stub!\n",PortHandle);
762
  return STATUS_NOT_IMPLEMENTED;
763 764 765
}

/******************************************************************************
766
 *  NtRegisterThreadTerminatePort	[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
767
 *  ZwRegisterThreadTerminatePort	[NTDLL.@]
768
 */
769
NTSTATUS WINAPI NtRegisterThreadTerminatePort(HANDLE PortHandle)
Juergen Schmied's avatar
Juergen Schmied committed
770
{
771
  FIXME("(%p),stub!\n",PortHandle);
772
  return STATUS_NOT_IMPLEMENTED;
773 774 775
}

/******************************************************************************
776
 *  NtRequestWaitReplyPort		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
777
 *  ZwRequestWaitReplyPort		[NTDLL.@]
778
 */
779 780 781 782
NTSTATUS WINAPI NtRequestWaitReplyPort(
        HANDLE PortHandle,
        PLPC_MESSAGE pLpcMessageIn,
        PLPC_MESSAGE pLpcMessageOut)
783
{
784 785 786 787
  FIXME("(%p,%p,%p),stub!\n",PortHandle,pLpcMessageIn,pLpcMessageOut);
  if(pLpcMessageIn)
  {
    TRACE("Message to send:\n");
788 789 790 791 792 793
    TRACE("\tDataSize            = %u\n",pLpcMessageIn->DataSize);
    TRACE("\tMessageSize         = %u\n",pLpcMessageIn->MessageSize);
    TRACE("\tMessageType         = %u\n",pLpcMessageIn->MessageType);
    TRACE("\tVirtualRangesOffset = %u\n",pLpcMessageIn->VirtualRangesOffset);
    TRACE("\tClientId.UniqueProcess = %p\n",pLpcMessageIn->ClientId.UniqueProcess);
    TRACE("\tClientId.UniqueThread  = %p\n",pLpcMessageIn->ClientId.UniqueThread);
794 795
    TRACE("\tMessageId           = %lu\n",pLpcMessageIn->MessageId);
    TRACE("\tSectionSize         = %lu\n",pLpcMessageIn->SectionSize);
796
    TRACE("\tData                = %s\n",
Mike McCormack's avatar
Mike McCormack committed
797
      debugstr_an((const char*)pLpcMessageIn->Data,pLpcMessageIn->DataSize));
798
  }
799
  return STATUS_NOT_IMPLEMENTED;
800 801 802
}

/******************************************************************************
803
 *  NtReplyWaitReceivePort	[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
804
 *  ZwReplyWaitReceivePort	[NTDLL.@]
805
 */
806 807 808 809 810
NTSTATUS WINAPI NtReplyWaitReceivePort(
        HANDLE PortHandle,
        PULONG PortIdentifier,
        PLPC_MESSAGE ReplyMessage,
        PLPC_MESSAGE Message)
Juergen Schmied's avatar
Juergen Schmied committed
811
{
812
  FIXME("(%p,%p,%p,%p),stub!\n",PortHandle,PortIdentifier,ReplyMessage,Message);
813
  return STATUS_NOT_IMPLEMENTED;
814 815
}

Juergen Schmied's avatar
Juergen Schmied committed
816 817
/*
 *	Misc
818
 */
Juergen Schmied's avatar
Juergen Schmied committed
819 820

 /******************************************************************************
821
 *  NtSetIntervalProfile	[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
822
 *  ZwSetIntervalProfile	[NTDLL.@]
Juergen Schmied's avatar
Juergen Schmied committed
823
 */
824 825 826 827
NTSTATUS WINAPI NtSetIntervalProfile(
        ULONG Interval,
        KPROFILE_SOURCE Source)
{
828
    FIXME("%u,%d\n", Interval, Source);
829
    return STATUS_SUCCESS;
830
}
Juergen Schmied's avatar
Juergen Schmied committed
831

832 833
static  SYSTEM_CPU_INFORMATION cached_sci;

834 835 836 837 838 839 840 841
/*******************************************************************************
 * Architecture specific feature detection for CPUs
 *
 * This a set of mutually exclusive #if define()s each providing its own get_cpuinfo() to be called
 * from fill_cpu_info();
 */
#if defined(__i386__) || defined(__x86_64__)

842 843 844 845
#define AUTH	0x68747541	/* "Auth" */
#define ENTI	0x69746e65	/* "enti" */
#define CAMD	0x444d4163	/* "cAMD" */

846 847 848 849
#define GENU	0x756e6547	/* "Genu" */
#define INEI	0x49656e69	/* "ineI" */
#define NTEL	0x6c65746e	/* "ntel" */

850 851 852 853 854 855 856 857 858 859 860 861
/* Calls cpuid with an eax of 'ax' and returns the 16 bytes in *p
 * We are compiled with -fPIC, so we can't clobber ebx.
 */
static inline void do_cpuid(unsigned int ax, unsigned int *p)
{
#ifdef __i386__
	__asm__("pushl %%ebx\n\t"
                "cpuid\n\t"
                "movl %%ebx, %%esi\n\t"
                "popl %%ebx"
                : "=a" (p[0]), "=S" (p[1]), "=c" (p[2]), "=d" (p[3])
                :  "0" (ax));
862 863 864 865 866 867 868
#elif defined(__x86_64__)
	__asm__("push %%rbx\n\t"
                "cpuid\n\t"
                "movq %%rbx, %%rsi\n\t"
                "pop %%rbx"
                : "=a" (p[0]), "=S" (p[1]), "=c" (p[2]), "=d" (p[3])
                :  "0" (ax));
869 870 871 872
#endif
}

/* From xf86info havecpuid.c 1.11 */
873
static inline BOOL have_cpuid(void)
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
{
#ifdef __i386__
	unsigned int f1, f2;
	__asm__("pushfl\n\t"
                "pushfl\n\t"
                "popl %0\n\t"
                "movl %0,%1\n\t"
                "xorl %2,%0\n\t"
                "pushl %0\n\t"
                "popfl\n\t"
                "pushfl\n\t"
                "popl %0\n\t"
                "popfl"
                : "=&r" (f1), "=&r" (f2)
                : "ir" (0x00200000));
	return ((f1^f2) & 0x00200000) != 0;
890
#elif defined(__x86_64__)
891
        return TRUE;
892
#else
893
        return FALSE;
894 895 896
#endif
}

897 898 899
/* Detect if a SSE2 processor is capable of Denormals Are Zero (DAZ) mode.
 *
 * This function assumes you have already checked for SSE2/FXSAVE support. */
900
static inline BOOL have_sse_daz_mode(void)
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
{
#ifdef __i386__
    typedef struct DECLSPEC_ALIGN(16) _M128A {
        ULONGLONG Low;
        LONGLONG High;
    } M128A;

    typedef struct _XMM_SAVE_AREA32 {
        WORD ControlWord;
        WORD StatusWord;
        BYTE TagWord;
        BYTE Reserved1;
        WORD ErrorOpcode;
        DWORD ErrorOffset;
        WORD ErrorSelector;
        WORD Reserved2;
        DWORD DataOffset;
        WORD DataSelector;
        WORD Reserved3;
        DWORD MxCsr;
        DWORD MxCsr_Mask;
        M128A FloatRegisters[8];
        M128A XmmRegisters[16];
        BYTE Reserved4[96];
    } XMM_SAVE_AREA32;

    /* Intel says we need a zeroed 16-byte aligned buffer */
    char buffer[512 + 16];
    XMM_SAVE_AREA32 *state = (XMM_SAVE_AREA32 *)(((ULONG_PTR)buffer + 15) & ~15);
    memset(buffer, 0, sizeof(buffer));

    __asm__ __volatile__( "fxsave %0" : "=m" (*state) : "m" (*state) );

    return (state->MxCsr_Mask & (1 << 6)) >> 6;
#else /* all x86_64 processors include SSE2 with DAZ mode */
936
    return TRUE;
937 938 939
#endif
}

940 941 942 943
static inline void get_cpuinfo(SYSTEM_CPU_INFORMATION* info)
{
    unsigned int regs[4], regs2[4];

944 945 946 947 948 949
#if defined(__i386__)
    info->Architecture = PROCESSOR_ARCHITECTURE_INTEL;
#elif defined(__x86_64__)
    info->Architecture = PROCESSOR_ARCHITECTURE_AMD64;
#endif

950 951 952 953
    /* We're at least a 386 */
    info->FeatureSet = CPU_FEATURE_VME | CPU_FEATURE_X86 | CPU_FEATURE_PGE;
    info->Level = 3;

954 955 956 957 958 959
    if (!have_cpuid()) return;

    do_cpuid(0x00000000, regs);  /* get standard cpuid level and vendor name */
    if (regs[0]>=0x00000001)   /* Check for supported cpuid version */
    {
        do_cpuid(0x00000001, regs2); /* get cpu features */
960 961 962 963 964 965 966 967 968 969 970 971 972

        if(regs2[3] & (1 << 3 )) info->FeatureSet |= CPU_FEATURE_PSE;
        if(regs2[3] & (1 << 4 )) info->FeatureSet |= CPU_FEATURE_TSC;
        if(regs2[3] & (1 << 8 )) info->FeatureSet |= CPU_FEATURE_CX8;
        if(regs2[3] & (1 << 11)) info->FeatureSet |= CPU_FEATURE_SEP;
        if(regs2[3] & (1 << 12)) info->FeatureSet |= CPU_FEATURE_MTRR;
        if(regs2[3] & (1 << 15)) info->FeatureSet |= CPU_FEATURE_CMOV;
        if(regs2[3] & (1 << 16)) info->FeatureSet |= CPU_FEATURE_PAT;
        if(regs2[3] & (1 << 23)) info->FeatureSet |= CPU_FEATURE_MMX;
        if(regs2[3] & (1 << 24)) info->FeatureSet |= CPU_FEATURE_FXSR;
        if(regs2[3] & (1 << 25)) info->FeatureSet |= CPU_FEATURE_SSE;
        if(regs2[3] & (1 << 26)) info->FeatureSet |= CPU_FEATURE_SSE2;

973 974 975 976 977 978 979
        user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED]       = !(regs2[3] & 1);
        user_shared_data->ProcessorFeatures[PF_RDTSC_INSTRUCTION_AVAILABLE]   = (regs2[3] & (1 << 4 )) >> 4;
        user_shared_data->ProcessorFeatures[PF_PAE_ENABLED]                   = (regs2[3] & (1 << 6 )) >> 6;
        user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE_DOUBLE]       = (regs2[3] & (1 << 8 )) >> 8;
        user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE]    = (regs2[3] & (1 << 23)) >> 23;
        user_shared_data->ProcessorFeatures[PF_XMMI_INSTRUCTIONS_AVAILABLE]   = (regs2[3] & (1 << 25)) >> 25;
        user_shared_data->ProcessorFeatures[PF_XMMI64_INSTRUCTIONS_AVAILABLE] = (regs2[3] & (1 << 26)) >> 26;
980 981 982
        user_shared_data->ProcessorFeatures[PF_SSE3_INSTRUCTIONS_AVAILABLE]   = regs2[2] & 1;
        user_shared_data->ProcessorFeatures[PF_XSAVE_ENABLED]                 = (regs2[2] & (1 << 27)) >> 27;
        user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE128]           = (regs2[2] & (1 << 13)) >> 13;
983

984 985 986
        if((regs2[3] & (1 << 26)) && (regs2[3] & (1 << 24))) /* has SSE2 and FXSAVE/FXRSTOR */
            user_shared_data->ProcessorFeatures[PF_SSE_DAZ_MODE_AVAILABLE] = have_sse_daz_mode();

987 988
        if (regs[1] == AUTH && regs[3] == ENTI && regs[2] == CAMD)
        {
989 990 991 992
            info->Level = (regs2[0] >> 8) & 0xf; /* family */
            if (info->Level == 0xf)  /* AMD says to add the extended family to the family if family is 0xf */
                info->Level += (regs2[0] >> 20) & 0xff;

993 994 995 996 997
            /* repack model and stepping to make a "revision" */
            info->Revision  = ((regs2[0] >> 16) & 0xf) << 12; /* extended model */
            info->Revision |= ((regs2[0] >> 4 ) & 0xf) << 8;  /* model          */
            info->Revision |= regs2[0] & 0xf;                 /* stepping       */

998 999 1000 1001
            do_cpuid(0x80000000, regs);  /* get vendor cpuid level */
            if (regs[0] >= 0x80000001)
            {
                do_cpuid(0x80000001, regs2);  /* get vendor features */
1002 1003
                user_shared_data->ProcessorFeatures[PF_VIRT_FIRMWARE_ENABLED]        = (regs2[2] & (1 << 2  )) >> 2;
                user_shared_data->ProcessorFeatures[PF_NX_ENABLED]                   = (regs2[3] & (1 << 20 )) >> 20;
1004
                user_shared_data->ProcessorFeatures[PF_3DNOW_INSTRUCTIONS_AVAILABLE] = (regs2[3] & (1 << 31 )) >> 31;
1005 1006 1007 1008 1009
                if(regs2[3] & (1 << 31)) info->FeatureSet |= CPU_FEATURE_3DNOW;
            }
        }
        else if (regs[1] == GENU && regs[3] == INEI && regs[2] == NTEL)
        {
1010 1011 1012
            info->Level = ((regs2[0] >> 8) & 0xf) + ((regs2[0] >> 20) & 0xff); /* family + extended family */
            if(info->Level == 15) info->Level = 6;

1013 1014 1015 1016 1017
            /* repack model and stepping to make a "revision" */
            info->Revision  = ((regs2[0] >> 16) & 0xf) << 12; /* extended model */
            info->Revision |= ((regs2[0] >> 4 ) & 0xf) << 8;  /* model          */
            info->Revision |= regs2[0] & 0xf;                 /* stepping       */

1018 1019 1020 1021 1022 1023 1024 1025
            if(regs2[3] & (1 << 21)) info->FeatureSet |= CPU_FEATURE_DS;
            user_shared_data->ProcessorFeatures[PF_VIRT_FIRMWARE_ENABLED] = (regs2[2] & (1 << 5 )) >> 5;

            do_cpuid(0x80000000, regs);  /* get vendor cpuid level */
            if (regs[0] >= 0x80000001)
            {
                do_cpuid(0x80000001, regs2);  /* get vendor features */
                user_shared_data->ProcessorFeatures[PF_NX_ENABLED] = (regs2[3] & (1 << 20 )) >> 20;
1026 1027
            }
        }
1028 1029 1030
        else
        {
            info->Level = (regs2[0] >> 8) & 0xf; /* family */
1031 1032 1033 1034

            /* repack model and stepping to make a "revision" */
            info->Revision = ((regs2[0] >> 4 ) & 0xf) << 8;  /* model    */
            info->Revision |= regs2[0] & 0xf;                /* stepping */
1035
        }
1036 1037 1038
    }
}

1039 1040 1041
#elif defined(__powerpc__) || defined(__ppc__)

static inline void get_cpuinfo(SYSTEM_CPU_INFORMATION* info)
1042
{
1043 1044 1045
#ifdef __APPLE__
    size_t valSize;
    int value;
1046

1047 1048 1049 1050 1051 1052
    valSize = sizeof(value);
    if (sysctlbyname("hw.optional.floatingpoint", &value, &valSize, NULL, 0) == 0)
        user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED] = !value;

    valSize = sizeof(value);
    if (sysctlbyname("hw.cpusubtype", &value, &valSize, NULL, 0) == 0)
1053
    {
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
        switch (value)
        {
            case CPU_SUBTYPE_POWERPC_601:
            case CPU_SUBTYPE_POWERPC_602:       info->Level = 1;   break;
            case CPU_SUBTYPE_POWERPC_603:       info->Level = 3;   break;
            case CPU_SUBTYPE_POWERPC_603e:
            case CPU_SUBTYPE_POWERPC_603ev:     info->Level = 6;   break;
            case CPU_SUBTYPE_POWERPC_604:       info->Level = 4;   break;
            case CPU_SUBTYPE_POWERPC_604e:      info->Level = 9;   break;
            case CPU_SUBTYPE_POWERPC_620:       info->Level = 20;  break;
            case CPU_SUBTYPE_POWERPC_750:       /* G3/G4 derive from 603 so ... */
            case CPU_SUBTYPE_POWERPC_7400:
            case CPU_SUBTYPE_POWERPC_7450:      info->Level = 6;   break;
            case CPU_SUBTYPE_POWERPC_970:       info->Level = 9;
                /* :o) user_shared_data->ProcessorFeatures[PF_ALTIVEC_INSTRUCTIONS_AVAILABLE] ;-) */
                break;
            default: break;
        }
1072 1073
    }
#else
1074
    FIXME("CPU Feature detection not implemented.\n");
1075
#endif
1076 1077
    info->Architecture = PROCESSOR_ARCHITECTURE_PPC;
}
1078

1079
#elif defined(__arm__)
1080

1081 1082
static inline void get_cpuinfo(SYSTEM_CPU_INFORMATION* info)
{
1083
#ifdef linux
1084 1085 1086 1087
    char line[512];
    char *s, *value;
    FILE *f = fopen("/proc/cpuinfo", "r");
    if (f)
1088
    {
1089
        while (fgets(line, sizeof(line), f) != NULL)
1090 1091 1092 1093 1094 1095
        {
            /* NOTE: the ':' is the only character we can rely on */
            if (!(value = strchr(line,':')))
                continue;
            /* terminate the valuename */
            s = value - 1;
1096
            while ((s >= line) && isspace(*s)) s--;
1097 1098 1099
            *(s + 1) = '\0';
            /* and strip leading spaces from value */
            value += 1;
1100
            while (isspace(*value)) value++;
1101 1102
            if ((s = strchr(value,'\n')))
                *s='\0';
1103
            if (!strcasecmp(line, "CPU architecture"))
1104 1105
            {
                if (isdigit(value[0]))
1106
                    info->Level = atoi(value);
1107 1108 1109 1110 1111 1112
                continue;
            }
            if (!strcasecmp(line, "CPU revision"))
            {
                if (isdigit(value[0]))
                    info->Revision = atoi(value);
1113 1114
                continue;
            }
1115
            if (!strcasecmp(line, "features"))
1116
            {
1117 1118 1119 1120
                if (strstr(value, "vfpv3"))
                    user_shared_data->ProcessorFeatures[PF_ARM_VFP_32_REGISTERS_AVAILABLE] = TRUE;
                if (strstr(value, "neon"))
                    user_shared_data->ProcessorFeatures[PF_ARM_NEON_INSTRUCTIONS_AVAILABLE] = TRUE;
1121 1122
                continue;
            }
1123 1124
        }
        fclose(f);
1125
    }
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
#elif defined(__FreeBSD__)
    size_t valsize;
    char buf[8];
    int value;

    valsize = sizeof(buf);
    if (!sysctlbyname("hw.machine_arch", &buf, &valsize, NULL, 0) &&
        sscanf(buf, "armv%i", &value) == 1)
        info->Level = value;

    valsize = sizeof(value);
    if (!sysctlbyname("hw.floatingpoint", &value, &valsize, NULL, 0))
        user_shared_data->ProcessorFeatures[PF_ARM_VFP_32_REGISTERS_AVAILABLE] = value;
1139 1140
#else
    FIXME("CPU Feature detection not implemented.\n");
1141
#endif
1142 1143
    if (info->Level >= 8)
        user_shared_data->ProcessorFeatures[PF_ARM_V8_INSTRUCTIONS_AVAILABLE] = TRUE;
1144 1145
    info->Architecture = PROCESSOR_ARCHITECTURE_ARM;
}
1146

1147 1148 1149 1150
#elif defined(__aarch64__)

static inline void get_cpuinfo(SYSTEM_CPU_INFORMATION* info)
{
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
#ifdef linux
    char line[512];
    char *s, *value;
    FILE *f = fopen("/proc/cpuinfo", "r");
    if (f)
    {
        while (fgets(line, sizeof(line), f) != NULL)
        {
            /* NOTE: the ':' is the only character we can rely on */
            if (!(value = strchr(line,':')))
                continue;
            /* terminate the valuename */
            s = value - 1;
            while ((s >= line) && isspace(*s)) s--;
            *(s + 1) = '\0';
            /* and strip leading spaces from value */
            value += 1;
            while (isspace(*value)) value++;
            if ((s = strchr(value,'\n')))
                *s='\0';
            if (!strcasecmp(line, "CPU architecture"))
            {
                if (isdigit(value[0]))
                    info->Level = atoi(value);
                continue;
            }
            if (!strcasecmp(line, "CPU revision"))
            {
                if (isdigit(value[0]))
                    info->Revision = atoi(value);
                continue;
            }
            if (!strcasecmp(line, "Features"))
            {
                if (strstr(value, "crc32"))
                    user_shared_data->ProcessorFeatures[PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE] = TRUE;
                if (strstr(value, "aes"))
                    user_shared_data->ProcessorFeatures[PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE] = TRUE;
                continue;
            }
        }
        fclose(f);
    }
#else
    FIXME("CPU Feature detection not implemented.\n");
#endif
    info->Level = max(info->Level, 8);
    user_shared_data->ProcessorFeatures[PF_ARM_V8_INSTRUCTIONS_AVAILABLE] = TRUE;
1199
    info->Architecture = PROCESSOR_ARCHITECTURE_ARM64;
1200 1201
}

1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
#endif /* End architecture specific feature detection for CPUs */

/******************************************************************
 *		fill_cpu_info
 *
 * inits a couple of places with CPU related information:
 * - cached_sci in this file
 * - Peb->NumberOfProcessors
 * - SharedUserData->ProcessFeatures[] array
 */
void fill_cpu_info(void)
{
    long num;

#ifdef _SC_NPROCESSORS_ONLN
    num = sysconf(_SC_NPROCESSORS_ONLN);
    if (num < 1)
1219
    {
1220 1221
        num = 1;
        WARN("Failed to detect the number of processors.\n");
1222
    }
1223 1224 1225 1226 1227 1228
#elif defined(CTL_HW) && defined(HW_NCPU)
    int mib[2];
    size_t len = sizeof(num);
    mib[0] = CTL_HW;
    mib[1] = HW_NCPU;
    if (sysctl(mib, 2, &num, &len, NULL, 0) != 0)
1229
    {
1230 1231
        num = 1;
        WARN("Failed to detect the number of processors.\n");
1232 1233
    }
#else
1234
    num = 1;
1235
    FIXME("Detecting the number of processors is not supported.\n");
1236
#endif
1237 1238 1239 1240 1241
    NtCurrentTeb()->Peb->NumberOfProcessors = num;

    memset(&cached_sci, 0, sizeof(cached_sci));
    get_cpuinfo(&cached_sci);

1242 1243 1244 1245
    TRACE("<- CPU arch %d, level %d, rev %d, features 0x%x\n",
          cached_sci.Architecture, cached_sci.Level, cached_sci.Revision, cached_sci.FeatureSet);
}

1246 1247 1248 1249
#ifdef linux
static inline BOOL logical_proc_info_add_by_id(SYSTEM_LOGICAL_PROCESSOR_INFORMATION *data,
        DWORD *len, DWORD max_len, LOGICAL_PROCESSOR_RELATIONSHIP rel, DWORD id, DWORD proc)
{
1250
    DWORD i;
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272

    for(i=0; i<*len; i++)
    {
        if(data[i].Relationship!=rel || data[i].u.Reserved[1]!=id)
            continue;

        data[i].ProcessorMask |= (ULONG_PTR)1<<proc;
        return TRUE;
    }

    if(*len == max_len)
        return FALSE;

    data[i].Relationship = rel;
    data[i].ProcessorMask = (ULONG_PTR)1<<proc;
    /* TODO: set processor core flags */
    data[i].u.Reserved[0] = 0;
    data[i].u.Reserved[1] = id;
    *len = i+1;
    return TRUE;
}

1273 1274 1275
static inline BOOL logical_proc_info_add_cache(SYSTEM_LOGICAL_PROCESSOR_INFORMATION *data,
        DWORD *len, DWORD max_len, ULONG_PTR mask, CACHE_DESCRIPTOR *cache)
{
1276
    DWORD i;
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294

    for(i=0; i<*len; i++)
    {
        if(data[i].Relationship==RelationCache && data[i].ProcessorMask==mask
                && data[i].u.Cache.Level==cache->Level && data[i].u.Cache.Type==cache->Type)
            return TRUE;
    }

    if(*len == max_len)
        return FALSE;

    data[i].Relationship = RelationCache;
    data[i].ProcessorMask = mask;
    data[i].u.Cache = *cache;
    *len = i+1;
    return TRUE;
}

1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
static inline BOOL logical_proc_info_add_numa_node(SYSTEM_LOGICAL_PROCESSOR_INFORMATION *data,
        DWORD *len, DWORD max_len, ULONG_PTR mask, DWORD node_id)
{
    if(*len == max_len)
        return FALSE;

    data[*len].Relationship = RelationNumaNode;
    data[*len].ProcessorMask = mask;
    data[*len].u.NumaNode.NodeNumber = node_id;
    (*len)++;
    return TRUE;
}

1308 1309 1310
static NTSTATUS create_logical_proc_info(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data, DWORD *max_len)
{
    static const char core_info[] = "/sys/devices/system/cpu/cpu%d/%s";
1311
    static const char cache_info[] = "/sys/devices/system/cpu/cpu%d/cache/index%d/%s";
1312
    static const char numa_info[] = "/sys/devices/system/node/node%d/cpumap";
1313

1314
    FILE *fcpu_list, *fnuma_list, *f;
1315
    DWORD len = 0, beg, end, i, j, r;
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
    char op, name[MAX_PATH];

    fcpu_list = fopen("/sys/devices/system/cpu/online", "r");
    if(!fcpu_list)
        return STATUS_NOT_IMPLEMENTED;

    while(!feof(fcpu_list))
    {
        if(!fscanf(fcpu_list, "%u%c ", &beg, &op))
            break;
        if(op == '-') fscanf(fcpu_list, "%u%c ", &end, &op);
        else end = beg;

        for(i=beg; i<=end; i++)
        {
            if(i > 8*sizeof(ULONG_PTR))
            {
                FIXME("skipping logical processor %d\n", i);
                continue;
            }

            sprintf(name, core_info, i, "core_id");
            f = fopen(name, "r");
            if(f)
            {
                fscanf(f, "%u", &r);
                fclose(f);
            }
            else r = i;
            if(!logical_proc_info_add_by_id(*data, &len, *max_len, RelationProcessorCore, r, i))
            {
                SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;

                *max_len *= 2;
                new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *data, *max_len*sizeof(*new_data));
                if(!new_data)
                {
                    fclose(fcpu_list);
                    return STATUS_NO_MEMORY;
                }

                *data = new_data;
                logical_proc_info_add_by_id(*data, &len, *max_len, RelationProcessorCore, r, i);
            }

            sprintf(name, core_info, i, "physical_package_id");
            f = fopen(name, "r");
            if(f)
            {
                fscanf(f, "%u", &r);
                fclose(f);
            }
            else r = 0;
            if(!logical_proc_info_add_by_id(*data, &len, *max_len, RelationProcessorPackage, r, i))
            {
                SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;

                *max_len *= 2;
                new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *data, *max_len*sizeof(*new_data));
                if(!new_data)
                {
                    fclose(fcpu_list);
                    return STATUS_NO_MEMORY;
                }

                *data = new_data;
                logical_proc_info_add_by_id(*data, &len, *max_len, RelationProcessorPackage, r, i);
            }
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458

            for(j=0; j<4; j++)
            {
                CACHE_DESCRIPTOR cache;
                ULONG_PTR mask = 0;

                sprintf(name, cache_info, i, j, "shared_cpu_map");
                f = fopen(name, "r");
                if(!f) continue;
                while(!feof(f))
                {
                    if(!fscanf(f, "%x%c ", &r, &op))
                        break;
                    mask = (sizeof(ULONG_PTR)>sizeof(int) ? mask<<(8*sizeof(DWORD)) : 0) + r;
                }
                fclose(f);

                sprintf(name, cache_info, i, j, "level");
                f = fopen(name, "r");
                if(!f) continue;
                fscanf(f, "%u", &r);
                fclose(f);
                cache.Level = r;

                sprintf(name, cache_info, i, j, "ways_of_associativity");
                f = fopen(name, "r");
                if(!f) continue;
                fscanf(f, "%u", &r);
                fclose(f);
                cache.Associativity = r;

                sprintf(name, cache_info, i, j, "coherency_line_size");
                f = fopen(name, "r");
                if(!f) continue;
                fscanf(f, "%u", &r);
                fclose(f);
                cache.LineSize = r;

                sprintf(name, cache_info, i, j, "size");
                f = fopen(name, "r");
                if(!f) continue;
                fscanf(f, "%u%c", &r, &op);
                fclose(f);
                if(op != 'K')
                    WARN("unknown cache size %u%c\n", r, op);
                cache.Size = (op=='K' ? r*1024 : r);

                sprintf(name, cache_info, i, j, "type");
                f = fopen(name, "r");
                if(!f) continue;
                fscanf(f, "%s", name);
                fclose(f);
                if(!memcmp(name, "Data", 5))
                    cache.Type = CacheData;
                else if(!memcmp(name, "Instruction", 11))
                    cache.Type = CacheInstruction;
                else
                    cache.Type = CacheUnified;

                if(!logical_proc_info_add_cache(*data, &len, *max_len, mask, &cache))
                {
                    SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;

                    *max_len *= 2;
                    new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *data, *max_len*sizeof(*new_data));
                    if(!new_data)
                    {
                        fclose(fcpu_list);
                        return STATUS_NO_MEMORY;
                    }

                    *data = new_data;
                    logical_proc_info_add_cache(*data, &len, *max_len, mask, &cache);
                }
            }
1459 1460 1461 1462
        }
    }
    fclose(fcpu_list);

1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
    fnuma_list = fopen("/sys/devices/system/node/online", "r");
    if(!fnuma_list)
    {
        ULONG_PTR mask = 0;

        for(i=0; i<len; i++)
            if((*data)[i].Relationship == RelationProcessorCore)
                mask |= (*data)[i].ProcessorMask;

        if(len == *max_len)
        {
            SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;

            *max_len *= 2;
            new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *data, *max_len*sizeof(*new_data));
            if(!new_data)
                return STATUS_NO_MEMORY;

            *data = new_data;
        }
        logical_proc_info_add_numa_node(*data, &len, *max_len, mask, 0);
    }
    else
    {
        while(!feof(fnuma_list))
        {
            if(!fscanf(fnuma_list, "%u%c ", &beg, &op))
                break;
            if(op == '-') fscanf(fnuma_list, "%u%c ", &end, &op);
            else end = beg;

            for(i=beg; i<=end; i++)
            {
                ULONG_PTR mask = 0;

                sprintf(name, numa_info, i);
                f = fopen(name, "r");
                if(!f) continue;
                while(!feof(f))
                {
                    if(!fscanf(f, "%x%c ", &r, &op))
                        break;
                    mask = (sizeof(ULONG_PTR)>sizeof(int) ? mask<<(8*sizeof(DWORD)) : 0) + r;
                }
                fclose(f);

                if(len == *max_len)
                {
                    SYSTEM_LOGICAL_PROCESSOR_INFORMATION *new_data;

                    *max_len *= 2;
                    new_data = RtlReAllocateHeap(GetProcessHeap(), 0, *data, *max_len*sizeof(*new_data));
                    if(!new_data)
                    {
                        fclose(fnuma_list);
                        return STATUS_NO_MEMORY;
                    }

                    *data = new_data;
                }
                logical_proc_info_add_numa_node(*data, &len, *max_len, mask, i);
            }
        }
        fclose(fnuma_list);
    }

1529 1530 1531
    *max_len = len * sizeof(**data);
    return STATUS_SUCCESS;
}
1532 1533 1534
#elif defined(__APPLE__)
static NTSTATUS create_logical_proc_info(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data, DWORD *max_len)
{
1535 1536
    DWORD len = 0, i, j, k;
    DWORD cores_no, lcpu_no, lcpu_per_core, cores_per_package, assoc;
1537 1538
    size_t size;
    ULONG_PTR mask;
1539 1540
    LONGLONG cache_size, cache_line_size, cache_sharing[10];
    CACHE_DESCRIPTOR cache[4];
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575

    lcpu_no = NtCurrentTeb()->Peb->NumberOfProcessors;

    size = sizeof(cores_no);
    if(sysctlbyname("machdep.cpu.core_count", &cores_no, &size, NULL, 0))
        cores_no = lcpu_no;

    lcpu_per_core = lcpu_no/cores_no;
    for(i=0; i<cores_no; i++)
    {
        mask = 0;
        for(j=lcpu_per_core*i; j<lcpu_per_core*(i+1); j++)
            mask |= (ULONG_PTR)1<<j;

        (*data)[len].Relationship = RelationProcessorCore;
        (*data)[len].ProcessorMask = mask;
        (*data)[len].u.ProcessorCore.Flags = 0; /* TODO */
        len++;
    }

    size = sizeof(cores_per_package);
    if(sysctlbyname("machdep.cpu.cores_per_package", &cores_per_package, &size, NULL, 0))
        cores_per_package = lcpu_no;

    for(i=0; i<(lcpu_no+cores_per_package-1)/cores_per_package; i++)
    {
        mask = 0;
        for(j=cores_per_package*i; j<cores_per_package*(i+1) && j<lcpu_no; j++)
            mask |= (ULONG_PTR)1<<j;

        (*data)[len].Relationship = RelationProcessorPackage;
        (*data)[len].ProcessorMask = mask;
        len++;
    }

1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
    memset(cache, 0, sizeof(cache));
    cache[0].Level = 1;
    cache[0].Type = CacheInstruction;
    cache[1].Level = 1;
    cache[1].Type = CacheData;
    cache[2].Level = 2;
    cache[2].Type = CacheUnified;
    cache[3].Level = 3;
    cache[3].Type = CacheUnified;

    size = sizeof(cache_line_size);
    if(!sysctlbyname("hw.cachelinesize", &cache_line_size, &size, NULL, 0))
    {
        for(i=0; i<4; i++)
            cache[i].LineSize = cache_line_size;
    }

    /* TODO: set associativity for all caches */
    size = sizeof(assoc);
    if(!sysctlbyname("machdep.cpu.cache.L2_associativity", &assoc, &size, NULL, 0))
        cache[2].Associativity = assoc;

    size = sizeof(cache_size);
    if(!sysctlbyname("hw.l1icachesize", &cache_size, &size, NULL, 0))
        cache[0].Size = cache_size;
    size = sizeof(cache_size);
    if(!sysctlbyname("hw.l1dcachesize", &cache_size, &size, NULL, 0))
        cache[1].Size = cache_size;
    size = sizeof(cache_size);
    if(!sysctlbyname("hw.l2cachesize", &cache_size, &size, NULL, 0))
        cache[2].Size = cache_size;
    size = sizeof(cache_size);
    if(!sysctlbyname("hw.l3cachesize", &cache_size, &size, NULL, 0))
        cache[3].Size = cache_size;

    size = sizeof(cache_sharing);
    if(!sysctlbyname("hw.cacheconfig", cache_sharing, &size, NULL, 0))
    {
        for(i=1; i<4 && i<size/sizeof(*cache_sharing); i++)
        {
            if(!cache_sharing[i] || !cache[i].Size)
                continue;

            for(j=0; j<lcpu_no/cache_sharing[i]; j++)
            {
                mask = 0;
                for(k=j*cache_sharing[i]; k<lcpu_no && k<(j+1)*cache_sharing[i]; k++)
                    mask |= (ULONG_PTR)1<<k;

                if(i==1 && cache[0].Size)
                {
                    (*data)[len].Relationship = RelationCache;
                    (*data)[len].ProcessorMask = mask;
                    (*data)[len].u.Cache = cache[0];
                    len++;
                }

                (*data)[len].Relationship = RelationCache;
                (*data)[len].ProcessorMask = mask;
                (*data)[len].u.Cache = cache[i];
                len++;
            }
        }
    }

1641 1642 1643 1644 1645 1646 1647 1648
    mask = 0;
    for(i=0; i<lcpu_no; i++)
        mask |= (ULONG_PTR)1<<i;
    (*data)[len].Relationship = RelationNumaNode;
    (*data)[len].ProcessorMask = mask;
    (*data)[len].u.NumaNode.NodeNumber = 0;
    len++;

1649 1650 1651
    *max_len = len * sizeof(**data);
    return STATUS_SUCCESS;
}
1652 1653 1654 1655 1656 1657 1658 1659
#else
static NTSTATUS create_logical_proc_info(SYSTEM_LOGICAL_PROCESSOR_INFORMATION **data, DWORD *max_len)
{
    FIXME("stub\n");
    return STATUS_NOT_IMPLEMENTED;
}
#endif

Juergen Schmied's avatar
Juergen Schmied committed
1660
/******************************************************************************
1661
 * NtQuerySystemInformation [NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1662
 * ZwQuerySystemInformation [NTDLL.@]
Juergen Schmied's avatar
Juergen Schmied committed
1663 1664 1665 1666 1667 1668
 *
 * ARGUMENTS:
 *  SystemInformationClass	Index to a certain information structure
 *	SystemTimeAdjustmentInformation	SYSTEM_TIME_ADJUSTMENT
 *	SystemCacheInformation		SYSTEM_CACHE_INFORMATION
 *	SystemConfigurationInformation	CONFIGURATION_INFORMATION
1669
 *	observed (class/len):
Juergen Schmied's avatar
Juergen Schmied committed
1670 1671 1672 1673
 *		0x0/0x2c
 *		0x12/0x18
 *		0x2/0x138
 *		0x8/0x600
1674
 *              0x25/0xc
Juergen Schmied's avatar
Juergen Schmied committed
1675 1676 1677
 *  SystemInformation	caller supplies storage for the information structure
 *  Length		size of the structure
 *  ResultLength	Data written
1678
 */
Juergen Schmied's avatar
Juergen Schmied committed
1679 1680 1681 1682 1683
NTSTATUS WINAPI NtQuerySystemInformation(
	IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
	OUT PVOID SystemInformation,
	IN ULONG Length,
	OUT PULONG ResultLength)
1684
{
1685 1686 1687
    NTSTATUS    ret = STATUS_SUCCESS;
    ULONG       len = 0;

1688
    TRACE("(0x%08x,%p,0x%08x,%p)\n",
1689 1690 1691
          SystemInformationClass,SystemInformation,Length,ResultLength);

    switch (SystemInformationClass)
1692
    {
1693 1694
    case SystemBasicInformation:
        {
1695 1696
            SYSTEM_BASIC_INFORMATION sbi;

1697
            virtual_get_system_info( &sbi );
1698 1699
            len = sizeof(sbi);

1700
            if ( Length == len)
1701
            {
1702 1703
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else memcpy( SystemInformation, &sbi, len);
1704 1705 1706 1707
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
        }
        break;
1708
    case SystemCpuInformation:
1709
        if (Length >= (len = sizeof(cached_sci)))
1710
        {
1711 1712
            if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
            else memcpy(SystemInformation, &cached_sci, len);
1713
        }
1714
        else ret = STATUS_INFO_LENGTH_MISMATCH;
1715
        break;
1716 1717
    case SystemPerformanceInformation:
        {
1718
            SYSTEM_PERFORMANCE_INFORMATION spi;
1719
            static BOOL fixme_written = FALSE;
1720
            FILE *fp;
1721 1722 1723 1724

            memset(&spi, 0 , sizeof(spi));
            len = sizeof(spi);

1725 1726
            spi.Reserved3 = 0x7fffffff; /* Available paged pool memory? */

1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
            if ((fp = fopen("/proc/uptime", "r")))
            {
                double uptime, idle_time;

                fscanf(fp, "%lf %lf", &uptime, &idle_time);
                fclose(fp);
                spi.IdleTime.QuadPart = 10000000 * idle_time;
            }
            else
            {
                static ULONGLONG idle;
                /* many programs expect IdleTime to change so fake change */
                spi.IdleTime.QuadPart = ++idle;
            }

1742
            if (Length >= len)
1743
            {
1744 1745
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else memcpy( SystemInformation, &spi, len);
1746 1747
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
1748 1749 1750 1751
            if(!fixme_written) {
                FIXME("info_class SYSTEM_PERFORMANCE_INFORMATION\n");
                fixme_written = TRUE;
            }
1752 1753 1754 1755
        }
        break;
    case SystemTimeOfDayInformation:
        {
1756 1757 1758 1759 1760
            SYSTEM_TIMEOFDAY_INFORMATION sti;

            memset(&sti, 0 , sizeof(sti));

            /* liKeSystemTime, liExpTimeZoneBias, uCurrentTimeZoneId */
1761
            sti.liKeBootTime.QuadPart = server_start_time;
1762 1763

            if (Length <= sizeof(sti))
1764
            {
1765 1766 1767
                len = Length;
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else memcpy( SystemInformation, &sti, Length);
1768 1769 1770 1771 1772 1773
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
        }
        break;
    case SystemProcessInformation:
        {
1774
            SYSTEM_PROCESS_INFORMATION* spi = SystemInformation;
1775 1776
            SYSTEM_PROCESS_INFORMATION* last = NULL;
            HANDLE hSnap = 0;
1777
            WCHAR procname[1024];
1778
            WCHAR* exename;
1779
            DWORD wlen = 0;
1780
            DWORD procstructlen = 0;
1781 1782 1783

            SERVER_START_REQ( create_snapshot )
            {
1784 1785
                req->flags      = SNAP_PROCESS | SNAP_THREAD;
                req->attributes = 0;
1786 1787
                if (!(ret = wine_server_call( req )))
                    hSnap = wine_server_ptr_handle( reply->handle );
1788 1789 1790 1791 1792 1793 1794
            }
            SERVER_END_REQ;
            len = 0;
            while (ret == STATUS_SUCCESS)
            {
                SERVER_START_REQ( next_process )
                {
1795
                    req->handle = wine_server_obj_handle( hSnap );
1796
                    req->reset = (len == 0);
1797
                    wine_server_set_reply( req, procname, sizeof(procname)-sizeof(WCHAR) );
1798 1799
                    if (!(ret = wine_server_call( req )))
                    {
1800 1801 1802 1803 1804 1805 1806 1807 1808
                        /* Make sure procname is 0 terminated */
                        procname[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;

                        /* Get only the executable name, not the path */
                        if ((exename = strrchrW(procname, '\\')) != NULL) exename++;
                        else exename = procname;

                        wlen = (strlenW(exename) + 1) * sizeof(WCHAR);

1809
                        procstructlen = sizeof(*spi) + wlen + ((reply->threads - 1) * sizeof(SYSTEM_THREAD_INFORMATION));
1810

1811
                        if (Length >= len + procstructlen)
1812
                        {
Paul Vriens's avatar
Paul Vriens committed
1813
                            /* ftCreationTime, ftUserTime, ftKernelTime;
1814 1815 1816
                             * vmCounters, ioCounters
                             */
 
1817
                            memset(spi, 0, sizeof(*spi));
1818

1819
                            spi->NextEntryOffset = procstructlen - wlen;
1820
                            spi->dwThreadCount = reply->threads;
1821

1822
                            /* spi->pszProcessName will be set later on */
1823

1824
                            spi->dwBasePriority = reply->priority;
1825 1826 1827
                            spi->UniqueProcessId = UlongToHandle(reply->pid);
                            spi->ParentProcessId = UlongToHandle(reply->ppid);
                            spi->HandleCount = reply->handles;
1828

1829
                            /* spi->ti will be set later on */
1830

1831
                        }
1832
                        len += procstructlen;
1833 1834 1835
                    }
                }
                SERVER_END_REQ;
1836
 
1837 1838 1839 1840 1841
                if (ret != STATUS_SUCCESS)
                {
                    if (ret == STATUS_NO_MORE_FILES) ret = STATUS_SUCCESS;
                    break;
                }
1842 1843

                if (Length >= len)
1844 1845 1846 1847 1848 1849 1850 1851 1852
                {
                    int     i, j;

                    /* set thread info */
                    i = j = 0;
                    while (ret == STATUS_SUCCESS)
                    {
                        SERVER_START_REQ( next_thread )
                        {
1853
                            req->handle = wine_server_obj_handle( hSnap );
1854 1855 1856 1857
                            req->reset = (j == 0);
                            if (!(ret = wine_server_call( req )))
                            {
                                j++;
1858
                                if (UlongToHandle(reply->pid) == spi->UniqueProcessId)
1859 1860 1861 1862
                                {
                                    /* ftKernelTime, ftUserTime, ftCreateTime;
                                     * dwTickCount, dwStartAddress
                                     */
Paul Vriens's avatar
Paul Vriens committed
1863 1864 1865

                                    memset(&spi->ti[i], 0, sizeof(spi->ti));

1866 1867 1868
                                    spi->ti[i].CreateTime.QuadPart = 0xdeadbeef;
                                    spi->ti[i].ClientId.UniqueProcess = UlongToHandle(reply->pid);
                                    spi->ti[i].ClientId.UniqueThread  = UlongToHandle(reply->tid);
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
                                    spi->ti[i].dwCurrentPriority = reply->base_pri + reply->delta_pri;
                                    spi->ti[i].dwBasePriority = reply->base_pri;
                                    i++;
                                }
                            }
                        }
                        SERVER_END_REQ;
                    }
                    if (ret == STATUS_NO_MORE_FILES) ret = STATUS_SUCCESS;

                    /* now append process name */
1880
                    spi->ProcessName.Buffer = (WCHAR*)((char*)spi + spi->NextEntryOffset);
1881 1882
                    spi->ProcessName.Length = wlen - sizeof(WCHAR);
                    spi->ProcessName.MaximumLength = wlen;
1883
                    memcpy( spi->ProcessName.Buffer, exename, wlen );
1884
                    spi->NextEntryOffset += wlen;
1885 1886

                    last = spi;
1887
                    spi = (SYSTEM_PROCESS_INFORMATION*)((char*)spi + spi->NextEntryOffset);
1888 1889
                }
            }
1890
            if (ret == STATUS_SUCCESS && last) last->NextEntryOffset = 0;
1891
            if (len > Length) ret = STATUS_INFO_LENGTH_MISMATCH;
1892 1893 1894 1895 1896
            if (hSnap) NtClose(hSnap);
        }
        break;
    case SystemProcessorPerformanceInformation:
        {
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
            SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *sppi = NULL;
            unsigned int cpus = 0;
            int out_cpus = Length / sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION);

            if (out_cpus == 0)
            {
                len = 0;
                ret = STATUS_INFO_LENGTH_MISMATCH;
                break;
            }
            else
#ifdef __APPLE__
            {
                processor_cpu_load_info_data_t *pinfo;
                mach_msg_type_number_t info_count;

                if (host_processor_info (mach_host_self (),
                                         PROCESSOR_CPU_LOAD_INFO,
                                         &cpus,
                                         (processor_info_array_t*)&pinfo,
                                         &info_count) == 0)
                {
                    int i;
                    cpus = min(cpus,out_cpus);
                    len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
                    sppi = RtlAllocateHeap(GetProcessHeap(), 0,len);
                    for (i = 0; i < cpus; i++)
                    {
1925 1926 1927
                        sppi[i].IdleTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_IDLE];
                        sppi[i].KernelTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_SYSTEM];
                        sppi[i].UserTime.QuadPart = pinfo[i].cpu_ticks[CPU_STATE_USER];
1928
                    }
1929
                    vm_deallocate (mach_task_self (), (vm_address_t) pinfo, info_count * sizeof(natural_t));
1930 1931 1932 1933
                }
            }
#else
            {
1934
                FILE *cpuinfo = fopen("/proc/stat", "r");
1935 1936
                if (cpuinfo)
                {
1937
                    unsigned long clk_tck = sysconf(_SC_CLK_TCK);
1938
                    unsigned long usr,nice,sys,idle,remainder[8];
1939 1940
                    int i, count;
                    char name[32];
1941
                    char line[255];
1942 1943

                    /* first line is combined usage */
1944
                    while (fgets(line,255,cpuinfo))
1945
                    {
1946 1947 1948 1949 1950 1951 1952 1953
                        count = sscanf(line, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
                                       name, &usr, &nice, &sys, &idle,
                                       &remainder[0], &remainder[1], &remainder[2], &remainder[3],
                                       &remainder[4], &remainder[5], &remainder[6], &remainder[7]);

                        if (count < 5 || strncmp( name, "cpu", 3 )) break;
                        for (i = 0; i + 5 < count; ++i) sys += remainder[i];
                        sys += idle;
1954
                        usr += nice;
1955 1956 1957 1958 1959
                        cpus = atoi( name + 3 ) + 1;
                        if (cpus > out_cpus) break;
                        len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
                        if (sppi)
                            sppi = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sppi, len );
1960
                        else
1961 1962 1963 1964 1965 1966
                            sppi = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, len );

                        sppi[cpus-1].IdleTime.QuadPart   = (ULONGLONG)idle * 10000000 / clk_tck;
                        sppi[cpus-1].KernelTime.QuadPart = (ULONGLONG)sys * 10000000 / clk_tck;
                        sppi[cpus-1].UserTime.QuadPart   = (ULONGLONG)usr * 10000000 / clk_tck;
                    }
1967 1968 1969 1970 1971 1972 1973 1974
                    fclose(cpuinfo);
                }
            }
#endif

            if (cpus == 0)
            {
                static int i = 1;
1975
                unsigned int n;
1976 1977 1978
                cpus = min(NtCurrentTeb()->Peb->NumberOfProcessors, out_cpus);
                len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
                sppi = RtlAllocateHeap(GetProcessHeap(), 0, len);
1979 1980
                FIXME("stub info_class SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION\n");
                /* many programs expect these values to change so fake change */
1981 1982 1983 1984 1985 1986
                for (n = 0; n < cpus; n++)
                {
                    sppi[n].KernelTime.QuadPart = 1 * i;
                    sppi[n].UserTime.QuadPart   = 2 * i;
                    sppi[n].IdleTime.QuadPart   = 3 * i;
                }
1987 1988
                i++;
            }
1989 1990

            if (Length >= len)
1991
            {
1992
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1993
                else memcpy( SystemInformation, sppi, len);
1994 1995
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
1996 1997

            RtlFreeHeap(GetProcessHeap(),0,sppi);
1998 1999
        }
        break;
2000
    case SystemModuleInformation:
2001
        /* FIXME: should be system-wide */
2002 2003
        if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
        else ret = LdrQueryProcessModuleInformation( SystemInformation, Length, &len );
2004
        break;
2005 2006 2007 2008 2009 2010
    case SystemHandleInformation:
        {
            SYSTEM_HANDLE_INFORMATION shi;

            memset(&shi, 0, sizeof(shi));
            len = sizeof(shi);
2011

2012 2013 2014 2015 2016 2017
            if ( Length >= len)
            {
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else memcpy( SystemInformation, &shi, len);
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
2018
            FIXME("info_class SYSTEM_HANDLE_INFORMATION\n");
2019 2020
        }
        break;
2021 2022
    case SystemCacheInformation:
        {
2023 2024 2025 2026 2027 2028
            SYSTEM_CACHE_INFORMATION sci;

            memset(&sci, 0, sizeof(sci)); /* FIXME */
            len = sizeof(sci);

            if ( Length >= len)
2029
            {
2030 2031
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else memcpy( SystemInformation, &sci, len);
2032 2033
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
2034
            FIXME("info_class SYSTEM_CACHE_INFORMATION\n");
2035 2036
        }
        break;
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
    case SystemInterruptInformation:
        {
            SYSTEM_INTERRUPT_INFORMATION sii;

            memset(&sii, 0, sizeof(sii));
            len = sizeof(sii);

            if ( Length >= len)
            {
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else memcpy( SystemInformation, &sii, len);
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
2050
            FIXME("info_class SYSTEM_INTERRUPT_INFORMATION\n");
2051 2052
        }
        break;
2053 2054
    case SystemKernelDebuggerInformation:
        {
2055 2056 2057 2058 2059 2060 2061
            SYSTEM_KERNEL_DEBUGGER_INFORMATION skdi;

            skdi.DebuggerEnabled = FALSE;
            skdi.DebuggerNotPresent = TRUE;
            len = sizeof(skdi);

            if ( Length >= len)
2062
            {
2063 2064
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else memcpy( SystemInformation, &skdi, len);
2065 2066 2067 2068
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
        }
        break;
2069 2070
    case SystemRegistryQuotaInformation:
        {
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
	    /* Something to do with the size of the registry             *
	     * Since we don't have a size limitation, fake it            *
	     * This is almost certainly wrong.                           *
	     * This sets each of the three words in the struct to 32 MB, *
	     * which is enough to make the IE 5 installer happy.         */
            SYSTEM_REGISTRY_QUOTA_INFORMATION srqi;

            srqi.RegistryQuotaAllowed = 0x2000000;
            srqi.RegistryQuotaUsed = 0x200000;
            srqi.Reserved1 = (void*)0x200000;
            len = sizeof(srqi);

            if ( Length >= len)
2084
            {
2085 2086 2087 2088 2089 2090
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else
                {
                    FIXME("SystemRegistryQuotaInformation: faking max registry size of 32 MB\n");
                    memcpy( SystemInformation, &srqi, len);
                }
2091 2092 2093
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
        }
2094
	break;
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
    case SystemLogicalProcessorInformation:
        {
            SYSTEM_LOGICAL_PROCESSOR_INFORMATION *buf;

            /* Each logical processor may use up to 7 entries in returned table:
             * core, numa node, package, L1i, L1d, L2, L3 */
            len = 7 * NtCurrentTeb()->Peb->NumberOfProcessors;
            buf = RtlAllocateHeap(GetProcessHeap(), 0, len * sizeof(*buf));
            if(!buf)
            {
                ret = STATUS_NO_MEMORY;
                break;
            }

            ret = create_logical_proc_info(&buf, &len);
            if( ret != STATUS_SUCCESS )
            {
                RtlFreeHeap(GetProcessHeap(), 0, buf);
                break;
            }

            if( Length >= len)
            {
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else memcpy( SystemInformation, buf, len);
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
            RtlFreeHeap(GetProcessHeap(), 0, buf);
        }
        break;
2125
    default:
2126
	FIXME("(0x%08x,%p,0x%08x,%p) stub\n",
2127
	      SystemInformationClass,SystemInformation,Length,ResultLength);
2128 2129 2130 2131 2132 2133

        /* Several Information Classes are not implemented on Windows and return 2 different values 
         * STATUS_NOT_IMPLEMENTED or STATUS_INVALID_INFO_CLASS
         * in 95% of the cases it's STATUS_INVALID_INFO_CLASS, so use this as the default
        */
        ret = STATUS_INVALID_INFO_CLASS;
2134
    }
2135

2136
    if (ResultLength) *ResultLength = len;
2137

2138
    return ret;
Juergen Schmied's avatar
Juergen Schmied committed
2139 2140
}

2141 2142 2143 2144 2145 2146
/******************************************************************************
 * NtSetSystemInformation [NTDLL.@]
 * ZwSetSystemInformation [NTDLL.@]
 */
NTSTATUS WINAPI NtSetSystemInformation(SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG Length)
{
2147
    FIXME("(0x%08x,%p,0x%08x) stub\n",SystemInformationClass,SystemInformation,Length);
2148 2149
    return STATUS_SUCCESS;
}
2150

2151
/******************************************************************************
2152
 *  NtCreatePagingFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
2153
 *  ZwCreatePagingFile		[NTDLL.@]
2154
 */
Juergen Schmied's avatar
Juergen Schmied committed
2155
NTSTATUS WINAPI NtCreatePagingFile(
2156
	PUNICODE_STRING PageFileName,
2157 2158
	PLARGE_INTEGER MinimumSize,
	PLARGE_INTEGER MaximumSize,
2159
	PLARGE_INTEGER ActualSize)
2160
{
2161
    FIXME("(%p %p %p %p) stub\n", PageFileName, MinimumSize, MaximumSize, ActualSize);
2162
    return STATUS_SUCCESS;
2163 2164
}

2165
/******************************************************************************
2166
 *  NtDisplayString				[NTDLL.@]
2167
 *
2168 2169
 * writes a string to the nt-textmode screen eg. during startup
 */
2170
NTSTATUS WINAPI NtDisplayString ( PUNICODE_STRING string )
2171
{
2172 2173 2174 2175 2176 2177 2178 2179 2180
    STRING stringA;
    NTSTATUS ret;

    if (!(ret = RtlUnicodeStringToAnsiString( &stringA, string, TRUE )))
    {
        MESSAGE( "%.*s", stringA.Length, stringA.Buffer );
        RtlFreeAnsiString( &stringA );
    }
    return ret;
2181
}
2182

2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
/******************************************************************************
 *  NtInitiatePowerAction                       [NTDLL.@]
 *
 */
NTSTATUS WINAPI NtInitiatePowerAction(
	IN POWER_ACTION SystemAction,
	IN SYSTEM_POWER_STATE MinSystemState,
	IN ULONG Flags,
	IN BOOLEAN Asynchronous)
{
2193
        FIXME("(%d,%d,0x%08x,%d),stub\n",
2194 2195 2196
		SystemAction,MinSystemState,Flags,Asynchronous);
        return STATUS_NOT_IMPLEMENTED;
}
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225

#ifdef linux
/* Fallback using /proc/cpuinfo for Linux systems without cpufreq. For
 * most distributions on recent enough hardware, this is only likely to
 * happen while running in virtualized environments such as QEMU. */
static ULONG mhz_from_cpuinfo(void)
{
    char line[512];
    char *s, *value;
    double cmz = 0;
    FILE* f = fopen("/proc/cpuinfo", "r");
    if(f) {
        while (fgets(line, sizeof(line), f) != NULL) {
            if (!(value = strchr(line,':')))
                continue;
            s = value - 1;
            while ((s >= line) && isspace(*s)) s--;
            *(s + 1) = '\0';
            value++;
            if (!strcasecmp(line, "cpu MHz")) {
                sscanf(value, " %lf", &cmz);
                break;
            }
        }
        fclose(f);
    }
    return cmz;
}
#endif
2226

2227
/******************************************************************************
2228
 *  NtPowerInformation				[NTDLL.@]
2229
 *
2230
 */
2231 2232 2233 2234 2235 2236
NTSTATUS WINAPI NtPowerInformation(
	IN POWER_INFORMATION_LEVEL InformationLevel,
	IN PVOID lpInputBuffer,
	IN ULONG nInputBufferSize,
	IN PVOID lpOutputBuffer,
	IN ULONG nOutputBufferSize)
2237
{
2238
	TRACE("(%d,%p,%d,%p,%d)\n",
2239
		InformationLevel,lpInputBuffer,nInputBufferSize,lpOutputBuffer,nOutputBufferSize);
2240 2241
	switch(InformationLevel) {
		case SystemPowerCapabilities: {
2242
			PSYSTEM_POWER_CAPABILITIES PowerCaps = lpOutputBuffer;
2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279
			FIXME("semi-stub: SystemPowerCapabilities\n");
			if (nOutputBufferSize < sizeof(SYSTEM_POWER_CAPABILITIES))
				return STATUS_BUFFER_TOO_SMALL;
			/* FIXME: These values are based off a native XP desktop, should probably use APM/ACPI to get the 'real' values */
			PowerCaps->PowerButtonPresent = TRUE;
			PowerCaps->SleepButtonPresent = FALSE;
			PowerCaps->LidPresent = FALSE;
			PowerCaps->SystemS1 = TRUE;
			PowerCaps->SystemS2 = FALSE;
			PowerCaps->SystemS3 = FALSE;
			PowerCaps->SystemS4 = TRUE;
			PowerCaps->SystemS5 = TRUE;
			PowerCaps->HiberFilePresent = TRUE;
			PowerCaps->FullWake = TRUE;
			PowerCaps->VideoDimPresent = FALSE;
			PowerCaps->ApmPresent = FALSE;
			PowerCaps->UpsPresent = FALSE;
			PowerCaps->ThermalControl = FALSE;
			PowerCaps->ProcessorThrottle = FALSE;
			PowerCaps->ProcessorMinThrottle = 100;
			PowerCaps->ProcessorMaxThrottle = 100;
			PowerCaps->DiskSpinDown = TRUE;
			PowerCaps->SystemBatteriesPresent = FALSE;
			PowerCaps->BatteriesAreShortTerm = FALSE;
			PowerCaps->BatteryScale[0].Granularity = 0;
			PowerCaps->BatteryScale[0].Capacity = 0;
			PowerCaps->BatteryScale[1].Granularity = 0;
			PowerCaps->BatteryScale[1].Capacity = 0;
			PowerCaps->BatteryScale[2].Granularity = 0;
			PowerCaps->BatteryScale[2].Capacity = 0;
			PowerCaps->AcOnLineWake = PowerSystemUnspecified;
			PowerCaps->SoftLidWake = PowerSystemUnspecified;
			PowerCaps->RtcWake = PowerSystemSleeping1;
			PowerCaps->MinDeviceWakeState = PowerSystemUnspecified;
			PowerCaps->DefaultLowLatencyWake = PowerSystemUnspecified;
			return STATUS_SUCCESS;
		}
2280 2281
		case SystemExecutionState: {
			PULONG ExecutionState = lpOutputBuffer;
2282
			WARN("semi-stub: SystemExecutionState\n"); /* Needed for .NET Framework, but using a FIXME is really noisy. */
2283 2284 2285 2286 2287 2288
			if (lpInputBuffer != NULL)
				return STATUS_INVALID_PARAMETER;
			/* FIXME: The actual state should be the value set by SetThreadExecutionState which is not currently implemented. */
			*ExecutionState = ES_USER_PRESENT;
			return STATUS_SUCCESS;
		}
2289
		case ProcessorInformation: {
2290
			const int cannedMHz = 1000; /* We fake a 1GHz processor if we can't conjure up real values */
2291
			PROCESSOR_POWER_INFORMATION* cpu_power = lpOutputBuffer;
2292
			int i, out_cpus;
2293 2294 2295

			if ((lpOutputBuffer == NULL) || (nOutputBufferSize == 0))
				return STATUS_INVALID_PARAMETER;
2296 2297
			out_cpus = NtCurrentTeb()->Peb->NumberOfProcessors;
			if ((nOutputBufferSize / sizeof(PROCESSOR_POWER_INFORMATION)) < out_cpus)
2298
				return STATUS_BUFFER_TOO_SMALL;
2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396
#if defined(linux)
			{
				char filename[128];
				FILE* f;

				for(i = 0; i < out_cpus; i++) {
					sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq", i);
					f = fopen(filename, "r");
					if (f && (fscanf(f, "%d", &cpu_power[i].CurrentMhz) == 1)) {
						cpu_power[i].CurrentMhz /= 1000;
						fclose(f);
					}
					else {
						if(i == 0) {
							cpu_power[0].CurrentMhz = mhz_from_cpuinfo();
							if(cpu_power[0].CurrentMhz == 0)
								cpu_power[0].CurrentMhz = cannedMHz;
						}
						else
							cpu_power[i].CurrentMhz = cpu_power[0].CurrentMhz;
						if(f) fclose(f);
					}

					sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", i);
					f = fopen(filename, "r");
					if (f && (fscanf(f, "%d", &cpu_power[i].MaxMhz) == 1)) {
						cpu_power[i].MaxMhz /= 1000;
						fclose(f);
					}
					else {
						cpu_power[i].MaxMhz = cpu_power[i].CurrentMhz;
						if(f) fclose(f);
					}

					sprintf(filename, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_max_freq", i);
					f = fopen(filename, "r");
					if(f && (fscanf(f, "%d", &cpu_power[i].MhzLimit) == 1)) {
						cpu_power[i].MhzLimit /= 1000;
						fclose(f);
					}
					else
					{
						cpu_power[i].MhzLimit = cpu_power[i].MaxMhz;
						if(f) fclose(f);
					}

					cpu_power[i].Number = i;
					cpu_power[i].MaxIdleState = 0;     /* FIXME */
					cpu_power[i].CurrentIdleState = 0; /* FIXME */
				}
			}
#elif defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__DragonFly__)
			{
				int num;
				size_t valSize = sizeof(num);
				if (sysctlbyname("hw.clockrate", &num, &valSize, NULL, 0))
					num = cannedMHz;
				for(i = 0; i < out_cpus; i++) {
					cpu_power[i].CurrentMhz = num;
					cpu_power[i].MaxMhz = num;
					cpu_power[i].MhzLimit = num;
					cpu_power[i].Number = i;
					cpu_power[i].MaxIdleState = 0;     /* FIXME */
					cpu_power[i].CurrentIdleState = 0; /* FIXME */
				}
			}
#elif defined (__APPLE__)
			{
				size_t valSize;
				unsigned long long currentMhz;
				unsigned long long maxMhz;

				valSize = sizeof(currentMhz);
				if (!sysctlbyname("hw.cpufrequency", &currentMhz, &valSize, NULL, 0))
					currentMhz /= 1000000;
				else
					currentMhz = cannedMHz;

				valSize = sizeof(maxMhz);
				if (!sysctlbyname("hw.cpufrequency_max", &maxMhz, &valSize, NULL, 0))
					maxMhz /= 1000000;
				else
					maxMhz = currentMhz;

				for(i = 0; i < out_cpus; i++) {
					cpu_power[i].CurrentMhz = currentMhz;
					cpu_power[i].MaxMhz = maxMhz;
					cpu_power[i].MhzLimit = maxMhz;
					cpu_power[i].Number = i;
					cpu_power[i].MaxIdleState = 0;     /* FIXME */
					cpu_power[i].CurrentIdleState = 0; /* FIXME */
				}
			}
#else
			for(i = 0; i < out_cpus; i++) {
				cpu_power[i].CurrentMhz = cannedMHz;
				cpu_power[i].MaxMhz = cannedMHz;
				cpu_power[i].MhzLimit = cannedMHz;
2397 2398 2399 2400
				cpu_power[i].Number = i;
				cpu_power[i].MaxIdleState = 0; /* FIXME */
				cpu_power[i].CurrentIdleState = 0; /* FIXME */
			}
2401 2402 2403 2404 2405 2406 2407
			WARN("Unable to detect CPU MHz for this platform. Reporting %d MHz.\n", cannedMHz);
#endif
			for(i = 0; i < out_cpus; i++) {
				TRACE("cpu_power[%d] = %u %u %u %u %u %u\n", i, cpu_power[i].Number,
					  cpu_power[i].MaxMhz, cpu_power[i].CurrentMhz, cpu_power[i].MhzLimit,
					  cpu_power[i].MaxIdleState, cpu_power[i].CurrentIdleState);
			}
2408 2409
			return STATUS_SUCCESS;
		}
2410
		default:
2411 2412
			/* FIXME: Needed by .NET Framework */
			WARN("Unimplemented NtPowerInformation action: %d\n", InformationLevel);
2413 2414
			return STATUS_NOT_IMPLEMENTED;
	}
2415
}
2416

2417 2418 2419 2420
/******************************************************************************
 *  NtShutdownSystem				[NTDLL.@]
 *
 */
2421
NTSTATUS WINAPI NtShutdownSystem(SHUTDOWN_ACTION Action)
2422
{
2423 2424
    FIXME("%d\n",Action);
    return STATUS_SUCCESS;
2425 2426
}

2427
/******************************************************************************
2428
 *  NtAllocateLocallyUniqueId (NTDLL.@)
2429 2430 2431
 */
NTSTATUS WINAPI NtAllocateLocallyUniqueId(PLUID Luid)
{
2432
    NTSTATUS status;
2433

2434
    TRACE("%p\n", Luid);
2435 2436 2437

    if (!Luid)
        return STATUS_ACCESS_VIOLATION;
2438

2439 2440 2441 2442 2443 2444 2445 2446 2447 2448
    SERVER_START_REQ( allocate_locally_unique_id )
    {
        status = wine_server_call( req );
        if (!status)
        {
            Luid->LowPart = reply->luid.low_part;
            Luid->HighPart = reply->luid.high_part;
        }
    }
    SERVER_END_REQ;
Francois Gouget's avatar
Francois Gouget committed
2449

2450
    return status;
2451
}
2452 2453 2454 2455 2456 2457 2458

/******************************************************************************
 *        VerSetConditionMask   (NTDLL.@)
 */
ULONGLONG WINAPI VerSetConditionMask( ULONGLONG dwlConditionMask, DWORD dwTypeBitMask,
                                      BYTE dwConditionMask)
{
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
    if(dwTypeBitMask == 0)
	return dwlConditionMask;
    dwConditionMask &= 0x07;
    if(dwConditionMask == 0)
	return dwlConditionMask;

    if(dwTypeBitMask & VER_PRODUCT_TYPE)
	dwlConditionMask |= dwConditionMask << 7*3;
    else if (dwTypeBitMask & VER_SUITENAME)
	dwlConditionMask |= dwConditionMask << 6*3;
    else if (dwTypeBitMask & VER_SERVICEPACKMAJOR)
	dwlConditionMask |= dwConditionMask << 5*3;
    else if (dwTypeBitMask & VER_SERVICEPACKMINOR)
	dwlConditionMask |= dwConditionMask << 4*3;
    else if (dwTypeBitMask & VER_PLATFORMID)
	dwlConditionMask |= dwConditionMask << 3*3;
    else if (dwTypeBitMask & VER_BUILDNUMBER)
	dwlConditionMask |= dwConditionMask << 2*3;
    else if (dwTypeBitMask & VER_MAJORVERSION)
	dwlConditionMask |= dwConditionMask << 1*3;
    else if (dwTypeBitMask & VER_MINORVERSION)
	dwlConditionMask |= dwConditionMask << 0*3;
2481 2482
    return dwlConditionMask;
}
2483 2484 2485 2486 2487 2488 2489 2490 2491 2492

/******************************************************************************
 *  NtAccessCheckAndAuditAlarm   (NTDLL.@)
 *  ZwAccessCheckAndAuditAlarm   (NTDLL.@)
 */
NTSTATUS WINAPI NtAccessCheckAndAuditAlarm(PUNICODE_STRING SubsystemName, HANDLE HandleId, PUNICODE_STRING ObjectTypeName,
                                           PUNICODE_STRING ObjectName, PSECURITY_DESCRIPTOR SecurityDescriptor,
                                           ACCESS_MASK DesiredAccess, PGENERIC_MAPPING GenericMapping, BOOLEAN ObjectCreation,
                                           PACCESS_MASK GrantedAccess, PBOOLEAN AccessStatus, PBOOLEAN GenerateOnClose)
{
2493
    FIXME("(%s, %p, %s, %p, 0x%08x, %p, %d, %p, %p, %p), stub\n", debugstr_us(SubsystemName), HandleId,
2494 2495 2496 2497 2498
          debugstr_us(ObjectTypeName), SecurityDescriptor, DesiredAccess, GenericMapping, ObjectCreation,
          GrantedAccess, AccessStatus, GenerateOnClose);

    return STATUS_NOT_IMPLEMENTED;
}
2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510

/******************************************************************************
 *  NtSystemDebugControl   (NTDLL.@)
 *  ZwSystemDebugControl   (NTDLL.@)
 */
NTSTATUS WINAPI NtSystemDebugControl(SYSDBG_COMMAND command, PVOID inbuffer, ULONG inbuflength, PVOID outbuffer,
                                     ULONG outbuflength, PULONG retlength)
{
    FIXME("(%d, %p, %d, %p, %d, %p), stub\n", command, inbuffer, inbuflength, outbuffer, outbuflength, retlength);

    return STATUS_NOT_IMPLEMENTED;
}