w32.c 199 KB
Newer Older
1
/* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
2
   Copyright (C) 1994-1995, 2000-2013 Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
3

4 5
This file is part of GNU Emacs.

6
GNU Emacs is free software: you can redistribute it and/or modify
7
it under the terms of the GNU General Public License as published by
8 9
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
10 11 12 13 14 15 16

GNU Emacs 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 General Public License for more details.

You should have received a copy of the GNU General Public License
17
along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
18

19
/*
Richard M. Stallman's avatar
Richard M. Stallman committed
20 21
   Geoff Voelker (voelker@cs.washington.edu)                         7-29-94
*/
Geoff Voelker's avatar
Geoff Voelker committed
22
#include <stddef.h> /* for offsetof */
Richard M. Stallman's avatar
Richard M. Stallman committed
23 24
#include <stdlib.h>
#include <stdio.h>
25
#include <float.h>	/* for DBL_EPSILON */
Richard M. Stallman's avatar
Richard M. Stallman committed
26
#include <io.h>
27
#include <errno.h>
Richard M. Stallman's avatar
Richard M. Stallman committed
28 29
#include <fcntl.h>
#include <ctype.h>
30
#include <signal.h>
Karl Heuer's avatar
Karl Heuer committed
31
#include <sys/file.h>
32
#include <sys/time.h>
33
#include <sys/utime.h>
34
#include <math.h>
35
#include <time.h>
36 37

/* must include CRT headers *before* config.h */
Pavel Janík's avatar
Pavel Janík committed
38 39

#include <config.h>
Daniel Colascione's avatar
Daniel Colascione committed
40
#include <mbstring.h>	/* for _mbspbrk */
Pavel Janík's avatar
Pavel Janík committed
41

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#undef access
#undef chdir
#undef chmod
#undef creat
#undef ctime
#undef fopen
#undef link
#undef mkdir
#undef mktemp
#undef open
#undef rename
#undef rmdir
#undef unlink

#undef close
#undef dup
#undef dup2
#undef pipe
#undef read
#undef write
Richard M. Stallman's avatar
Richard M. Stallman committed
62

Andrew Innes's avatar
Andrew Innes committed
63 64
#undef strerror

65 66
#undef localtime

Richard M. Stallman's avatar
Richard M. Stallman committed
67 68 69
#include "lisp.h"

#include <pwd.h>
Lars Hansen's avatar
Lars Hansen committed
70
#include <grp.h>
Richard M. Stallman's avatar
Richard M. Stallman committed
71

72 73 74 75
#ifdef __GNUC__
#define _ANONYMOUS_UNION
#define _ANONYMOUS_STRUCT
#endif
76
#include <windows.h>
77 78 79
/* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
   use a different name to avoid compilation problems.  */
typedef struct _MEMORY_STATUS_EX {
80 81 82 83 84 85 86 87 88
  DWORD dwLength;
  DWORD dwMemoryLoad;
  DWORDLONG ullTotalPhys;
  DWORDLONG ullAvailPhys;
  DWORDLONG ullTotalPageFile;
  DWORDLONG ullAvailPageFile;
  DWORDLONG ullTotalVirtual;
  DWORDLONG ullAvailVirtual;
  DWORDLONG ullAvailExtendedVirtual;
89
} MEMORY_STATUS_EX,*LPMEMORY_STATUS_EX;
90

91
#include <lmcons.h>
92
#include <shlobj.h>
93

94 95
#include <tlhelp32.h>
#include <psapi.h>
96
#ifndef _MSC_VER
Eli Zaretskii's avatar
Eli Zaretskii committed
97
#include <w32api.h>
98
#endif
Juanma Barranquero's avatar
Juanma Barranquero committed
99
#if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
100
/* This either is not in psapi.h or guarded by higher value of
101
   _WIN32_WINNT than what we use.  w32api supplied with MinGW 3.15
Eli Zaretskii's avatar
Eli Zaretskii committed
102
   defines it in psapi.h  */
103
typedef struct _PROCESS_MEMORY_COUNTERS_EX {
104 105 106 107 108 109 110 111 112 113 114
  DWORD  cb;
  DWORD  PageFaultCount;
  SIZE_T PeakWorkingSetSize;
  SIZE_T WorkingSetSize;
  SIZE_T QuotaPeakPagedPoolUsage;
  SIZE_T QuotaPagedPoolUsage;
  SIZE_T QuotaPeakNonPagedPoolUsage;
  SIZE_T QuotaNonPagedPoolUsage;
  SIZE_T PagefileUsage;
  SIZE_T PeakPagefileUsage;
  SIZE_T PrivateUsage;
115
} PROCESS_MEMORY_COUNTERS_EX,*PPROCESS_MEMORY_COUNTERS_EX;
Eli Zaretskii's avatar
Eli Zaretskii committed
116
#endif
117

118 119
#include <winioctl.h>
#include <aclapi.h>
120 121 122 123 124 125 126 127 128
#include <sddl.h>

#include <sys/acl.h>

/* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
   define them by hand if not already defined.  */
#ifndef SDDL_REVISION_1
#define SDDL_REVISION_1	1
#endif	/* SDDL_REVISION_1 */
129 130

#ifdef _MSC_VER
131 132 133 134
/* MSVC doesn't provide the definition of REPARSE_DATA_BUFFER and the
   associated macros, except on ntifs.h, which cannot be included
   because it triggers conflicts with other Windows API headers.  So
   we define it here by hand.  */
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161

typedef struct _REPARSE_DATA_BUFFER {
    ULONG  ReparseTag;
    USHORT ReparseDataLength;
    USHORT Reserved;
    union {
        struct {
            USHORT SubstituteNameOffset;
            USHORT SubstituteNameLength;
            USHORT PrintNameOffset;
            USHORT PrintNameLength;
            ULONG Flags;
            WCHAR PathBuffer[1];
        } SymbolicLinkReparseBuffer;
        struct {
            USHORT SubstituteNameOffset;
            USHORT SubstituteNameLength;
            USHORT PrintNameOffset;
            USHORT PrintNameLength;
            WCHAR PathBuffer[1];
        } MountPointReparseBuffer;
        struct {
            UCHAR  DataBuffer[1];
        } GenericReparseBuffer;
    } DUMMYUNIONNAME;
} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;

162
#ifndef FILE_DEVICE_FILE_SYSTEM
163
#define FILE_DEVICE_FILE_SYSTEM	9
164 165
#endif
#ifndef METHOD_BUFFERED
166
#define METHOD_BUFFERED	        0
167 168
#endif
#ifndef FILE_ANY_ACCESS
169
#define FILE_ANY_ACCESS	        0x00000000
170 171
#endif
#ifndef CTL_CODE
172
#define CTL_CODE(t,f,m,a)       (((t)<<16)|((a)<<14)|((f)<<2)|(m))
173
#endif
174 175
#define FSCTL_GET_REPARSE_POINT \
  CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
176 177
#endif

178
/* TCP connection support.  */
179 180 181 182 183 184 185 186 187 188
#include <sys/socket.h>
#undef socket
#undef bind
#undef connect
#undef htons
#undef ntohs
#undef inet_addr
#undef gethostname
#undef gethostbyname
#undef getservbyname
189
#undef getpeername
Geoff Voelker's avatar
Geoff Voelker committed
190
#undef shutdown
191 192 193 194 195 196
#undef setsockopt
#undef listen
#undef getsockname
#undef accept
#undef recvfrom
#undef sendto
197

Geoff Voelker's avatar
Geoff Voelker committed
198
#include "w32.h"
199
#include <dirent.h>
Daniel Colascione's avatar
Daniel Colascione committed
200
#include "w32common.h"
Geoff Voelker's avatar
Geoff Voelker committed
201
#include "w32heap.h"
202
#include "w32select.h"
203
#include "systime.h"
Eli Zaretskii's avatar
Eli Zaretskii committed
204
#include "dispextern.h"		/* for xstrcasecmp */
205
#include "coding.h"		/* for Vlocale_coding_system */
206

207 208 209
#include "careadlinkat.h"
#include "allocator.h"

Glenn Morris's avatar
Glenn Morris committed
210
/* For serial_configure and serial_open.  */
211 212
#include "process.h"

213 214 215
typedef HRESULT (WINAPI * ShGetFolderPath_fn)
  (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);

216 217
Lisp_Object QCloaded_from;

218
void globals_of_w32 (void);
219
static DWORD get_rid (PSID);
220 221 222 223 224
static int is_symlink (const char *);
static char * chase_symlinks (const char *);
static int enable_privilege (LPCTSTR, BOOL, TOKEN_PRIVILEGES *);
static int restore_privilege (TOKEN_PRIVILEGES *);
static BOOL WINAPI revert_to_self (void);
225

226 227 228 229 230 231
extern int sys_access (const char *, int);
extern void *e_malloc (size_t);
extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
		       EMACS_TIME *, void *);


232

233 234 235 236 237 238 239 240 241
/* Initialization states.

   WARNING: If you add any more such variables for additional APIs,
            you MUST add initialization for them to globals_of_w32
            below.  This is because these variables might get set
            to non-NULL values during dumping, but the dumped Emacs
            cannot reuse those values, because it could be run on a
            different version of the OS, where API addresses are
            different.  */
242 243 244 245
static BOOL g_b_init_is_windows_9x;
static BOOL g_b_init_open_process_token;
static BOOL g_b_init_get_token_information;
static BOOL g_b_init_lookup_account_sid;
246 247
static BOOL g_b_init_get_sid_sub_authority;
static BOOL g_b_init_get_sid_sub_authority_count;
248
static BOOL g_b_init_get_security_info;
249 250 251 252
static BOOL g_b_init_get_file_security;
static BOOL g_b_init_get_security_descriptor_owner;
static BOOL g_b_init_get_security_descriptor_group;
static BOOL g_b_init_is_valid_sid;
253 254 255 256 257 258 259 260 261 262
static BOOL g_b_init_create_toolhelp32_snapshot;
static BOOL g_b_init_process32_first;
static BOOL g_b_init_process32_next;
static BOOL g_b_init_open_thread_token;
static BOOL g_b_init_impersonate_self;
static BOOL g_b_init_revert_to_self;
static BOOL g_b_init_get_process_memory_info;
static BOOL g_b_init_get_process_working_set_size;
static BOOL g_b_init_global_memory_status;
static BOOL g_b_init_global_memory_status_ex;
263 264 265
static BOOL g_b_init_get_length_sid;
static BOOL g_b_init_equal_sid;
static BOOL g_b_init_copy_sid;
266 267
static BOOL g_b_init_get_native_system_info;
static BOOL g_b_init_get_system_times;
268
static BOOL g_b_init_create_symbolic_link;
269 270 271 272 273
static BOOL g_b_init_get_security_descriptor_dacl;
static BOOL g_b_init_convert_sd_to_sddl;
static BOOL g_b_init_convert_sddl_to_sd;
static BOOL g_b_init_is_valid_security_descriptor;
static BOOL g_b_init_set_file_security;
274

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
/*
  BEGIN: Wrapper functions around OpenProcessToken
  and other functions in advapi32.dll that are only
  supported in Windows NT / 2k / XP
*/
  /* ** Function pointer typedefs ** */
typedef BOOL (WINAPI * OpenProcessToken_Proc) (
    HANDLE ProcessHandle,
    DWORD DesiredAccess,
    PHANDLE TokenHandle);
typedef BOOL (WINAPI * GetTokenInformation_Proc) (
    HANDLE TokenHandle,
    TOKEN_INFORMATION_CLASS TokenInformationClass,
    LPVOID TokenInformation,
    DWORD TokenInformationLength,
    PDWORD ReturnLength);
291 292 293 294 295 296 297 298 299
typedef BOOL (WINAPI * GetProcessTimes_Proc) (
    HANDLE process_handle,
    LPFILETIME creation_time,
    LPFILETIME exit_time,
    LPFILETIME kernel_time,
    LPFILETIME user_time);

GetProcessTimes_Proc get_process_times_fn = NULL;

300 301
#ifdef _UNICODE
const char * const LookupAccountSid_Name = "LookupAccountSidW";
302
const char * const GetFileSecurity_Name =  "GetFileSecurityW";
303
const char * const SetFileSecurity_Name =  "SetFileSecurityW";
304 305
#else
const char * const LookupAccountSid_Name = "LookupAccountSidA";
306
const char * const GetFileSecurity_Name =  "GetFileSecurityA";
307
const char * const SetFileSecurity_Name =  "SetFileSecurityA";
308 309 310 311 312 313 314 315 316
#endif
typedef BOOL (WINAPI * LookupAccountSid_Proc) (
    LPCTSTR lpSystemName,
    PSID Sid,
    LPTSTR Name,
    LPDWORD cbName,
    LPTSTR DomainName,
    LPDWORD cbDomainName,
    PSID_NAME_USE peUse);
317 318 319 320 321
typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
    PSID pSid,
    DWORD n);
typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
    PSID pSid);
322 323 324 325 326 327 328 329 330
typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
    HANDLE handle,
    SE_OBJECT_TYPE ObjectType,
    SECURITY_INFORMATION SecurityInfo,
    PSID *ppsidOwner,
    PSID *ppsidGroup,
    PACL *ppDacl,
    PACL *ppSacl,
    PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
331 332 333 334 335 336
typedef BOOL (WINAPI * GetFileSecurity_Proc) (
    LPCTSTR lpFileName,
    SECURITY_INFORMATION RequestedInformation,
    PSECURITY_DESCRIPTOR pSecurityDescriptor,
    DWORD nLength,
    LPDWORD lpnLengthNeeded);
337 338 339 340
typedef BOOL (WINAPI *SetFileSecurity_Proc) (
    LPCTSTR lpFileName,
    SECURITY_INFORMATION SecurityInformation,
    PSECURITY_DESCRIPTOR pSecurityDescriptor);
341 342 343 344 345 346 347 348
typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
    PSECURITY_DESCRIPTOR pSecurityDescriptor,
    PSID *pOwner,
    LPBOOL lpbOwnerDefaulted);
typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
    PSECURITY_DESCRIPTOR pSecurityDescriptor,
    PSID *pGroup,
    LPBOOL lpbGroupDefaulted);
349 350 351 352 353
typedef BOOL (WINAPI *GetSecurityDescriptorDacl_Proc) (
    PSECURITY_DESCRIPTOR pSecurityDescriptor,
    LPBOOL lpbDaclPresent,
    PACL *pDacl,
    LPBOOL lpbDaclDefaulted);
354 355
typedef BOOL (WINAPI * IsValidSid_Proc) (
    PSID sid);
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
    DWORD dwFlags,
    DWORD th32ProcessID);
typedef BOOL (WINAPI * Process32First_Proc) (
    HANDLE hSnapshot,
    LPPROCESSENTRY32 lppe);
typedef BOOL (WINAPI * Process32Next_Proc) (
    HANDLE hSnapshot,
    LPPROCESSENTRY32 lppe);
typedef BOOL (WINAPI * OpenThreadToken_Proc) (
    HANDLE ThreadHandle,
    DWORD DesiredAccess,
    BOOL OpenAsSelf,
    PHANDLE TokenHandle);
typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
    SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
    HANDLE Process,
    PPROCESS_MEMORY_COUNTERS ppsmemCounters,
    DWORD cb);
typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
    HANDLE hProcess,
379 380
    PSIZE_T lpMinimumWorkingSetSize,
    PSIZE_T lpMaximumWorkingSetSize);
381 382 383
typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
    LPMEMORYSTATUS lpBuffer);
typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
384
    LPMEMORY_STATUS_EX lpBuffer);
385 386 387 388 389 390 391 392 393
typedef BOOL (WINAPI * CopySid_Proc) (
    DWORD nDestinationSidLength,
    PSID pDestinationSid,
    PSID pSourceSid);
typedef BOOL (WINAPI * EqualSid_Proc) (
    PSID pSid1,
    PSID pSid2);
typedef DWORD (WINAPI * GetLengthSid_Proc) (
    PSID pSid);
394 395 396 397 398 399
typedef void (WINAPI * GetNativeSystemInfo_Proc) (
    LPSYSTEM_INFO lpSystemInfo);
typedef BOOL (WINAPI * GetSystemTimes_Proc) (
    LPFILETIME lpIdleTime,
    LPFILETIME lpKernelTime,
    LPFILETIME lpUserTime);
400 401 402 403
typedef BOOLEAN (WINAPI *CreateSymbolicLink_Proc) (
    LPTSTR lpSymlinkFileName,
    LPTSTR lpTargetFileName,
    DWORD  dwFlags);
404 405 406 407 408 409 410 411 412 413 414 415
typedef BOOL (WINAPI *ConvertStringSecurityDescriptorToSecurityDescriptor_Proc) (
    LPCTSTR StringSecurityDescriptor,
    DWORD StringSDRevision,
    PSECURITY_DESCRIPTOR  *SecurityDescriptor,
    PULONG  SecurityDescriptorSize);
typedef BOOL (WINAPI *ConvertSecurityDescriptorToStringSecurityDescriptor_Proc) (
    PSECURITY_DESCRIPTOR  SecurityDescriptor,
    DWORD RequestedStringSDRevision,
    SECURITY_INFORMATION SecurityInformation,
    LPTSTR  *StringSecurityDescriptor,
    PULONG StringSecurityDescriptorLen);
typedef BOOL (WINAPI *IsValidSecurityDescriptor_Proc) (PSECURITY_DESCRIPTOR);
416

417
  /* ** A utility function ** */
Kim F. Storm's avatar
Kim F. Storm committed
418
static BOOL
419
is_windows_9x (void)
420
{
421
  static BOOL s_b_ret = 0;
422
  OSVERSIONINFO os_ver;
423
  if (g_b_init_is_windows_9x == 0)
424
    {
425
      g_b_init_is_windows_9x = 1;
426 427
      ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
      os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
428 429 430 431
      if (GetVersionEx (&os_ver))
        {
          s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
        }
432
    }
433
  return s_b_ret;
434 435
}

436 437
static Lisp_Object ltime (ULONGLONG);

438
/* Get total user and system times for get-internal-run-time.
439
   Returns a list of integers if the times are provided by the OS
440 441
   (NT derivatives), otherwise it returns the result of current-time. */
Lisp_Object
442
w32_get_internal_run_time (void)
443 444 445 446
{
  if (get_process_times_fn)
    {
      FILETIME create, exit, kernel, user;
447
      HANDLE proc = GetCurrentProcess ();
448 449 450 451 452 453 454 455
      if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
        {
          LARGE_INTEGER user_int, kernel_int, total;
          user_int.LowPart = user.dwLowDateTime;
          user_int.HighPart = user.dwHighDateTime;
          kernel_int.LowPart = kernel.dwLowDateTime;
          kernel_int.HighPart = kernel.dwHighDateTime;
          total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
456
	  return ltime (total.QuadPart);
457 458 459 460 461 462
        }
    }

  return Fcurrent_time ();
}

463 464
  /* ** The wrapper functions ** */

465 466 467 468
static BOOL WINAPI
open_process_token (HANDLE ProcessHandle,
		    DWORD DesiredAccess,
		    PHANDLE TokenHandle)
469
{
470
  static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
471 472 473 474 475
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
476 477 478 479 480 481 482 483
  if (g_b_init_open_process_token == 0)
    {
      g_b_init_open_process_token = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      s_pfn_Open_Process_Token =
        (OpenProcessToken_Proc) GetProcAddress (hm_advapi32, "OpenProcessToken");
    }
  if (s_pfn_Open_Process_Token == NULL)
484 485 486 487
    {
      return FALSE;
    }
  return (
488
      s_pfn_Open_Process_Token (
489 490 491 492 493 494
          ProcessHandle,
          DesiredAccess,
          TokenHandle)
      );
}

495 496 497 498 499 500
static BOOL WINAPI
get_token_information (HANDLE TokenHandle,
		       TOKEN_INFORMATION_CLASS TokenInformationClass,
		       LPVOID TokenInformation,
		       DWORD TokenInformationLength,
		       PDWORD ReturnLength)
501
{
502
  static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
503 504 505 506 507
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
508 509 510 511 512 513 514 515
  if (g_b_init_get_token_information == 0)
    {
      g_b_init_get_token_information = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      s_pfn_Get_Token_Information =
        (GetTokenInformation_Proc) GetProcAddress (hm_advapi32, "GetTokenInformation");
    }
  if (s_pfn_Get_Token_Information == NULL)
516 517 518 519
    {
      return FALSE;
    }
  return (
520
      s_pfn_Get_Token_Information (
521 522 523 524 525 526 527 528
          TokenHandle,
          TokenInformationClass,
          TokenInformation,
          TokenInformationLength,
          ReturnLength)
      );
}

529 530 531 532 533 534 535 536
static BOOL WINAPI
lookup_account_sid (LPCTSTR lpSystemName,
		    PSID Sid,
		    LPTSTR Name,
		    LPDWORD cbName,
		    LPTSTR DomainName,
		    LPDWORD cbDomainName,
		    PSID_NAME_USE peUse)
537
{
538
  static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
539 540 541 542 543
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
544 545 546 547 548 549 550 551
  if (g_b_init_lookup_account_sid == 0)
    {
      g_b_init_lookup_account_sid = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      s_pfn_Lookup_Account_Sid =
        (LookupAccountSid_Proc) GetProcAddress (hm_advapi32, LookupAccountSid_Name);
    }
  if (s_pfn_Lookup_Account_Sid == NULL)
552 553 554 555
    {
      return FALSE;
    }
  return (
556
      s_pfn_Lookup_Account_Sid (
557 558 559 560 561 562 563 564 565 566
          lpSystemName,
          Sid,
          Name,
          cbName,
          DomainName,
          cbDomainName,
          peUse)
      );
}

567 568
static PDWORD WINAPI
get_sid_sub_authority (PSID pSid, DWORD n)
569 570
{
  static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
571
  static DWORD zero = 0U;
572 573 574
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
575
      return &zero;
576 577 578 579 580 581 582 583 584 585 586
    }
  if (g_b_init_get_sid_sub_authority == 0)
    {
      g_b_init_get_sid_sub_authority = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      s_pfn_Get_Sid_Sub_Authority =
        (GetSidSubAuthority_Proc) GetProcAddress (
            hm_advapi32, "GetSidSubAuthority");
    }
  if (s_pfn_Get_Sid_Sub_Authority == NULL)
    {
587
      return &zero;
588 589 590 591
    }
  return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
}

592 593
static PUCHAR WINAPI
get_sid_sub_authority_count (PSID pSid)
594 595
{
  static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
596
  static UCHAR zero = 0U;
597 598 599
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
600
      return &zero;
601 602 603 604 605 606 607 608 609 610 611
    }
  if (g_b_init_get_sid_sub_authority_count == 0)
    {
      g_b_init_get_sid_sub_authority_count = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      s_pfn_Get_Sid_Sub_Authority_Count =
        (GetSidSubAuthorityCount_Proc) GetProcAddress (
            hm_advapi32, "GetSidSubAuthorityCount");
    }
  if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
    {
612
      return &zero;
613 614 615 616
    }
  return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
}

617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
static DWORD WINAPI
get_security_info (HANDLE handle,
		   SE_OBJECT_TYPE ObjectType,
		   SECURITY_INFORMATION SecurityInfo,
		   PSID *ppsidOwner,
		   PSID *ppsidGroup,
		   PACL *ppDacl,
		   PACL *ppSacl,
		   PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
{
  static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
  if (g_b_init_get_security_info == 0)
    {
      g_b_init_get_security_info = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      s_pfn_Get_Security_Info =
        (GetSecurityInfo_Proc) GetProcAddress (
            hm_advapi32, "GetSecurityInfo");
    }
  if (s_pfn_Get_Security_Info == NULL)
    {
      return FALSE;
    }
  return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
				   ppsidOwner, ppsidGroup, ppDacl, ppSacl,
				   ppSecurityDescriptor));
}

650 651 652 653 654 655
static BOOL WINAPI
get_file_security (LPCTSTR lpFileName,
		   SECURITY_INFORMATION RequestedInformation,
		   PSECURITY_DESCRIPTOR pSecurityDescriptor,
		   DWORD nLength,
		   LPDWORD lpnLengthNeeded)
656 657 658 659 660
{
  static GetFileSecurity_Proc s_pfn_Get_File_Security = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
661
      errno = ENOTSUP;
662 663 664 665 666 667 668 669 670 671 672 673
      return FALSE;
    }
  if (g_b_init_get_file_security == 0)
    {
      g_b_init_get_file_security = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      s_pfn_Get_File_Security =
        (GetFileSecurity_Proc) GetProcAddress (
            hm_advapi32, GetFileSecurity_Name);
    }
  if (s_pfn_Get_File_Security == NULL)
    {
674
      errno = ENOTSUP;
675 676 677 678 679 680 681
      return FALSE;
    }
  return (s_pfn_Get_File_Security (lpFileName, RequestedInformation,
				   pSecurityDescriptor, nLength,
				   lpnLengthNeeded));
}

682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
static BOOL WINAPI
set_file_security (LPCTSTR lpFileName,
		   SECURITY_INFORMATION SecurityInformation,
		   PSECURITY_DESCRIPTOR pSecurityDescriptor)
{
  static SetFileSecurity_Proc s_pfn_Set_File_Security = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      errno = ENOTSUP;
      return FALSE;
    }
  if (g_b_init_set_file_security == 0)
    {
      g_b_init_set_file_security = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      s_pfn_Set_File_Security =
        (SetFileSecurity_Proc) GetProcAddress (
            hm_advapi32, SetFileSecurity_Name);
    }
  if (s_pfn_Set_File_Security == NULL)
    {
      errno = ENOTSUP;
      return FALSE;
    }
  return (s_pfn_Set_File_Security (lpFileName, SecurityInformation,
				   pSecurityDescriptor));
}

711 712 713 714
static BOOL WINAPI
get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
			       PSID *pOwner,
			       LPBOOL lpbOwnerDefaulted)
715 716 717 718 719
{
  static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
720
      errno = ENOTSUP;
721 722 723 724 725 726 727 728 729 730 731 732
      return FALSE;
    }
  if (g_b_init_get_security_descriptor_owner == 0)
    {
      g_b_init_get_security_descriptor_owner = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      s_pfn_Get_Security_Descriptor_Owner =
        (GetSecurityDescriptorOwner_Proc) GetProcAddress (
            hm_advapi32, "GetSecurityDescriptorOwner");
    }
  if (s_pfn_Get_Security_Descriptor_Owner == NULL)
    {
733
      errno = ENOTSUP;
734 735 736 737 738 739
      return FALSE;
    }
  return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
					       lpbOwnerDefaulted));
}

740 741 742 743
static BOOL WINAPI
get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
			       PSID *pGroup,
			       LPBOOL lpbGroupDefaulted)
744 745 746 747 748
{
  static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
749
      errno = ENOTSUP;
750 751 752 753 754 755 756 757 758 759 760 761
      return FALSE;
    }
  if (g_b_init_get_security_descriptor_group == 0)
    {
      g_b_init_get_security_descriptor_group = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      s_pfn_Get_Security_Descriptor_Group =
        (GetSecurityDescriptorGroup_Proc) GetProcAddress (
            hm_advapi32, "GetSecurityDescriptorGroup");
    }
  if (s_pfn_Get_Security_Descriptor_Group == NULL)
    {
762
      errno = ENOTSUP;
763 764 765 766 767 768
      return FALSE;
    }
  return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
					       lpbGroupDefaulted));
}

769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
static BOOL WINAPI
get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor,
			      LPBOOL lpbDaclPresent,
			      PACL *pDacl,
			      LPBOOL lpbDaclDefaulted)
{
  static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      errno = ENOTSUP;
      return FALSE;
    }
  if (g_b_init_get_security_descriptor_dacl == 0)
    {
      g_b_init_get_security_descriptor_dacl = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      s_pfn_Get_Security_Descriptor_Dacl =
        (GetSecurityDescriptorDacl_Proc) GetProcAddress (
            hm_advapi32, "GetSecurityDescriptorDacl");
    }
  if (s_pfn_Get_Security_Descriptor_Dacl == NULL)
    {
      errno = ENOTSUP;
      return FALSE;
    }
  return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor,
					      lpbDaclPresent, pDacl,
					      lpbDaclDefaulted));
}

800 801
static BOOL WINAPI
is_valid_sid (PSID sid)
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
{
  static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
  if (g_b_init_is_valid_sid == 0)
    {
      g_b_init_is_valid_sid = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      s_pfn_Is_Valid_Sid =
        (IsValidSid_Proc) GetProcAddress (
            hm_advapi32, "IsValidSid");
    }
  if (s_pfn_Is_Valid_Sid == NULL)
    {
      return FALSE;
    }
  return (s_pfn_Is_Valid_Sid (sid));
}

824 825
static BOOL WINAPI
equal_sid (PSID sid1, PSID sid2)
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
{
  static EqualSid_Proc s_pfn_Equal_Sid = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
  if (g_b_init_equal_sid == 0)
    {
      g_b_init_equal_sid = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      s_pfn_Equal_Sid =
        (EqualSid_Proc) GetProcAddress (
            hm_advapi32, "EqualSid");
    }
  if (s_pfn_Equal_Sid == NULL)
    {
      return FALSE;
    }
  return (s_pfn_Equal_Sid (sid1, sid2));
}

848 849
static DWORD WINAPI
get_length_sid (PSID sid)
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
{
  static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return 0;
    }
  if (g_b_init_get_length_sid == 0)
    {
      g_b_init_get_length_sid = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      s_pfn_Get_Length_Sid =
        (GetLengthSid_Proc) GetProcAddress (
            hm_advapi32, "GetLengthSid");
    }
  if (s_pfn_Get_Length_Sid == NULL)
    {
      return 0;
    }
  return (s_pfn_Get_Length_Sid (sid));
}

872 873
static BOOL WINAPI
copy_sid (DWORD destlen, PSID dest, PSID src)
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
{
  static CopySid_Proc s_pfn_Copy_Sid = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
  if (g_b_init_copy_sid == 0)
    {
      g_b_init_copy_sid = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      s_pfn_Copy_Sid =
        (CopySid_Proc) GetProcAddress (
            hm_advapi32, "CopySid");
    }
  if (s_pfn_Copy_Sid == NULL)
    {
      return FALSE;
    }
  return (s_pfn_Copy_Sid (destlen, dest, src));
}

896 897 898 899 900 901
/*
  END: Wrapper functions around OpenProcessToken
  and other functions in advapi32.dll that are only
  supported in Windows NT / 2k / XP
*/

902 903
static void WINAPI
get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
{
  static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
  if (is_windows_9x () != TRUE)
    {
      if (g_b_init_get_native_system_info == 0)
	{
	  g_b_init_get_native_system_info = 1;
	  s_pfn_Get_Native_System_Info =
	    (GetNativeSystemInfo_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
						      "GetNativeSystemInfo");
	}
      if (s_pfn_Get_Native_System_Info != NULL)
	s_pfn_Get_Native_System_Info (lpSystemInfo);
    }
  else
    lpSystemInfo->dwNumberOfProcessors = -1;
}

922 923 924 925
static BOOL WINAPI
get_system_times (LPFILETIME lpIdleTime,
		  LPFILETIME lpKernelTime,
		  LPFILETIME lpUserTime)
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
{
  static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
  if (g_b_init_get_system_times == 0)
    {
      g_b_init_get_system_times = 1;
      s_pfn_Get_System_times =
	(GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
					     "GetSystemTimes");
    }
  if (s_pfn_Get_System_times == NULL)
    return FALSE;
  return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
}
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

static BOOLEAN WINAPI
create_symbolic_link (LPTSTR lpSymlinkFilename,
		      LPTSTR lpTargetFileName,
		      DWORD dwFlags)
{
  static CreateSymbolicLink_Proc s_pfn_Create_Symbolic_Link = NULL;
  BOOLEAN retval;

  if (is_windows_9x () == TRUE)
    {
      errno = ENOSYS;
      return 0;
    }
  if (g_b_init_create_symbolic_link == 0)
    {
      g_b_init_create_symbolic_link = 1;
#ifdef _UNICODE
      s_pfn_Create_Symbolic_Link =
	(CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
						 "CreateSymbolicLinkW");
#else
      s_pfn_Create_Symbolic_Link =
	(CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
						 "CreateSymbolicLinkA");
#endif
    }
  if (s_pfn_Create_Symbolic_Link == NULL)
    {
      errno = ENOSYS;
      return 0;
    }

  retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
				       dwFlags);
  /* If we were denied creation of the symlink, try again after
     enabling the SeCreateSymbolicLinkPrivilege for our process.  */
  if (!retval)
    {
      TOKEN_PRIVILEGES priv_current;

      if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE, &priv_current))
	{
	  retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
					       dwFlags);
	  restore_privilege (&priv_current);
	  revert_to_self ();
	}
    }
  return retval;
}
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 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 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

static BOOL WINAPI
is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor)
{
  static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc = NULL;

  if (is_windows_9x () == TRUE)
    {
      errno = ENOTSUP;
      return FALSE;
    }

  if (g_b_init_is_valid_security_descriptor == 0)
    {
      g_b_init_is_valid_security_descriptor = 1;
      s_pfn_Is_Valid_Security_Descriptor_Proc =
	(IsValidSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
							"IsValidSecurityDescriptor");
    }
  if (s_pfn_Is_Valid_Security_Descriptor_Proc == NULL)
    {
      errno = ENOTSUP;
      return FALSE;
    }

  return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor);
}

static BOOL WINAPI
convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor,
		    DWORD RequestedStringSDRevision,
		    SECURITY_INFORMATION SecurityInformation,
		    LPTSTR  *StringSecurityDescriptor,
		    PULONG StringSecurityDescriptorLen)
{
  static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL = NULL;
  BOOL retval;

  if (is_windows_9x () == TRUE)
    {
      errno = ENOTSUP;
      return FALSE;
    }

  if (g_b_init_convert_sd_to_sddl == 0)
    {
      g_b_init_convert_sd_to_sddl = 1;
#ifdef _UNICODE
      s_pfn_Convert_SD_To_SDDL =
	(ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
										  "ConvertSecurityDescriptorToStringSecurityDescriptorW");
#else
      s_pfn_Convert_SD_To_SDDL =
	(ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
										  "ConvertSecurityDescriptorToStringSecurityDescriptorA");
#endif
    }
  if (s_pfn_Convert_SD_To_SDDL == NULL)
    {
      errno = ENOTSUP;
      return FALSE;
    }

  retval = s_pfn_Convert_SD_To_SDDL (SecurityDescriptor,
				     RequestedStringSDRevision,
				     SecurityInformation,
				     StringSecurityDescriptor,
				     StringSecurityDescriptorLen);

  return retval;
}

static BOOL WINAPI
convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor,
		    DWORD StringSDRevision,
		    PSECURITY_DESCRIPTOR  *SecurityDescriptor,
		    PULONG  SecurityDescriptorSize)
{
  static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD = NULL;
  BOOL retval;

  if (is_windows_9x () == TRUE)
    {
      errno = ENOTSUP;
      return FALSE;
    }

  if (g_b_init_convert_sddl_to_sd == 0)
    {
      g_b_init_convert_sddl_to_sd = 1;
#ifdef _UNICODE
      s_pfn_Convert_SDDL_To_SD =
	(ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
										  "ConvertStringSecurityDescriptorToSecurityDescriptorW");
#else
      s_pfn_Convert_SDDL_To_SD =
	(ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
										  "ConvertStringSecurityDescriptorToSecurityDescriptorA");
#endif
    }
  if (s_pfn_Convert_SDDL_To_SD == NULL)
    {
      errno = ENOTSUP;
      return FALSE;
    }

  retval = s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor,
				     StringSDRevision,
				     SecurityDescriptor,
				     SecurityDescriptorSize);

  return retval;
}

Andrew Innes's avatar
Andrew Innes committed
1108 1109


1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
/* Return 1 if P is a valid pointer to an object of size SIZE.  Return
   0 if P is NOT a valid pointer.  Return -1 if we cannot validate P.

   This is called from alloc.c:valid_pointer_p.  */
int
w32_valid_pointer_p (void *p, int size)
{
  SIZE_T done;
  HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());

  if (h)
    {
      unsigned char *buf = alloca (size);
      int retval = ReadProcessMemory (h, p, buf, size, &done);

      CloseHandle (h);
      return retval;
    }
  else
    return -1;
}

Geoff Voelker's avatar
Geoff Voelker committed
1132
static char startup_dir[MAXPATHLEN];
1133

Richard M. Stallman's avatar
Richard M. Stallman committed
1134
/* Get the current working directory.  */
1135
char *
1136
getcwd (char *dir, int dirsize)
Richard M. Stallman's avatar
Richard M. Stallman committed
1137
{
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
  if (!dirsize)
    {
      errno = EINVAL;
      return NULL;
    }
  if (dirsize <= strlen (startup_dir))
    {
      errno = ERANGE;
      return NULL;
    }
Geoff Voelker's avatar
Geoff Voelker committed
1148
#if 0
1149 1150 1151
  if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
    return dir;
  return NULL;
Geoff Voelker's avatar
Geoff Voelker committed
1152
#else
1153 1154
  /* Emacs doesn't actually change directory itself, it stays in the
     same directory where it was started.  */
Geoff Voelker's avatar
Geoff Voelker committed
1155 1156 1157
  strcpy (dir, startup_dir);
  return dir;
#endif
Richard M. Stallman's avatar
Richard M. Stallman committed
1158 1159 1160
}

/* Emulate getloadavg.  */
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 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 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 1247 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

struct load_sample {
  time_t sample_time;
  ULONGLONG idle;
  ULONGLONG kernel;
  ULONGLONG user;
};

/* Number of processors on this machine.  */
static unsigned num_of_processors;

/* We maintain 1-sec samples for the last 16 minutes in a circular buffer.  */
static struct load_sample samples[16*60];
static int first_idx = -1, last_idx = -1;
static int max_idx = sizeof (samples) / sizeof (samples[0]);

static int
buf_next (int from)
{
  int next_idx = from + 1;

  if (next_idx >= max_idx)
    next_idx = 0;

  return next_idx;
}

static int
buf_prev (int from)
{
  int prev_idx = from - 1;

  if (prev_idx < 0)
    prev_idx = max_idx - 1;

  return prev_idx;
}

static void
sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
{
  SYSTEM_INFO sysinfo;
  FILETIME ft_idle, ft_user, ft_kernel;

  /* Initialize the number of processors on this machine.  */
  if (num_of_processors <= 0)
    {
      get_native_system_info (&sysinfo);
      num_of_processors = sysinfo.dwNumberOfProcessors;
      if (num_of_processors <= 0)
	{
	  GetSystemInfo (&sysinfo);
	  num_of_processors = sysinfo.dwNumberOfProcessors;
	}
      if (num_of_processors <= 0)
	num_of_processors = 1;
    }

  /* TODO: Take into account threads that are ready to run, by
     sampling the "\System\Processor Queue Length" performance
     counter.  The code below accounts only for threads that are
     actually running.  */

  if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
    {
      ULARGE_INTEGER uidle, ukernel, uuser;

      memcpy (&uidle, &ft_idle, sizeof (ft_idle));
      memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
      memcpy (&uuser, &ft_user, sizeof (ft_user));
      *idle = uidle.QuadPart;
      *kernel = ukernel.QuadPart;
      *user = uuser.QuadPart;
    }
  else
    {
      *idle = 0;
      *kernel = 0;
      *user = 0;
    }
}

/* Produce the load average for a given time interval, using the
   samples in the samples[] array.  WHICH can be 0, 1, or 2, meaning
   1-minute, 5-minute, or 15-minute average, respectively. */
static double
getavg (int which)
{
  double retval = -1.0;
  double tdiff;
  int idx;
  double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
  time_t now = samples[last_idx].sample_time;

  if (first_idx != last_idx)
    {
      for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
	{
	  tdiff = difftime (now, samples[idx].sample_time);
	  if (tdiff >= span - 2*DBL_EPSILON*now)
	    {
	      long double sys =
		samples[last_idx].kernel + samples[last_idx].user
		- (samples[idx].kernel + samples[idx].user);
	      long double idl = samples[last_idx].idle - samples[idx].idle;

	      retval = (1.0 - idl / sys) * num_of_processors;
	      break;
	    }
	  if (idx == first_idx)
	    break;
	}
    }

  return retval;
}

Richard M. Stallman's avatar
Richard M. Stallman committed
1278 1279 1280
int
getloadavg (double loadavg[], int nelem)
{
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
  int elem;
  ULONGLONG idle, kernel, user;
  time_t now = time (NULL);

  /* Store another sample.  We ignore samples that are less than 1 sec
     apart.  */
  if (difftime (now, samples[last_idx].sample_time) >= 1.0 - 2*DBL_EPSILON*now)
    {
      sample_system_load (&idle, &kernel, &user);
      last_idx = buf_next (last_idx);
      samples[last_idx].sample_time = now;
      samples[last_idx].idle = idle;
      samples[last_idx].kernel = kernel;
      samples[last_idx].user = user;
      /* If the buffer has more that 15 min worth of samples, discard
	 the old ones.  */
      if (first_idx == -1)
	first_idx = last_idx;
      while (first_idx != last_idx
	     && (difftime (now, samples[first_idx].sample_time)
	         >= 15.0*60 + 2*DBL_EPSILON*now))
	first_idx = buf_next (first_idx);
    }
Richard M. Stallman's avatar
Richard M. Stallman committed
1304

1305
  for (elem = 0; elem < nelem; elem++)
Richard M. Stallman's avatar
Richard M. Stallman committed
1306
    {
1307 1308 1309 1310 1311
      double avg = getavg (elem);

      if (avg < 0)
	break;
      loadavg[elem] = avg;
Richard M. Stallman's avatar
Richard M. Stallman committed
1312
    }
1313 1314

  return elem;
Richard M. Stallman's avatar
Richard M. Stallman committed
1315 1316
}

1317
/* Emulate getpwuid, getpwnam and others.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
1318

Geoff Voelker's avatar
Geoff Voelker committed
1319 1320
#define PASSWD_FIELD_SIZE 256

1321 1322 1323 1324 1325
static char dflt_passwd_name[PASSWD_FIELD_SIZE];
static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
static char dflt_passwd_dir[PASSWD_FIELD_SIZE];
static char dflt_passwd_shell[PASSWD_FIELD_SIZE];
Richard M. Stallman's avatar
Richard M. Stallman committed
1326

1327
static struct passwd dflt_passwd =
Richard M. Stallman's avatar
Richard M. Stallman committed
1328
{
1329 1330
  dflt_passwd_name,
  dflt_passwd_passwd,
Richard M. Stallman's avatar
Richard M. Stallman committed
1331 1332 1333
  0,
  0,
  0,
1334 1335 1336
  dflt_passwd_gecos,
  dflt_passwd_dir,
  dflt_passwd_shell,
Richard M. Stallman's avatar
Richard M. Stallman committed
1337 1338
};

1339 1340 1341
static char dflt_group_name[GNLEN+1];

static struct group dflt_group =
Lars Hansen's avatar
Lars Hansen committed
1342
{
1343 1344 1345 1346
  /* When group information is not available, we return this as the
     group for all files.  */
  dflt_group_name,
  0,
Lars Hansen's avatar
Lars Hansen committed
1347 1348
};

1349
unsigned
1350
getuid (void)
1351
{
1352
  return dflt_passwd.pw_uid;
1353 1354
}

1355
unsigned
1356
geteuid (void)
1357
{
1358 1359 1360
  /* I could imagine arguing for checking to see whether the user is
     in the Administrators group and returning a UID of 0 for that
     case, but I don't know how wise that would be in the long run.  */
1361
  return getuid ();
1362 1363
}

1364
unsigned
1365
getgid (void)
1366
{
1367
  return dflt_passwd.pw_gid;
1368 1369
}

1370
unsigned
1371
getegid (void)
1372
{
1373 1374 1375
  return getgid ();
}

Richard M. Stallman's avatar
Richard M. Stallman committed
1376
struct passwd *
1377
getpwuid (unsigned uid)
Richard M. Stallman's avatar
Richard M. Stallman committed
1378
{
1379 1380
  if (uid == dflt_passwd.pw_uid)
    return &dflt_passwd;
1381
  return NULL;
Richard M. Stallman's avatar
Richard M. Stallman committed
1382 1383
}

Lars Hansen's avatar
Lars Hansen committed
1384 1385 1386
struct group *
getgrgid (gid_t gid)
{
1387
  return &dflt_group;
Lars Hansen's avatar
Lars Hansen committed
1388 1389
}

Richard M. Stallman's avatar
Richard M. Stallman committed
1390 1391 1392 1393
struct passwd *
getpwnam (char *name)
{
  struct passwd *pw;
1394

Richard M. Stallman's avatar
Richard M. Stallman committed
1395 1396 1397 1398
  pw = getpwuid (getuid ());
  if (!pw)
    return pw;

1399
  if (xstrcasecmp (name, pw->pw_name))
Richard M. Stallman's avatar
Richard M. Stallman committed
1400 1401 1402 1403 1404
    return NULL;

  return pw;
}

1405
static void
1406
init_user_info (void)
Richard M. Stallman's avatar
Richard M. Stallman committed
1407
{
1408 1409 1410 1411 1412 1413 1414
  /* Find the user's real name by opening the process token and
     looking up the name associated with the user-sid in that token.

     Use the relative portion of the identifier authority value from
     the user-sid as the user id value (same for group id using the
     primary group sid from the process token). */

1415
  char         uname[UNLEN+1], gname[GNLEN+1], domain[1025];
1416
  DWORD        ulength = sizeof (uname), dlength = sizeof (domain), needed;
1417
  DWORD	       glength = sizeof (gname);
1418 1419
  HANDLE       token = NULL;
  SID_NAME_USE user_type;
1420 1421
  unsigned char *buf = NULL;
  DWORD        blen = 0;