nt.c 73.9 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 226 227 228 229 230 231 232
                                   BufferLength - FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ) );
        ret = wine_server_call( req );
        if (PreviousState)
        {
            *ReturnLength = reply->len + FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges );
            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 266 267 268 269 270 271
    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 */
        0,    /* TokenSessionId */
        0,    /* TokenGroupsAndPrivileges */
        0,    /* TokenSessionReference */
        0,    /* TokenSandBoxInert */
        0,    /* TokenAuditPolicy */
        0,    /* TokenOrigin */
272
        sizeof(TOKEN_ELEVATION_TYPE), /* TokenElevationType */
273 274 275 276 277 278 279 280 281 282 283 284 285
        0,    /* TokenLinkedToken */
        sizeof(TOKEN_ELEVATION), /* TokenElevation */
        0,    /* TokenHasRestrictions */
        0,    /* TokenAccessInformation */
        0,    /* TokenVirtualizationAllowed */
        0,    /* TokenVirtualizationEnabled */
        0,    /* TokenIntegrityLevel */
        0,    /* TokenUIAccess */
        0,    /* TokenMandatoryPolicy */
        0     /* TokenLogonSid */
    };

    ULONG len = 0;
286
    NTSTATUS status = STATUS_SUCCESS;
287

288
    TRACE("(%p,%d,%p,%d,%p)\n",
289 290
          token,tokeninfoclass,tokeninfo,tokeninfolength,retlen);

291 292
    if (tokeninfoclass < MaxTokenInfoClass)
        len = info_len[tokeninfoclass];
293

294
    if (retlen) *retlen = len;
295 296

    if (tokeninfolength < len)
297
        return STATUS_BUFFER_TOO_SMALL;
298 299 300 301

    switch (tokeninfoclass)
    {
    case TokenUser:
302
        SERVER_START_REQ( get_token_sid )
303 304
        {
            TOKEN_USER * tuser = tokeninfo;
305
            PSID sid = tuser + 1;
306 307
            DWORD sid_len = tokeninfolength < sizeof(TOKEN_USER) ? 0 : tokeninfolength - sizeof(TOKEN_USER);

308
            req->handle = wine_server_obj_handle( token );
309
            req->which_sid = tokeninfoclass;
310 311
            wine_server_set_reply( req, sid, sid_len );
            status = wine_server_call( req );
312
            if (retlen) *retlen = reply->sid_len + sizeof(TOKEN_USER);
313 314 315 316 317
            if (status == STATUS_SUCCESS)
            {
                tuser->User.Sid = sid;
                tuser->User.Attributes = 0;
            }
318
        }
319
        SERVER_END_REQ;
320 321
        break;
    case TokenGroups:
322 323 324 325
    {
        char stack_buffer[256];
        unsigned int server_buf_len = sizeof(stack_buffer);
        void *buffer = stack_buffer;
326
        BOOLEAN need_more_memory;
327 328 329 330 331

        /* we cannot work out the size of the server buffer required for the
         * input size, since there are two factors affecting how much can be
         * stored in the buffer - number of groups and lengths of sids */
        do
332
        {
333 334
            need_more_memory = FALSE;

335 336 337
            SERVER_START_REQ( get_token_groups )
            {
                TOKEN_GROUPS *groups = tokeninfo;
338

339
                req->handle = wine_server_obj_handle( token );
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
                wine_server_set_reply( req, buffer, server_buf_len );
                status = wine_server_call( req );
                if (status == STATUS_BUFFER_TOO_SMALL)
                {
                    if (buffer == stack_buffer)
                        buffer = RtlAllocateHeap(GetProcessHeap(), 0, reply->user_len);
                    else
                        buffer = RtlReAllocateHeap(GetProcessHeap(), 0, buffer, reply->user_len);
                    if (!buffer) return STATUS_NO_MEMORY;

                    server_buf_len = reply->user_len;
                    need_more_memory = TRUE;
                }
                else if (status == STATUS_SUCCESS)
                {
                    struct token_groups *tg = buffer;
                    unsigned int *attr = (unsigned int *)(tg + 1);
                    ULONG i;
358
                    const int non_sid_portion = (sizeof(struct token_groups) + tg->count * sizeof(unsigned int));
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
                    SID *sids = (SID *)((char *)tokeninfo + FIELD_OFFSET( TOKEN_GROUPS, Groups[tg->count] ));
                    ULONG needed_bytes = FIELD_OFFSET( TOKEN_GROUPS, Groups[tg->count] ) +
                        reply->user_len - non_sid_portion;

                    if (retlen) *retlen = needed_bytes;

                    if (needed_bytes <= tokeninfolength)
                    {
                        groups->GroupCount = tg->count;
                        memcpy( sids, (char *)buffer + non_sid_portion,
                                reply->user_len - non_sid_portion );

                        for (i = 0; i < tg->count; i++)
                        {
                            groups->Groups[i].Attributes = attr[i];
                            groups->Groups[i].Sid = sids;
                            sids = (SID *)((char *)sids + RtlLengthSid(sids));
                        }
                    }
                    else status = STATUS_BUFFER_TOO_SMALL;
                }
                else if (retlen) *retlen = 0;
            }
            SERVER_END_REQ;
        } while (need_more_memory);
        if (buffer != stack_buffer) RtlFreeHeap(GetProcessHeap(), 0, buffer);
385
        break;
386
    }
387
    case TokenPrimaryGroup:
388
        SERVER_START_REQ( get_token_sid )
389 390
        {
            TOKEN_PRIMARY_GROUP *tgroup = tokeninfo;
391 392 393 394 395 396 397 398 399 400
            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;
401
        }
402
        SERVER_END_REQ;
403
        break;
404
    case TokenPrivileges:
405
        SERVER_START_REQ( get_token_privileges )
406 407
        {
            TOKEN_PRIVILEGES *tpriv = tokeninfo;
408
            req->handle = wine_server_obj_handle( token );
409
            if (tpriv && tokeninfolength > FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ))
410
                wine_server_set_reply( req, tpriv->Privileges, tokeninfolength - FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ) );
411
            status = wine_server_call( req );
412
            if (retlen) *retlen = FIELD_OFFSET( TOKEN_PRIVILEGES, Privileges ) + reply->len;
413
            if (tpriv) tpriv->PrivilegeCount = reply->len / sizeof(LUID_AND_ATTRIBUTES);
414
        }
415
        SERVER_END_REQ;
416
        break;
417
    case TokenOwner:
418
        SERVER_START_REQ( get_token_sid )
419
        {
420 421 422 423 424 425 426 427 428 429 430
            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;
431
        }
432
        SERVER_END_REQ;
433
        break;
434 435 436 437
    case TokenImpersonationLevel:
        SERVER_START_REQ( get_token_impersonation_level )
        {
            SECURITY_IMPERSONATION_LEVEL *impersonation_level = tokeninfo;
438
            req->handle = wine_server_obj_handle( token );
439 440 441 442 443 444
            status = wine_server_call( req );
            if (status == STATUS_SUCCESS)
                *impersonation_level = reply->impersonation_level;
        }
        SERVER_END_REQ;
        break;
445 446 447 448
    case TokenStatistics:
        SERVER_START_REQ( get_token_statistics )
        {
            TOKEN_STATISTICS *statistics = tokeninfo;
449
            req->handle = wine_server_obj_handle( token );
450 451 452 453 454 455 456
            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 */
457 458
                statistics->ExpirationTime.u.HighPart = 0x7fffffff;
                statistics->ExpirationTime.u.LowPart  = 0xffffffff;
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
                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;
478
            req->handle = wine_server_obj_handle( token );
479 480 481 482 483 484
            status = wine_server_call( req );
            if (status == STATUS_SUCCESS)
                *token_type = reply->primary ? TokenPrimary : TokenImpersonation;
        }
        SERVER_END_REQ;
        break;
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
    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;
510 511 512 513 514 515 516
    case TokenElevationType:
        {
            TOKEN_ELEVATION_TYPE *elevation_type = tokeninfo;
            FIXME("QueryInformationToken( ..., TokenElevationType, ...) semi-stub\n");
            *elevation_type = TokenElevationTypeFull;
        }
        break;
517 518 519 520 521 522 523
    case TokenElevation:
        {
            TOKEN_ELEVATION *elevation = tokeninfo;
            FIXME("QueryInformationToken( ..., TokenElevation, ...) semi-stub\n");
            elevation->TokenIsElevated = TRUE;
        }
        break;
524 525
    default:
        {
526
            ERR("Unhandled Token Information class %d!\n", tokeninfoclass);
527 528
            return STATUS_NOT_IMPLEMENTED;
        }
529
    }
530
    return status;
531 532
}

533 534 535 536 537 538 539 540 541 542
/******************************************************************************
*  NtSetInformationToken		[NTDLL.@]
*  ZwSetInformationToken		[NTDLL.@]
*/
NTSTATUS WINAPI NtSetInformationToken(
        HANDLE TokenHandle,
        TOKEN_INFORMATION_CLASS TokenInformationClass,
        PVOID TokenInformation,
        ULONG TokenInformationLength)
{
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
    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;
581 582
}

583 584 585 586 587 588 589 590 591 592 593 594
/******************************************************************************
*  NtAdjustGroupsToken		[NTDLL.@]
*  ZwAdjustGroupsToken		[NTDLL.@]
*/
NTSTATUS WINAPI NtAdjustGroupsToken(
        HANDLE TokenHandle,
        BOOLEAN ResetToDefault,
        PTOKEN_GROUPS NewState,
        ULONG BufferLength,
        PTOKEN_GROUPS PreviousState,
        PULONG ReturnLength)
{
595
    FIXME("%p %d %p %u %p %p\n", TokenHandle, ResetToDefault,
596 597 598 599
          NewState, BufferLength, PreviousState, ReturnLength);
    return STATUS_NOT_IMPLEMENTED;
}

600 601 602 603 604 605 606 607 608 609 610 611
/******************************************************************************
*  NtPrivilegeCheck		[NTDLL.@]
*  ZwPrivilegeCheck		[NTDLL.@]
*/
NTSTATUS WINAPI NtPrivilegeCheck(
    HANDLE ClientToken,
    PPRIVILEGE_SET RequiredPrivileges,
    PBOOLEAN Result)
{
    NTSTATUS status;
    SERVER_START_REQ( check_token_privileges )
    {
612
        req->handle = wine_server_obj_handle( ClientToken );
613
        req->all_required = ((RequiredPrivileges->Control & PRIVILEGE_SET_ALL_NECESSARY) ? TRUE : FALSE);
614
        wine_server_add_data( req, RequiredPrivileges->Privilege,
615
            RequiredPrivileges->PrivilegeCount * sizeof(RequiredPrivileges->Privilege[0]) );
616
        wine_server_set_reply( req, RequiredPrivileges->Privilege,
617 618 619 620 621 622 623 624 625 626 627
            RequiredPrivileges->PrivilegeCount * sizeof(RequiredPrivileges->Privilege[0]) );

        status = wine_server_call( req );

        if (status == STATUS_SUCCESS)
            *Result = (reply->has_privileges ? TRUE : FALSE);
    }
    SERVER_END_REQ;
    return status;
}

Juergen Schmied's avatar
Juergen Schmied committed
628 629
/*
 *	Section
630
 */
631

632
/******************************************************************************
633
 *  NtQuerySection	[NTDLL.@]
634
 */
Juergen Schmied's avatar
Juergen Schmied committed
635 636
NTSTATUS WINAPI NtQuerySection(
	IN HANDLE SectionHandle,
637
	IN SECTION_INFORMATION_CLASS SectionInformationClass,
Juergen Schmied's avatar
Juergen Schmied committed
638 639 640
	OUT PVOID SectionInformation,
	IN ULONG Length,
	OUT PULONG ResultLength)
641
{
642
	FIXME("(%p,%d,%p,0x%08x,%p) stub!\n",
Juergen Schmied's avatar
Juergen Schmied committed
643
	SectionHandle,SectionInformationClass,SectionInformation,Length,ResultLength);
644 645 646
	return 0;
}

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

/******************************************************************************
652
 *  NtCreatePort		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
653
 *  ZwCreatePort		[NTDLL.@]
654
 */
655
NTSTATUS WINAPI NtCreatePort(PHANDLE PortHandle,POBJECT_ATTRIBUTES ObjectAttributes,
656
                             ULONG MaxConnectInfoLength,ULONG MaxDataLength,PULONG reserved)
657
{
658
  FIXME("(%p,%p,%u,%u,%p),stub!\n",PortHandle,ObjectAttributes,
659
        MaxConnectInfoLength,MaxDataLength,reserved);
660
  return STATUS_NOT_IMPLEMENTED;
661 662 663
}

/******************************************************************************
664
 *  NtConnectPort		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
665
 *  ZwConnectPort		[NTDLL.@]
666
 */
667 668 669 670 671 672 673 674 675
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)
676
{
677 678 679 680 681 682
    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));
683
    return STATUS_NOT_IMPLEMENTED;
684 685
}

686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
/******************************************************************************
 *  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;
}

708
/******************************************************************************
709
 *  NtListenPort		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
710
 *  ZwListenPort		[NTDLL.@]
711
 */
712
NTSTATUS WINAPI NtListenPort(HANDLE PortHandle,PLPC_MESSAGE pLpcMessage)
Juergen Schmied's avatar
Juergen Schmied committed
713
{
714
  FIXME("(%p,%p),stub!\n",PortHandle,pLpcMessage);
715
  return STATUS_NOT_IMPLEMENTED;
716 717 718
}

/******************************************************************************
719
 *  NtAcceptConnectPort	[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
720
 *  ZwAcceptConnectPort	[NTDLL.@]
721
 */
722 723 724 725 726 727 728
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
729
{
730
  FIXME("(%p,%u,%p,%d,%p,%p),stub!\n",
731
        PortHandle,PortIdentifier,pLpcMessage,Accept,WriteSection,ReadSection);
732
  return STATUS_NOT_IMPLEMENTED;
733 734 735
}

/******************************************************************************
736
 *  NtCompleteConnectPort	[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
737
 *  ZwCompleteConnectPort	[NTDLL.@]
738
 */
739
NTSTATUS WINAPI NtCompleteConnectPort(HANDLE PortHandle)
Juergen Schmied's avatar
Juergen Schmied committed
740
{
741
  FIXME("(%p),stub!\n",PortHandle);
742
  return STATUS_NOT_IMPLEMENTED;
743 744 745
}

/******************************************************************************
746
 *  NtRegisterThreadTerminatePort	[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
747
 *  ZwRegisterThreadTerminatePort	[NTDLL.@]
748
 */
749
NTSTATUS WINAPI NtRegisterThreadTerminatePort(HANDLE PortHandle)
Juergen Schmied's avatar
Juergen Schmied committed
750
{
751
  FIXME("(%p),stub!\n",PortHandle);
752
  return STATUS_NOT_IMPLEMENTED;
753 754 755
}

/******************************************************************************
756
 *  NtRequestWaitReplyPort		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
757
 *  ZwRequestWaitReplyPort		[NTDLL.@]
758
 */
759 760 761 762
NTSTATUS WINAPI NtRequestWaitReplyPort(
        HANDLE PortHandle,
        PLPC_MESSAGE pLpcMessageIn,
        PLPC_MESSAGE pLpcMessageOut)
763
{
764 765 766 767
  FIXME("(%p,%p,%p),stub!\n",PortHandle,pLpcMessageIn,pLpcMessageOut);
  if(pLpcMessageIn)
  {
    TRACE("Message to send:\n");
768 769 770 771 772 773
    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);
774 775
    TRACE("\tMessageId           = %lu\n",pLpcMessageIn->MessageId);
    TRACE("\tSectionSize         = %lu\n",pLpcMessageIn->SectionSize);
776
    TRACE("\tData                = %s\n",
Mike McCormack's avatar
Mike McCormack committed
777
      debugstr_an((const char*)pLpcMessageIn->Data,pLpcMessageIn->DataSize));
778
  }
779
  return STATUS_NOT_IMPLEMENTED;
780 781 782
}

/******************************************************************************
783
 *  NtReplyWaitReceivePort	[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
784
 *  ZwReplyWaitReceivePort	[NTDLL.@]
785
 */
786 787 788 789 790
NTSTATUS WINAPI NtReplyWaitReceivePort(
        HANDLE PortHandle,
        PULONG PortIdentifier,
        PLPC_MESSAGE ReplyMessage,
        PLPC_MESSAGE Message)
Juergen Schmied's avatar
Juergen Schmied committed
791
{
792
  FIXME("(%p,%p,%p,%p),stub!\n",PortHandle,PortIdentifier,ReplyMessage,Message);
793
  return STATUS_NOT_IMPLEMENTED;
794 795
}

Juergen Schmied's avatar
Juergen Schmied committed
796 797
/*
 *	Misc
798
 */
Juergen Schmied's avatar
Juergen Schmied committed
799 800

 /******************************************************************************
801
 *  NtSetIntervalProfile	[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
802
 *  ZwSetIntervalProfile	[NTDLL.@]
Juergen Schmied's avatar
Juergen Schmied committed
803
 */
804 805 806 807
NTSTATUS WINAPI NtSetIntervalProfile(
        ULONG Interval,
        KPROFILE_SOURCE Source)
{
808
    FIXME("%u,%d\n", Interval, Source);
809
    return STATUS_SUCCESS;
810
}
Juergen Schmied's avatar
Juergen Schmied committed
811

812
static  SYSTEM_CPU_INFORMATION cached_sci;
813
static  ULONGLONG cpuHz = 1000000000; /* default to a 1GHz */
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879

#define AUTH	0x68747541	/* "Auth" */
#define ENTI	0x69746e65	/* "enti" */
#define CAMD	0x444d4163	/* "cAMD" */

/* 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));
#endif
}

/* From xf86info havecpuid.c 1.11 */
static inline int have_cpuid(void)
{
#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;
#else
        return 0;
#endif
}

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

    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 */
        switch ((regs2[0] >> 8) & 0xf)  /* cpu family */
        {
        case 3: info->Level = 3;        break;
        case 4: info->Level = 4;        break;
        case 5: info->Level = 5;        break;
        case 15: /* PPro/2/3/4 has same info as P1 */
        case 6: info->Level = 6;         break;
        default:
            FIXME("unknown cpu family %d, please report! (-> setting to 386)\n",
                  (regs2[0] >> 8)&0xf);
            info->Level = 3;
            break;
        }
880 881 882 883 884 885 886
        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;
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906

        if (regs[1] == AUTH && regs[3] == ENTI && regs[2] == CAMD)
        {
            do_cpuid(0x80000000, regs);  /* get vendor cpuid level */
            if (regs[0] >= 0x80000001)
            {
                do_cpuid(0x80000001, regs2);  /* get vendor features */
                user_shared_data->ProcessorFeatures[PF_3DNOW_INSTRUCTIONS_AVAILABLE] = (regs2[3] & (1 << 31 )) >> 31;
            }
        }
    }
}

/******************************************************************
 *		fill_cpu_info
 *
 * inits a couple of places with CPU related information:
 * - cached_sci & cpuHZ in this file
 * - Peb->NumberOfProcessors
 * - SharedUserData->ProcessFeatures[] array
907 908 909 910 911 912 913 914 915
 *
 * It creates a registry subhierarchy, looking like:
 * "\HARDWARE\DESCRIPTION\System\CentralProcessor\<processornumber>\Identifier (CPU x86)".
 * Note that there is a hierarchy for every processor installed, so this
 * supports multiprocessor systems. This is done like Win95 does it, I think.
 *
 * It creates some registry entries in the environment part:
 * "\HKLM\System\CurrentControlSet\Control\Session Manager\Environment". These are
 * always present. When deleted, Windows will add them again.
916 917 918 919 920 921 922
 */
void fill_cpu_info(void)
{
    memset(&cached_sci, 0, sizeof(cached_sci));
    /* choose sensible defaults ...
     * FIXME: perhaps overridable with precompiler flags?
     */
923
#ifdef __i386__
924 925
    cached_sci.Architecture     = PROCESSOR_ARCHITECTURE_INTEL;
    cached_sci.Level		= 5; /* 586 */
926 927 928 929
#elif defined(__x86_64__)
    cached_sci.Architecture     = PROCESSOR_ARCHITECTURE_AMD64;
#elif defined(__powerpc__)
    cached_sci.Architecture     = PROCESSOR_ARCHITECTURE_PPC;
930 931
#elif defined(__arm__)
    cached_sci.Architecture     = PROCESSOR_ARCHITECTURE_ARM;
932 933
#elif defined(__ALPHA__)
    cached_sci.Architecture     = PROCESSOR_ARCHITECTURE_ALPHA;
934 935
#elif defined(__sparc__)
    cached_sci.Architecture     = PROCESSOR_ARCHITECTURE_SPARC;
936 937 938
#else
#error Unknown CPU
#endif
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    cached_sci.Revision   	= 0;
    cached_sci.Reserved         = 0;
    cached_sci.FeatureSet       = 0x1fff; /* FIXME: set some sensible defaults out of ProcessFeatures[] */

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

    /* Hmm, reasonable processor feature defaults? */

#ifdef linux
    {
	char line[200];
	FILE *f = fopen ("/proc/cpuinfo", "r");

	if (!f)
		return;
	while (fgets(line,200,f) != NULL)
        {
            char	*s,*value;

            /* NOTE: the ':' is the only character we can rely on */
            if (!(value = strchr(line,':')))
                continue;

            /* terminate the valuename */
            s = value - 1;
            while ((s >= line) && ((*s == ' ') || (*s == '\t'))) s--;
            *(s + 1) = '\0';

            /* and strip leading spaces from value */
            value += 1;
            while (*value==' ') value++;
            if ((s = strchr(value,'\n')))
                *s='\0';

            if (!strcasecmp(line, "processor"))
            {
                /* processor number counts up... */
                unsigned int x;

                if (sscanf(value, "%d",&x))
                    if (x + 1 > NtCurrentTeb()->Peb->NumberOfProcessors)
                        NtCurrentTeb()->Peb->NumberOfProcessors = x + 1;

                continue;
            }
            if (!strcasecmp(line, "model"))
            {
                /* First part of Revision */
                int	x;

                if (sscanf(value, "%d",&x))
                    cached_sci.Revision = cached_sci.Revision | (x << 8);

                continue;
            }

            /* 2.1 method */
            if (!strcasecmp(line, "cpu family"))
            {
                if (isdigit(value[0]))
                {
                    cached_sci.Level = atoi(value);
                }
                continue;
            }
            /* old 2.0 method */
            if (!strcasecmp(line, "cpu"))
            {
                if (isdigit(value[0]) && value[1] == '8' && value[2] == '6' && value[3] == 0)
                {
                    switch (cached_sci.Level = value[0] - '0')
                    {
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                        break;
                    default:
                        FIXME("unknown Linux 2.0 cpu family '%s', please report ! (-> setting to 386)\n", value);
                        cached_sci.Level = 3;
                        break;
                    }
                }
                continue;
            }
            if (!strcasecmp(line, "stepping"))
            {
                /* Second part of Revision */
                int	x;

                if (sscanf(value, "%d",&x))
                    cached_sci.Revision = cached_sci.Revision | x;
                continue;
            }
            if (!strcasecmp(line, "cpu MHz"))
            {
                double cmz;
                if (sscanf( value, "%lf", &cmz ) == 1)
                {
                    /* SYSTEMINFO doesn't have a slot for cpu speed, so store in a global */
                    cpuHz = cmz * 1000 * 1000;
                }
                continue;
            }
            if (!strcasecmp(line, "fdiv_bug"))
            {
                if (!strncasecmp(value, "yes",3))
                    user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_PRECISION_ERRATA] = TRUE;
                continue;
            }
            if (!strcasecmp(line, "fpu"))
            {
                if (!strncasecmp(value, "no",2))
                    user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED] = TRUE;
                continue;
            }
            if (!strcasecmp(line, "flags") || !strcasecmp(line, "features"))
            {
                if (strstr(value, "cx8"))
                    user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE_DOUBLE] = TRUE;
1059 1060
                if (strstr(value, "cx16"))
                    user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE128] = TRUE;
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
                if (strstr(value, "mmx"))
                    user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE] = TRUE;
                if (strstr(value, "tsc"))
                    user_shared_data->ProcessorFeatures[PF_RDTSC_INSTRUCTION_AVAILABLE] = TRUE;
                if (strstr(value, "3dnow"))
                    user_shared_data->ProcessorFeatures[PF_3DNOW_INSTRUCTIONS_AVAILABLE] = TRUE;
                /* This will also catch sse2, but we have sse itself
                 * if we have sse2, so no problem */
                if (strstr(value, "sse"))
                    user_shared_data->ProcessorFeatures[PF_XMMI_INSTRUCTIONS_AVAILABLE] = TRUE;
                if (strstr(value, "sse2"))
                    user_shared_data->ProcessorFeatures[PF_XMMI64_INSTRUCTIONS_AVAILABLE] = TRUE;
1073 1074
                if (strstr(value, "pni"))
                    user_shared_data->ProcessorFeatures[PF_SSE3_INSTRUCTIONS_AVAILABLE] = TRUE;
1075 1076
                if (strstr(value, "pae"))
                    user_shared_data->ProcessorFeatures[PF_PAE_ENABLED] = TRUE;
1077 1078
                if (strstr(value, "ht"))
                    cached_sci.FeatureSet |= CPU_FEATURE_HTT;
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 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
                continue;
            }
	}
	fclose(f);
    }
#elif defined (__NetBSD__)
    {
        int mib[2];
        int value;
        size_t val_len;
        char model[256];
        char *cpuclass;
        FILE *f = fopen("/var/run/dmesg.boot", "r");

        /* first deduce as much as possible from the sysctls */
        mib[0] = CTL_MACHDEP;
#ifdef CPU_FPU_PRESENT
        mib[1] = CPU_FPU_PRESENT;
        val_len = sizeof(value);
        if (sysctl(mib, 2, &value, &val_len, NULL, 0) >= 0)
            user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED] = !value;
#endif
#ifdef CPU_SSE
        mib[1] = CPU_SSE;   /* this should imply MMX */
        val_len = sizeof(value);
        if (sysctl(mib, 2, &value, &val_len, NULL, 0) >= 0)
            if (value) user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE] = TRUE;
#endif
#ifdef CPU_SSE2
        mib[1] = CPU_SSE2;  /* this should imply MMX */
        val_len = sizeof(value);
        if (sysctl(mib, 2, &value, &val_len, NULL, 0) >= 0)
            if (value) user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE] = TRUE;
#endif
        mib[0] = CTL_HW;
        mib[1] = HW_NCPU;
        val_len = sizeof(value);
        if (sysctl(mib, 2, &value, &val_len, NULL, 0) >= 0)
            if (value > NtCurrentTeb()->Peb->NumberOfProcessors)
                NtCurrentTeb()->Peb->NumberOfProcessors = value;
        mib[1] = HW_MODEL;
        val_len = sizeof(model)-1;
        if (sysctl(mib, 2, model, &val_len, NULL, 0) >= 0)
        {
            model[val_len] = '\0'; /* just in case */
            cpuclass = strstr(model, "-class");
            if (cpuclass != NULL) {
                while(cpuclass > model && cpuclass[0] != '(') cpuclass--;
                if (!strncmp(cpuclass+1, "386", 3))
                {
                    cached_sci.Level= 3;
                }
                if (!strncmp(cpuclass+1, "486", 3))
                {
                    cached_sci.Level= 4;
                }
                if (!strncmp(cpuclass+1, "586", 3))
                {
                    cached_sci.Level= 5;
                }
                if (!strncmp(cpuclass+1, "686", 3))
                {
                    cached_sci.Level= 6;
                    /* this should imply MMX */
                    user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE] = TRUE;
                }
            }
        }

        /* it may be worth reading from /var/run/dmesg.boot for
           additional information such as CX8, MMX and TSC
           (however this information should be considered less
           reliable than that from the sysctl calls) */
        if (f != NULL)
        {
            while (fgets(model, 255, f) != NULL)
            {
                int cpu, features;
                if (sscanf(model, "cpu%d: features %x<", &cpu, &features) == 2)
                {
                    /* we could scan the string but it is easier
                       to test the bits directly */
                    if (features & 0x1)
                        user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED] = TRUE;
                    if (features & 0x10)
                        user_shared_data->ProcessorFeatures[PF_RDTSC_INSTRUCTION_AVAILABLE] = TRUE;
                    if (features & 0x100)
                        user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE_DOUBLE] = TRUE;
                    if (features & 0x800000)
                        user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE] = TRUE;

                    break;
                }
            }
            fclose(f);
        }
    }
1176
#elif defined(__FreeBSD__) || defined (__FreeBSD_kernel__)
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
    {
        int ret, num;
        size_t len;

        get_cpuinfo( &cached_sci );

        /* Check for OS support of SSE -- Is this used, and should it be sse1 or sse2? */
        /*len = sizeof(num);
          ret = sysctlbyname("hw.instruction_sse", &num, &len, NULL, 0);
          if (!ret)
          user_shared_data->ProcessorFeatures[PF_XMMI_INSTRUCTIONS_AVAILABLE] = num;*/

        len = sizeof(num);
        ret = sysctlbyname("hw.ncpu", &num, &len, NULL, 0);
        if (!ret)
            NtCurrentTeb()->Peb->NumberOfProcessors = num;
1193 1194 1195 1196

        len = sizeof(num);
        if (!sysctlbyname("dev.cpu.0.freq", &num, &len, NULL, 0))
            cpuHz = num * 1000 * 1000;
1197 1198 1199 1200 1201 1202 1203 1204 1205
    }
#elif defined(__sun)
    {
        int num = sysconf( _SC_NPROCESSORS_ONLN );

        if (num == -1) num = 1;
        get_cpuinfo( &cached_sci );
        NtCurrentTeb()->Peb->NumberOfProcessors = num;
    }
1206 1207
#elif defined (__OpenBSD__)
    {
1208
        int mib[2], num, ret;
1209 1210 1211 1212 1213 1214
        size_t len;

        mib[0] = CTL_HW;
        mib[1] = HW_NCPU;
        len = sizeof(num);

1215 1216 1217
        ret = sysctl(mib, 2, &num, &len, NULL, 0);
        if (!ret)
            NtCurrentTeb()->Peb->NumberOfProcessors = num;
1218
    }
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
#elif defined (__APPLE__)
    {
        size_t valSize;
        unsigned long long longVal;
        int value;
        int cputype;
        char buffer[256];

        valSize = sizeof(int);
        if (sysctlbyname ("hw.optional.floatingpoint", &value, &valSize, NULL, 0) == 0)
        {
            if (value)
                user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED] = FALSE;
            else
                user_shared_data->ProcessorFeatures[PF_FLOATING_POINT_EMULATED] = TRUE;
        }
        valSize = sizeof(int);
        if (sysctlbyname ("hw.ncpu", &value, &valSize, NULL, 0) == 0)
            NtCurrentTeb()->Peb->NumberOfProcessors = value;

        /* FIXME: we don't use the "hw.activecpu" value... but the cached one */

        valSize = sizeof(int);
        if (sysctlbyname ("hw.cputype", &cputype, &valSize, NULL, 0) == 0)
        {
            switch (cputype)
            {
            case CPU_TYPE_POWERPC:
Huw Davies's avatar
Huw Davies committed
1247
                cached_sci.Architecture = PROCESSOR_ARCHITECTURE_PPC;
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
                valSize = sizeof(int);
                if (sysctlbyname ("hw.cpusubtype", &value, &valSize, NULL, 0) == 0)
                {
                    switch (value)
                    {
                    case CPU_SUBTYPE_POWERPC_601:
                    case CPU_SUBTYPE_POWERPC_602:       cached_sci.Level = 1;   break;
                    case CPU_SUBTYPE_POWERPC_603:       cached_sci.Level = 3;   break;
                    case CPU_SUBTYPE_POWERPC_603e:
                    case CPU_SUBTYPE_POWERPC_603ev:     cached_sci.Level = 6;   break;
                    case CPU_SUBTYPE_POWERPC_604:       cached_sci.Level = 4;   break;
                    case CPU_SUBTYPE_POWERPC_604e:      cached_sci.Level = 9;   break;
                    case CPU_SUBTYPE_POWERPC_620:       cached_sci.Level = 20;  break;
                    case CPU_SUBTYPE_POWERPC_750:       /* G3/G4 derive from 603 so ... */
                    case CPU_SUBTYPE_POWERPC_7400:
                    case CPU_SUBTYPE_POWERPC_7450:      cached_sci.Level = 6;   break;
                    case CPU_SUBTYPE_POWERPC_970:       cached_sci.Level = 9;
                        /* :o) user_shared_data->ProcessorFeatures[PF_ALTIVEC_INSTRUCTIONS_AVAILABLE] ;-) */
                        break;
                    default: break;
                    }
                }
                break; /* CPU_TYPE_POWERPC */
            case CPU_TYPE_I386:
                cached_sci.Architecture = PROCESSOR_ARCHITECTURE_INTEL;
                valSize = sizeof(int);
                if (sysctlbyname ("machdep.cpu.family", &value, &valSize, NULL, 0) == 0)
                {
                    cached_sci.Level = value;
                }
                valSize = sizeof(int);
                if (sysctlbyname ("machdep.cpu.model", &value, &valSize, NULL, 0) == 0)
                    cached_sci.Revision = (value << 8);
                valSize = sizeof(int);
                if (sysctlbyname ("machdep.cpu.stepping", &value, &valSize, NULL, 0) == 0)
                    cached_sci.Revision |= value;
                valSize = sizeof(buffer);
                if (sysctlbyname ("machdep.cpu.features", buffer, &valSize, NULL, 0) == 0)
                {
                    cached_sci.Revision |= value;
                    if (strstr(buffer, "CX8"))   user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE_DOUBLE] = TRUE;
1289
                    if (strstr(buffer, "CX16"))  user_shared_data->ProcessorFeatures[PF_COMPARE_EXCHANGE128] = TRUE;
1290 1291 1292 1293 1294
                    if (strstr(buffer, "MMX"))   user_shared_data->ProcessorFeatures[PF_MMX_INSTRUCTIONS_AVAILABLE] = TRUE;
                    if (strstr(buffer, "TSC"))   user_shared_data->ProcessorFeatures[PF_RDTSC_INSTRUCTION_AVAILABLE] = TRUE;
                    if (strstr(buffer, "3DNOW")) user_shared_data->ProcessorFeatures[PF_3DNOW_INSTRUCTIONS_AVAILABLE] = TRUE;
                    if (strstr(buffer, "SSE"))   user_shared_data->ProcessorFeatures[PF_XMMI_INSTRUCTIONS_AVAILABLE] = TRUE;
                    if (strstr(buffer, "SSE2"))  user_shared_data->ProcessorFeatures[PF_XMMI64_INSTRUCTIONS_AVAILABLE] = TRUE;
1295
                    if (strstr(buffer, "SSE3"))  user_shared_data->ProcessorFeatures[PF_SSE3_INSTRUCTIONS_AVAILABLE] = TRUE;
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
                    if (strstr(buffer, "PAE"))   user_shared_data->ProcessorFeatures[PF_PAE_ENABLED] = TRUE;
                }
                break; /* CPU_TYPE_I386 */
            default: break;
            } /* switch (cputype) */
        }
        valSize = sizeof(longVal);
        if (!sysctlbyname("hw.cpufrequency", &longVal, &valSize, NULL, 0))
            cpuHz = longVal;
    }
#else
    FIXME("not yet supported on this system\n");
#endif
    TRACE("<- CPU arch %d, level %d, rev %d, features 0x%x\n",
          cached_sci.Architecture, cached_sci.Level, cached_sci.Revision, cached_sci.FeatureSet);
}

Juergen Schmied's avatar
Juergen Schmied committed
1313
/******************************************************************************
1314
 * NtQuerySystemInformation [NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1315
 * ZwQuerySystemInformation [NTDLL.@]
Juergen Schmied's avatar
Juergen Schmied committed
1316 1317 1318 1319 1320 1321
 *
 * ARGUMENTS:
 *  SystemInformationClass	Index to a certain information structure
 *	SystemTimeAdjustmentInformation	SYSTEM_TIME_ADJUSTMENT
 *	SystemCacheInformation		SYSTEM_CACHE_INFORMATION
 *	SystemConfigurationInformation	CONFIGURATION_INFORMATION
1322
 *	observed (class/len):
Juergen Schmied's avatar
Juergen Schmied committed
1323 1324 1325 1326
 *		0x0/0x2c
 *		0x12/0x18
 *		0x2/0x138
 *		0x8/0x600
1327
 *              0x25/0xc
Juergen Schmied's avatar
Juergen Schmied committed
1328 1329 1330
 *  SystemInformation	caller supplies storage for the information structure
 *  Length		size of the structure
 *  ResultLength	Data written
1331
 */
Juergen Schmied's avatar
Juergen Schmied committed
1332 1333 1334 1335 1336
NTSTATUS WINAPI NtQuerySystemInformation(
	IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
	OUT PVOID SystemInformation,
	IN ULONG Length,
	OUT PULONG ResultLength)
1337
{
1338 1339 1340
    NTSTATUS    ret = STATUS_SUCCESS;
    ULONG       len = 0;

1341
    TRACE("(0x%08x,%p,0x%08x,%p)\n",
1342 1343 1344
          SystemInformationClass,SystemInformation,Length,ResultLength);

    switch (SystemInformationClass)
1345
    {
1346 1347
    case SystemBasicInformation:
        {
1348 1349
            SYSTEM_BASIC_INFORMATION sbi;

1350
            virtual_get_system_info( &sbi );
1351 1352
            len = sizeof(sbi);

1353
            if ( Length == len)
1354
            {
1355 1356
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else memcpy( SystemInformation, &sbi, len);
1357 1358 1359 1360
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
        }
        break;
1361
    case SystemCpuInformation:
1362
        if (Length >= (len = sizeof(cached_sci)))
1363
        {
1364 1365
            if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
            else memcpy(SystemInformation, &cached_sci, len);
1366
        }
1367
        else ret = STATUS_INFO_LENGTH_MISMATCH;
1368
        break;
1369 1370
    case SystemPerformanceInformation:
        {
1371
            SYSTEM_PERFORMANCE_INFORMATION spi;
1372
            static BOOL fixme_written = FALSE;
1373
            FILE *fp;
1374 1375 1376 1377

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

1378 1379
            spi.Reserved3 = 0x7fffffff; /* Available paged pool memory? */

1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
            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;
            }

1395
            if (Length >= len)
1396
            {
1397 1398
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else memcpy( SystemInformation, &spi, len);
1399 1400
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
1401 1402 1403 1404
            if(!fixme_written) {
                FIXME("info_class SYSTEM_PERFORMANCE_INFORMATION\n");
                fixme_written = TRUE;
            }
1405 1406 1407 1408
        }
        break;
    case SystemTimeOfDayInformation:
        {
1409 1410 1411 1412 1413
            SYSTEM_TIMEOFDAY_INFORMATION sti;

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

            /* liKeSystemTime, liExpTimeZoneBias, uCurrentTimeZoneId */
1414
            sti.liKeBootTime.QuadPart = server_start_time;
1415 1416

            if (Length <= sizeof(sti))
1417
            {
1418 1419 1420
                len = Length;
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else memcpy( SystemInformation, &sti, Length);
1421 1422 1423 1424 1425 1426
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
        }
        break;
    case SystemProcessInformation:
        {
1427
            SYSTEM_PROCESS_INFORMATION* spi = SystemInformation;
1428 1429
            SYSTEM_PROCESS_INFORMATION* last = NULL;
            HANDLE hSnap = 0;
1430
            WCHAR procname[1024];
1431
            WCHAR* exename;
1432
            DWORD wlen = 0;
1433
            DWORD procstructlen = 0;
1434 1435 1436

            SERVER_START_REQ( create_snapshot )
            {
1437 1438
                req->flags      = SNAP_PROCESS | SNAP_THREAD;
                req->attributes = 0;
1439 1440
                if (!(ret = wine_server_call( req )))
                    hSnap = wine_server_ptr_handle( reply->handle );
1441 1442 1443 1444 1445 1446 1447
            }
            SERVER_END_REQ;
            len = 0;
            while (ret == STATUS_SUCCESS)
            {
                SERVER_START_REQ( next_process )
                {
1448
                    req->handle = wine_server_obj_handle( hSnap );
1449
                    req->reset = (len == 0);
1450
                    wine_server_set_reply( req, procname, sizeof(procname)-sizeof(WCHAR) );
1451 1452
                    if (!(ret = wine_server_call( req )))
                    {
1453 1454 1455 1456 1457 1458 1459 1460 1461
                        /* 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);

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

1464
                        if (Length >= len + procstructlen)
1465
                        {
Paul Vriens's avatar
Paul Vriens committed
1466
                            /* ftCreationTime, ftUserTime, ftKernelTime;
1467 1468 1469
                             * vmCounters, ioCounters
                             */
 
1470
                            memset(spi, 0, sizeof(*spi));
1471

1472
                            spi->NextEntryOffset = procstructlen - wlen;
1473
                            spi->dwThreadCount = reply->threads;
1474

1475
                            /* spi->pszProcessName will be set later on */
1476

1477
                            spi->dwBasePriority = reply->priority;
1478 1479 1480
                            spi->UniqueProcessId = UlongToHandle(reply->pid);
                            spi->ParentProcessId = UlongToHandle(reply->ppid);
                            spi->HandleCount = reply->handles;
1481

1482
                            /* spi->ti will be set later on */
1483

1484
                            len += procstructlen;
1485 1486 1487 1488 1489
                        }
                        else ret = STATUS_INFO_LENGTH_MISMATCH;
                    }
                }
                SERVER_END_REQ;
1490
 
1491 1492 1493 1494 1495
                if (ret != STATUS_SUCCESS)
                {
                    if (ret == STATUS_NO_MORE_FILES) ret = STATUS_SUCCESS;
                    break;
                }
1496
                else /* Length is already checked for */
1497 1498 1499 1500 1501 1502 1503 1504 1505
                {
                    int     i, j;

                    /* set thread info */
                    i = j = 0;
                    while (ret == STATUS_SUCCESS)
                    {
                        SERVER_START_REQ( next_thread )
                        {
1506
                            req->handle = wine_server_obj_handle( hSnap );
1507 1508 1509 1510
                            req->reset = (j == 0);
                            if (!(ret = wine_server_call( req )))
                            {
                                j++;
1511
                                if (UlongToHandle(reply->pid) == spi->UniqueProcessId)
1512 1513 1514 1515
                                {
                                    /* ftKernelTime, ftUserTime, ftCreateTime;
                                     * dwTickCount, dwStartAddress
                                     */
Paul Vriens's avatar
Paul Vriens committed
1516 1517 1518

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

1519 1520 1521
                                    spi->ti[i].CreateTime.QuadPart = 0xdeadbeef;
                                    spi->ti[i].ClientId.UniqueProcess = UlongToHandle(reply->pid);
                                    spi->ti[i].ClientId.UniqueThread  = UlongToHandle(reply->tid);
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
                                    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 */
1533
                    spi->ProcessName.Buffer = (WCHAR*)((char*)spi + spi->NextEntryOffset);
1534 1535
                    spi->ProcessName.Length = wlen - sizeof(WCHAR);
                    spi->ProcessName.MaximumLength = wlen;
1536
                    memcpy( spi->ProcessName.Buffer, exename, wlen );
1537
                    spi->NextEntryOffset += wlen;
1538 1539

                    last = spi;
1540
                    spi = (SYSTEM_PROCESS_INFORMATION*)((char*)spi + spi->NextEntryOffset);
1541 1542
                }
            }
1543
            if (ret == STATUS_SUCCESS && last) last->NextEntryOffset = 0;
1544 1545 1546 1547 1548
            if (hSnap) NtClose(hSnap);
        }
        break;
    case SystemProcessorPerformanceInformation:
        {
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 1576
            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++)
                    {
1577 1578 1579
                        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];
1580
                    }
1581
                    vm_deallocate (mach_task_self (), (vm_address_t) pinfo, info_count * sizeof(natural_t));
1582 1583 1584 1585
                }
            }
#else
            {
1586
                FILE *cpuinfo = fopen("/proc/stat", "r");
1587 1588
                if (cpuinfo)
                {
1589
                    unsigned long usr,nice,sys,idle,remainder[8];
1590 1591
                    int count;
                    char name[10];
1592
                    char line[255];
1593 1594

                    /* first line is combined usage */
1595
                    if (fgets(line,255,cpuinfo))
1596 1597 1598 1599 1600 1601
                        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]);
1602 1603
                    else
                        count = 0;
1604
                    /* we set this up in the for older non-smp enabled kernels */
1605
                    if (count >= 5 && strcmp(name, "cpu") == 0)
1606
                    {
1607 1608 1609 1610
                        int i;
                        for (i = 0; i + 5 < count; ++i)
                            sys += remainder[i];
                        usr += nice;
1611 1612
                        sppi = RtlAllocateHeap(GetProcessHeap(), 0,
                                               sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION));
1613 1614
                        sppi->IdleTime.QuadPart = idle;
                        sppi->KernelTime.QuadPart = sys;
1615 1616 1617
                        sppi->UserTime.QuadPart = usr+nice;
                        sppi->Reserved1[0].QuadPart = 0;
                        sppi->Reserved1[1].QuadPart = 0;
1618 1619 1620 1621 1622 1623
                        cpus = 1;
                        len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION);
                    }

                    do
                    {
1624
                        if (fgets(line, 255, cpuinfo))
1625 1626 1627 1628 1629 1630
                            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]);
1631 1632
                        else
                            count = 0;
1633
                        if (count >= 5 && strncmp(name, "cpu", 3)==0)
1634
                        {
1635 1636 1637 1638
                            int i;
                            for (i = 0; i + 5 < count; ++i)
                                sys += remainder[i];
                            usr += nice;
1639 1640 1641
                            out_cpus --;
                            if (name[3]=='0') /* first cpu */
                            {
1642 1643 1644
                                sppi->IdleTime.QuadPart = idle;
                                sppi->KernelTime.QuadPart = sys;
                                sppi->UserTime.QuadPart = usr;
1645 1646 1647 1648 1649
                            }
                            else /* new cpu */
                            {
                                len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * (cpus+1);
                                sppi = RtlReAllocateHeap(GetProcessHeap(), 0, sppi, len);
1650 1651 1652
                                sppi[cpus].IdleTime.QuadPart = idle;
                                sppi[cpus].KernelTime.QuadPart = sys;
                                sppi[cpus].UserTime.QuadPart = usr;
1653 1654
                                sppi[cpus].Reserved1[0].QuadPart = 0;
                                sppi[cpus].Reserved1[1].QuadPart = 0;
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
                                cpus++;
                            }
                        }
                        else
                            break;
                    } while (out_cpus > 0);
                    fclose(cpuinfo);
                }
            }
#endif

            if (cpus == 0)
            {
                static int i = 1;
1669 1670 1671 1672
                int n;
                cpus = min(NtCurrentTeb()->Peb->NumberOfProcessors, out_cpus);
                len = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * cpus;
                sppi = RtlAllocateHeap(GetProcessHeap(), 0, len);
1673 1674
                FIXME("stub info_class SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION\n");
                /* many programs expect these values to change so fake change */
1675 1676 1677 1678 1679 1680
                for (n = 0; n < cpus; n++)
                {
                    sppi[n].KernelTime.QuadPart = 1 * i;
                    sppi[n].UserTime.QuadPart   = 2 * i;
                    sppi[n].IdleTime.QuadPart   = 3 * i;
                }
1681 1682
                i++;
            }
1683 1684

            if (Length >= len)
1685
            {
1686
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
1687
                else memcpy( SystemInformation, sppi, len);
1688 1689
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
1690 1691

            RtlFreeHeap(GetProcessHeap(),0,sppi);
1692 1693
        }
        break;
1694
    case SystemModuleInformation:
1695
        /* FIXME: should be system-wide */
1696 1697
        if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
        else ret = LdrQueryProcessModuleInformation( SystemInformation, Length, &len );
1698
        break;
1699 1700 1701 1702 1703 1704
    case SystemHandleInformation:
        {
            SYSTEM_HANDLE_INFORMATION shi;

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

1706 1707 1708 1709 1710 1711
            if ( Length >= len)
            {
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else memcpy( SystemInformation, &shi, len);
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
1712
            FIXME("info_class SYSTEM_HANDLE_INFORMATION\n");
1713 1714
        }
        break;
1715 1716
    case SystemCacheInformation:
        {
1717 1718 1719 1720 1721 1722
            SYSTEM_CACHE_INFORMATION sci;

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

            if ( Length >= len)
1723
            {
1724 1725
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else memcpy( SystemInformation, &sci, len);
1726 1727
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
1728
            FIXME("info_class SYSTEM_CACHE_INFORMATION\n");
1729 1730
        }
        break;
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
    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;
1744
            FIXME("info_class SYSTEM_INTERRUPT_INFORMATION\n");
1745 1746
        }
        break;
1747 1748
    case SystemKernelDebuggerInformation:
        {
1749 1750 1751 1752 1753 1754 1755
            SYSTEM_KERNEL_DEBUGGER_INFORMATION skdi;

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

            if ( Length >= len)
1756
            {
1757 1758
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else memcpy( SystemInformation, &skdi, len);
1759 1760 1761 1762
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
        }
        break;
1763 1764
    case SystemRegistryQuotaInformation:
        {
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
	    /* 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)
1778
            {
1779 1780 1781 1782 1783 1784
                if (!SystemInformation) ret = STATUS_ACCESS_VIOLATION;
                else
                {
                    FIXME("SystemRegistryQuotaInformation: faking max registry size of 32 MB\n");
                    memcpy( SystemInformation, &srqi, len);
                }
1785 1786 1787
            }
            else ret = STATUS_INFO_LENGTH_MISMATCH;
        }
1788 1789
	break;
    default:
1790
	FIXME("(0x%08x,%p,0x%08x,%p) stub\n",
1791
	      SystemInformationClass,SystemInformation,Length,ResultLength);
1792 1793 1794 1795 1796 1797

        /* 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;
1798
    }
1799

1800
    if (ResultLength) *ResultLength = len;
1801

1802
    return ret;
Juergen Schmied's avatar
Juergen Schmied committed
1803 1804
}

1805 1806 1807 1808 1809 1810
/******************************************************************************
 * NtSetSystemInformation [NTDLL.@]
 * ZwSetSystemInformation [NTDLL.@]
 */
NTSTATUS WINAPI NtSetSystemInformation(SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG Length)
{
1811
    FIXME("(0x%08x,%p,0x%08x) stub\n",SystemInformationClass,SystemInformation,Length);
1812 1813
    return STATUS_SUCCESS;
}
1814

1815
/******************************************************************************
1816
 *  NtCreatePagingFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1817
 *  ZwCreatePagingFile		[NTDLL.@]
1818
 */
Juergen Schmied's avatar
Juergen Schmied committed
1819
NTSTATUS WINAPI NtCreatePagingFile(
1820
	PUNICODE_STRING PageFileName,
1821 1822
	PLARGE_INTEGER MinimumSize,
	PLARGE_INTEGER MaximumSize,
1823
	PLARGE_INTEGER ActualSize)
1824
{
1825
    FIXME("(%p %p %p %p) stub\n", PageFileName, MinimumSize, MaximumSize, ActualSize);
1826
    return STATUS_SUCCESS;
1827 1828
}

1829
/******************************************************************************
1830
 *  NtDisplayString				[NTDLL.@]
1831
 *
1832 1833
 * writes a string to the nt-textmode screen eg. during startup
 */
1834
NTSTATUS WINAPI NtDisplayString ( PUNICODE_STRING string )
1835
{
1836 1837 1838 1839 1840 1841 1842 1843 1844
    STRING stringA;
    NTSTATUS ret;

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

1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
/******************************************************************************
 *  NtInitiatePowerAction                       [NTDLL.@]
 *
 */
NTSTATUS WINAPI NtInitiatePowerAction(
	IN POWER_ACTION SystemAction,
	IN SYSTEM_POWER_STATE MinSystemState,
	IN ULONG Flags,
	IN BOOLEAN Asynchronous)
{
1857
        FIXME("(%d,%d,0x%08x,%d),stub\n",
1858 1859 1860 1861 1862
		SystemAction,MinSystemState,Flags,Asynchronous);
        return STATUS_NOT_IMPLEMENTED;
}
	

1863
/******************************************************************************
1864
 *  NtPowerInformation				[NTDLL.@]
1865
 *
1866
 */
1867 1868 1869 1870 1871 1872
NTSTATUS WINAPI NtPowerInformation(
	IN POWER_INFORMATION_LEVEL InformationLevel,
	IN PVOID lpInputBuffer,
	IN ULONG nInputBufferSize,
	IN PVOID lpOutputBuffer,
	IN ULONG nOutputBufferSize)
1873
{
1874
	TRACE("(%d,%p,%d,%p,%d)\n",
1875
		InformationLevel,lpInputBuffer,nInputBufferSize,lpOutputBuffer,nOutputBufferSize);
1876 1877
	switch(InformationLevel) {
		case SystemPowerCapabilities: {
1878
			PSYSTEM_POWER_CAPABILITIES PowerCaps = lpOutputBuffer;
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
			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;
		}
1916 1917
		case SystemExecutionState: {
			PULONG ExecutionState = lpOutputBuffer;
1918
			WARN("semi-stub: SystemExecutionState\n"); /* Needed for .NET Framework, but using a FIXME is really noisy. */
1919 1920 1921 1922 1923 1924
			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;
		}
1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
                case ProcessorInformation: {
			PPROCESSOR_POWER_INFORMATION cpu_power = lpOutputBuffer;

			WARN("semi-stub: ProcessorInformation\n");
			if (nOutputBufferSize < sizeof(PROCESSOR_POWER_INFORMATION))
				return STATUS_BUFFER_TOO_SMALL;
                        cpu_power->Number = NtCurrentTeb()->Peb->NumberOfProcessors;
                        cpu_power->MaxMhz = cpuHz / 1000000;
                        cpu_power->CurrentMhz = cpuHz / 1000000;
                        cpu_power->MhzLimit = cpuHz / 1000000;
                        cpu_power->MaxIdleState = 0; /* FIXME */
                        cpu_power->CurrentIdleState = 0; /* FIXME */
                        return STATUS_SUCCESS;
                }
1939
		default:
1940 1941
			/* FIXME: Needed by .NET Framework */
			WARN("Unimplemented NtPowerInformation action: %d\n", InformationLevel);
1942 1943
			return STATUS_NOT_IMPLEMENTED;
	}
1944
}
1945

1946 1947 1948 1949
/******************************************************************************
 *  NtShutdownSystem				[NTDLL.@]
 *
 */
1950
NTSTATUS WINAPI NtShutdownSystem(SHUTDOWN_ACTION Action)
1951
{
1952 1953
    FIXME("%d\n",Action);
    return STATUS_SUCCESS;
1954 1955
}

1956
/******************************************************************************
1957
 *  NtAllocateLocallyUniqueId (NTDLL.@)
1958 1959 1960
 */
NTSTATUS WINAPI NtAllocateLocallyUniqueId(PLUID Luid)
{
1961
    NTSTATUS status;
1962

1963
    TRACE("%p\n", Luid);
1964 1965 1966

    if (!Luid)
        return STATUS_ACCESS_VIOLATION;
1967

1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
    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
1978

1979
    return status;
1980
}
1981 1982 1983 1984 1985 1986 1987

/******************************************************************************
 *        VerSetConditionMask   (NTDLL.@)
 */
ULONGLONG WINAPI VerSetConditionMask( ULONGLONG dwlConditionMask, DWORD dwTypeBitMask,
                                      BYTE dwConditionMask)
{
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
    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;
2010 2011
    return dwlConditionMask;
}
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021

/******************************************************************************
 *  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)
{
2022
    FIXME("(%s, %p, %s, %p, 0x%08x, %p, %d, %p, %p, %p), stub\n", debugstr_us(SubsystemName), HandleId,
2023 2024 2025 2026 2027
          debugstr_us(ObjectTypeName), SecurityDescriptor, DesiredAccess, GenericMapping, ObjectCreation,
          GrantedAccess, AccessStatus, GenerateOnClose);

    return STATUS_NOT_IMPLEMENTED;
}
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039

/******************************************************************************
 *  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;
}