w32.c 160 KB
Newer Older
1
/* Utility and Unix shadow routines for GNU Emacs on the Microsoft W32 API.
2
   Copyright (C) 1994-1995, 2000-2011  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 <mbstring.h>	/* for _mbspbrk */
35
#include <math.h>
36
#include <setjmp.h>
37
#include <time.h>
38 39

/* must include CRT headers *before* config.h */
Pavel Janík's avatar
Pavel Janík committed
40 41 42

#include <config.h>

43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
#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
63

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

66 67
#undef localtime

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

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

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

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

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

117
/* TCP connection support.  */
118 119 120 121 122 123 124 125 126 127
#include <sys/socket.h>
#undef socket
#undef bind
#undef connect
#undef htons
#undef ntohs
#undef inet_addr
#undef gethostname
#undef gethostbyname
#undef getservbyname
128
#undef getpeername
Geoff Voelker's avatar
Geoff Voelker committed
129
#undef shutdown
130 131 132 133 134 135
#undef setsockopt
#undef listen
#undef getsockname
#undef accept
#undef recvfrom
#undef sendto
136

Geoff Voelker's avatar
Geoff Voelker committed
137
#include "w32.h"
138
#include "ndir.h"
Geoff Voelker's avatar
Geoff Voelker committed
139
#include "w32heap.h"
140
#include "systime.h"
Eli Zaretskii's avatar
Eli Zaretskii committed
141
#include "dispextern.h"		/* for xstrcasecmp */
142
#include "coding.h"		/* for Vlocale_coding_system */
143

144 145 146
#include "careadlinkat.h"
#include "allocator.h"

Glenn Morris's avatar
Glenn Morris committed
147
/* For serial_configure and serial_open.  */
148 149
#include "process.h"

150 151 152
typedef HRESULT (WINAPI * ShGetFolderPath_fn)
  (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);

153 154
Lisp_Object QCloaded_from;

155
void globals_of_w32 (void);
156
static DWORD get_rid (PSID);
157

158

159 160 161 162 163 164 165 166 167
/* 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.  */
168 169 170 171
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;
172 173
static BOOL g_b_init_get_sid_sub_authority;
static BOOL g_b_init_get_sid_sub_authority_count;
174 175 176 177
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;
178 179 180 181 182 183 184 185 186 187
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;
188 189 190
static BOOL g_b_init_get_length_sid;
static BOOL g_b_init_equal_sid;
static BOOL g_b_init_copy_sid;
191 192
static BOOL g_b_init_get_native_system_info;
static BOOL g_b_init_get_system_times;
193

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
/*
  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);
210 211 212 213 214 215 216 217 218
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;

219 220
#ifdef _UNICODE
const char * const LookupAccountSid_Name = "LookupAccountSidW";
221
const char * const GetFileSecurity_Name =  "GetFileSecurityW";
222 223
#else
const char * const LookupAccountSid_Name = "LookupAccountSidA";
224
const char * const GetFileSecurity_Name =  "GetFileSecurityA";
225 226 227 228 229 230 231 232 233
#endif
typedef BOOL (WINAPI * LookupAccountSid_Proc) (
    LPCTSTR lpSystemName,
    PSID Sid,
    LPTSTR Name,
    LPDWORD cbName,
    LPTSTR DomainName,
    LPDWORD cbDomainName,
    PSID_NAME_USE peUse);
234 235 236 237 238
typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
    PSID pSid,
    DWORD n);
typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
    PSID pSid);
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
typedef BOOL (WINAPI * GetFileSecurity_Proc) (
    LPCTSTR lpFileName,
    SECURITY_INFORMATION RequestedInformation,
    PSECURITY_DESCRIPTOR pSecurityDescriptor,
    DWORD nLength,
    LPDWORD lpnLengthNeeded);
typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
    PSECURITY_DESCRIPTOR pSecurityDescriptor,
    PSID *pOwner,
    LPBOOL lpbOwnerDefaulted);
typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
    PSECURITY_DESCRIPTOR pSecurityDescriptor,
    PSID *pGroup,
    LPBOOL lpbGroupDefaulted);
typedef BOOL (WINAPI * IsValidSid_Proc) (
    PSID sid);
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
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,
    DWORD * lpMinimumWorkingSetSize,
    DWORD * lpMaximumWorkingSetSize);
typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
    LPMEMORYSTATUS lpBuffer);
typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
283
    LPMEMORY_STATUS_EX lpBuffer);
284 285 286 287 288 289 290 291 292
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);
293 294 295 296 297 298
typedef void (WINAPI * GetNativeSystemInfo_Proc) (
    LPSYSTEM_INFO lpSystemInfo);
typedef BOOL (WINAPI * GetSystemTimes_Proc) (
    LPFILETIME lpIdleTime,
    LPFILETIME lpKernelTime,
    LPFILETIME lpUserTime);
299

300
  /* ** A utility function ** */
Kim F. Storm's avatar
Kim F. Storm committed
301
static BOOL
302
is_windows_9x (void)
303
{
304
  static BOOL s_b_ret = 0;
305
  OSVERSIONINFO os_ver;
306
  if (g_b_init_is_windows_9x == 0)
307
    {
308
      g_b_init_is_windows_9x = 1;
309 310
      ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
      os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
311 312 313 314
      if (GetVersionEx (&os_ver))
        {
          s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
        }
315
    }
316
  return s_b_ret;
317 318
}

319 320 321 322
/* Get total user and system times for get-internal-run-time.
   Returns a list of three integers if the times are provided by the OS
   (NT derivatives), otherwise it returns the result of current-time. */
Lisp_Object
323
w32_get_internal_run_time (void)
324 325 326 327
{
  if (get_process_times_fn)
    {
      FILETIME create, exit, kernel, user;
328
      HANDLE proc = GetCurrentProcess ();
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
      if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
        {
          LARGE_INTEGER user_int, kernel_int, total;
          int microseconds;
          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;
          /* FILETIME is 100 nanosecond increments, Emacs only wants
             microsecond resolution.  */
          total.QuadPart /= 10;
          microseconds = total.QuadPart % 1000000;
          total.QuadPart /= 1000000;

          /* Sanity check to make sure we can represent the result.  */
          if (total.HighPart == 0)
            {
              int secs = total.LowPart;

              return list3 (make_number ((secs >> 16) & 0xffff),
                            make_number (secs & 0xffff),
                            make_number (microseconds));
            }
        }
    }

  return Fcurrent_time ();
}

359 360
  /* ** The wrapper functions ** */

361 362 363 364
static BOOL WINAPI
open_process_token (HANDLE ProcessHandle,
		    DWORD DesiredAccess,
		    PHANDLE TokenHandle)
365
{
366
  static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
367 368 369 370 371
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
372 373 374 375 376 377 378 379
  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)
380 381 382 383
    {
      return FALSE;
    }
  return (
384
      s_pfn_Open_Process_Token (
385 386 387 388 389 390
          ProcessHandle,
          DesiredAccess,
          TokenHandle)
      );
}

391 392 393 394 395 396
static BOOL WINAPI
get_token_information (HANDLE TokenHandle,
		       TOKEN_INFORMATION_CLASS TokenInformationClass,
		       LPVOID TokenInformation,
		       DWORD TokenInformationLength,
		       PDWORD ReturnLength)
397
{
398
  static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
399 400 401 402 403
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
404 405 406 407 408 409 410 411
  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)
412 413 414 415
    {
      return FALSE;
    }
  return (
416
      s_pfn_Get_Token_Information (
417 418 419 420 421 422 423 424
          TokenHandle,
          TokenInformationClass,
          TokenInformation,
          TokenInformationLength,
          ReturnLength)
      );
}

425 426 427 428 429 430 431 432
static BOOL WINAPI
lookup_account_sid (LPCTSTR lpSystemName,
		    PSID Sid,
		    LPTSTR Name,
		    LPDWORD cbName,
		    LPTSTR DomainName,
		    LPDWORD cbDomainName,
		    PSID_NAME_USE peUse)
433
{
434
  static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
435 436 437 438 439
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
440 441 442 443 444 445 446 447
  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)
448 449 450 451
    {
      return FALSE;
    }
  return (
452
      s_pfn_Lookup_Account_Sid (
453 454 455 456 457 458 459 460 461 462
          lpSystemName,
          Sid,
          Name,
          cbName,
          DomainName,
          cbDomainName,
          peUse)
      );
}

463 464
static PDWORD WINAPI
get_sid_sub_authority (PSID pSid, DWORD n)
465 466
{
  static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
467
  static DWORD zero = 0U;
468 469 470
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
471
      return &zero;
472 473 474 475 476 477 478 479 480 481 482
    }
  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)
    {
483
      return &zero;
484 485 486 487
    }
  return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
}

488 489
static PUCHAR WINAPI
get_sid_sub_authority_count (PSID pSid)
490 491
{
  static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
492
  static UCHAR zero = 0U;
493 494 495
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
496
      return &zero;
497 498 499 500 501 502 503 504 505 506 507
    }
  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)
    {
508
      return &zero;
509 510 511 512
    }
  return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
}

513 514 515 516 517 518
static BOOL WINAPI
get_file_security (LPCTSTR lpFileName,
		   SECURITY_INFORMATION RequestedInformation,
		   PSECURITY_DESCRIPTOR pSecurityDescriptor,
		   DWORD nLength,
		   LPDWORD lpnLengthNeeded)
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
{
  static GetFileSecurity_Proc s_pfn_Get_File_Security = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      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)
    {
      return FALSE;
    }
  return (s_pfn_Get_File_Security (lpFileName, RequestedInformation,
				   pSecurityDescriptor, nLength,
				   lpnLengthNeeded));
}

543 544 545 546
static BOOL WINAPI
get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
			       PSID *pOwner,
			       LPBOOL lpbOwnerDefaulted)
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
{
  static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      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)
    {
      return FALSE;
    }
  return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
					       lpbOwnerDefaulted));
}

570 571 572 573
static BOOL WINAPI
get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
			       PSID *pGroup,
			       LPBOOL lpbGroupDefaulted)
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
{
  static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      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)
    {
      return FALSE;
    }
  return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
					       lpbGroupDefaulted));
}

597 598
static BOOL WINAPI
is_valid_sid (PSID sid)
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
{
  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));
}

621 622
static BOOL WINAPI
equal_sid (PSID sid1, PSID sid2)
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
{
  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));
}

645 646
static DWORD WINAPI
get_length_sid (PSID sid)
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
{
  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));
}

669 670
static BOOL WINAPI
copy_sid (DWORD destlen, PSID dest, PSID src)
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
{
  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));
}

693 694 695 696 697 698
/*
  END: Wrapper functions around OpenProcessToken
  and other functions in advapi32.dll that are only
  supported in Windows NT / 2k / XP
*/

699 700
static void WINAPI
get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
{
  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;
}

719 720 721 722
static BOOL WINAPI
get_system_times (LPFILETIME lpIdleTime,
		  LPFILETIME lpKernelTime,
		  LPFILETIME lpUserTime)
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
{
  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));
}
Andrew Innes's avatar
Andrew Innes committed
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758

/* Equivalent of strerror for W32 error codes.  */
char *
w32_strerror (int error_no)
{
  static char buf[500];

  if (error_no == 0)
    error_no = GetLastError ();

  buf[0] = '\0';
  if (!FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL,
		      error_no,
		      0, /* choose most suitable language */
		      buf, sizeof (buf), NULL))
    sprintf (buf, "w32 error %u", error_no);
  return buf;
}

759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
/* 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
781
static char startup_dir[MAXPATHLEN];
782

Richard M. Stallman's avatar
Richard M. Stallman committed
783
/* Get the current working directory.  */
784
char *
Richard M. Stallman's avatar
Richard M. Stallman committed
785 786
getwd (char *dir)
{
Geoff Voelker's avatar
Geoff Voelker committed
787
#if 0
788 789 790
  if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
    return dir;
  return NULL;
Geoff Voelker's avatar
Geoff Voelker committed
791 792 793 794 795 796 797
#else
  /* Emacs doesn't actually change directory itself, and we want to
     force our real wd to be where emacs.exe is to avoid unnecessary
     conflicts when trying to rename or delete directories.  */
  strcpy (dir, startup_dir);
  return dir;
#endif
Richard M. Stallman's avatar
Richard M. Stallman committed
798 799 800
}

/* Emulate getloadavg.  */
801 802 803 804 805 806 807 808 809 810 811 812 813 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 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917

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
918 919 920
int
getloadavg (double loadavg[], int nelem)
{
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
  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
944

945
  for (elem = 0; elem < nelem; elem++)
Richard M. Stallman's avatar
Richard M. Stallman committed
946
    {
947 948 949 950 951
      double avg = getavg (elem);

      if (avg < 0)
	break;
      loadavg[elem] = avg;
Richard M. Stallman's avatar
Richard M. Stallman committed
952
    }
953 954

  return elem;
Richard M. Stallman's avatar
Richard M. Stallman committed
955 956
}

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

Geoff Voelker's avatar
Geoff Voelker committed
959 960
#define PASSWD_FIELD_SIZE 256

961 962 963 964 965
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
966

967
static struct passwd dflt_passwd =
Richard M. Stallman's avatar
Richard M. Stallman committed
968
{
969 970
  dflt_passwd_name,
  dflt_passwd_passwd,
Richard M. Stallman's avatar
Richard M. Stallman committed
971 972 973
  0,
  0,
  0,
974 975 976
  dflt_passwd_gecos,
  dflt_passwd_dir,
  dflt_passwd_shell,
Richard M. Stallman's avatar
Richard M. Stallman committed
977 978
};

979 980 981
static char dflt_group_name[GNLEN+1];

static struct group dflt_group =
Lars Hansen's avatar
Lars Hansen committed
982
{
983 984 985 986
  /* 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
987 988
};

989
unsigned
990
getuid (void)
991
{
992
  return dflt_passwd.pw_uid;
993 994
}

995
unsigned
996
geteuid (void)
997
{
998 999 1000
  /* 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.  */
1001
  return getuid ();
1002 1003
}

1004
unsigned
1005
getgid (void)
1006
{
1007
  return dflt_passwd.pw_gid;
1008 1009
}

1010
unsigned
1011
getegid (void)
1012
{
1013 1014 1015
  return getgid ();
}

Richard M. Stallman's avatar
Richard M. Stallman committed
1016
struct passwd *
1017
getpwuid (unsigned uid)
Richard M. Stallman's avatar
Richard M. Stallman committed
1018
{
1019 1020
  if (uid == dflt_passwd.pw_uid)
    return &dflt_passwd;
1021
  return NULL;
Richard M. Stallman's avatar
Richard M. Stallman committed
1022 1023
}

Lars Hansen's avatar
Lars Hansen committed
1024 1025 1026
struct group *
getgrgid (gid_t gid)
{
1027
  return &dflt_group;
Lars Hansen's avatar
Lars Hansen committed
1028 1029
}

Richard M. Stallman's avatar
Richard M. Stallman committed
1030 1031 1032 1033
struct passwd *
getpwnam (char *name)
{
  struct passwd *pw;
1034

Richard M. Stallman's avatar
Richard M. Stallman committed
1035 1036 1037 1038
  pw = getpwuid (getuid ());
  if (!pw)
    return pw;

1039
  if (xstrcasecmp (name, pw->pw_name))
Richard M. Stallman's avatar
Richard M. Stallman committed
1040 1041 1042 1043 1044
    return NULL;

  return pw;
}

1045
static void
1046
init_user_info (void)
Richard M. Stallman's avatar
Richard M. Stallman committed
1047
{
1048 1049 1050 1051 1052 1053 1054
  /* 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). */

1055
  char         uname[UNLEN+1], gname[GNLEN+1], domain[1025];
1056
  DWORD        ulength = sizeof (uname), dlength = sizeof (domain), needed;
1057
  DWORD	       glength = sizeof (gname);
1058 1059
  HANDLE       token = NULL;
  SID_NAME_USE user_type;
1060 1061
  unsigned char *buf = NULL;
  DWORD        blen = 0;
1062 1063
  TOKEN_USER   user_token;
  TOKEN_PRIMARY_GROUP group_token;
1064
  BOOL         result;
1065

1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
  result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
  if (result)
    {
      result = get_token_information (token, TokenUser, NULL, 0, &blen);
      if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
	{
	  buf = xmalloc (blen);
	  result = get_token_information (token, TokenUser,
					  (LPVOID)buf, blen, &needed);
	  if (result)
	    {
	      memcpy (&user_token, buf, sizeof (user_token));
	      result = lookup_account_sid (NULL, user_token.User.Sid,
					   uname, &ulength,
					   domain, &dlength, &user_type);
	    }
	}
      else
	result = FALSE;
    }
  if (result)
Richard M. Stallman's avatar
Richard M. Stallman committed
1087
    {
1088
      strcpy (dflt_passwd.pw_name, uname);
1089
      /* Determine a reasonable uid value.  */
1090
      if (xstrcasecmp ("administrator", uname) == 0)
1091
	{
1092 1093
	  dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
	  dflt_passwd.pw_gid = 513; /* well-known None gid */
1094 1095 1096
	}
      else
	{
1097 1098
	  /* Use the last sub-authority value of the RID, the relative
	     portion of the SID, as user/group ID. */
1099
	  dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
1100

1101
	  /* Get group id and name.  */
1102 1103 1104 1105 1106 1107 1108 1109 1110
	  result = get_token_information (token, TokenPrimaryGroup,
					  (LPVOID)buf, blen, &needed);
	  if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
	    {
	      buf = xrealloc (buf, blen = needed);
	      result = get_token_information (token, TokenPrimaryGroup,
					      (LPVOID)buf, blen, &needed);
	    }
	  if (result)
1111
	    {
1112
	      memcpy (&group_token, buf, sizeof (group_token));
1113
	      dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
1114
	      dlength = sizeof (domain);
1115 1116 1117
	      /* If we can get at the real Primary Group name, use that.
		 Otherwise, the default group name was already set to
		 "None" in globals_of_w32.  */
1118 1119 1120 1121
	      if (lookup_account_sid (NULL, group_token.PrimaryGroup,
				      gname, &glength, NULL, &dlength,
				      &user_type))
		strcpy (dflt_group_name, gname);
1122 1123
	    }
	  else
1124
	    dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1125 1126 1127
	}
    }
  /* If security calls are not supported (presumably because we
1128
     are running under Windows 9X), fallback to this: */
1129
  else if (GetUserName (uname, &ulength))
1130
    {
1131
      strcpy (dflt_passwd.pw_name, uname);
1132
      if (xstrcasecmp ("administrator", uname) == 0)
1133
	dflt_passwd.pw_uid = 0;
1134
      else
1135 1136
	dflt_passwd.pw_uid = 123;
      dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1137 1138 1139
    }
  else
    {
1140 1141 1142
      strcpy (dflt_passwd.pw_name, "unknown");
      dflt_passwd.pw_uid = 123;
      dflt_passwd.pw_gid = 123;
Richard M. Stallman's avatar
Richard M. Stallman committed
1143
    }
1144
  dflt_group.gr_gid = dflt_passwd.pw_gid;
Richard M. Stallman's avatar
Richard M. Stallman committed
1145

1146 1147
  /* Ensure HOME and SHELL are defined. */
  if (getenv ("HOME") == NULL)
1148
    abort ();
1149
  if (getenv ("SHELL") == NULL)
1150
    abort ();
Richard M. Stallman's avatar
Richard M. Stallman committed
1151

1152
  /* Set dir and shell from environment variables. */
1153 1154
  strcpy (dflt_passwd.pw_dir, getenv ("HOME"));
  strcpy (dflt_passwd.pw_shell, getenv ("SHELL"));
1155

1156
  xfree (buf);
1157 1158
  if (token)
    CloseHandle (token);
Richard M. Stallman's avatar
Richard M. Stallman committed
1159 1160 1161
}

int
1162
random (void)
Richard M. Stallman's avatar
Richard M. Stallman committed
1163
{
1164 1165
  /* rand () on NT gives us 15 random bits...hack together 30 bits.  */
  return ((rand () << 15) | rand ());
Richard M. Stallman's avatar
Richard M. Stallman committed
1166 1167 1168
}

void
1169
srandom (int seed)
Richard M. Stallman's avatar
Richard M. Stallman committed
1170
{
1171
  srand (seed);
Richard M. Stallman's avatar
Richard M. Stallman committed
1172 1173
}

Geoff Voelker's avatar
Geoff Voelker committed
1174

1175 1176 1177 1178 1179
/* Normalize filename by converting all path separators to
   the specified separator.  Also conditionally convert upper
   case path name components to lower case.  */

static void
1180
normalize_filename (register char *fp, char path_sep)
1181 1182 1183 1184
{
  char sep;
  char *elem;

1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
  /* Always lower-case drive letters a-z, even if the filesystem
     preserves case in filenames.
     This is so filenames can be compared by string comparison
     functions that are case-sensitive.  Even case-preserving filesystems
     do not distinguish case in drive letters.  */
  if (fp[1] == ':' && *fp >= 'A' && *fp <= 'Z')
    {
      *fp += 'a' - 'A';
      fp += 2;
    }

1196
  if (NILP (Vw32_downcase_file_names))
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
    {
      while (*fp)
	{
	  if (*fp == '/' || *fp == '\\')
	    *fp = path_sep;
	  fp++;
	}
      return;
    }

  sep = path_sep;		/* convert to this path separator */
  elem = fp;			/* start of current path element */

  do {
    if (*fp >= 'a' && *fp <= 'z')
      elem = 0;			/* don't convert this element */

    if (*fp == 0 || *fp == ':')
      {
	sep = *fp;		/* restore current separator (or 0) */
	*fp = '/';		/* after conversion of this element */
      }

    if (*fp == '/' || *fp == '\\')
      {
	if (elem && elem != fp)
	  {
	    *fp = 0;		/* temporary end of string */
	    _strlwr (elem);	/* while we convert to lower case */
	  }
	*fp = sep;		/* convert (or restore) path separator */
	elem = fp + 1;		/* next element starts after separator */
	sep = path_sep;
      }
  } while (*fp++);
}

1234
/* Destructively turn backslashes into slashes.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
1235
void
1236
dostounix_filename (register char *p)
Richard M. Stallman's avatar
Richard M. Stallman committed
1237
{
1238
  normalize_filename (p, '/');
Richard M. Stallman's avatar
Richard M. Stallman committed
1239 1240
}

1241
/* Destructively turn slashes into backslashes.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
1242
void
1243
unixtodos_filename (register char *p)
Richard M. Stallman's avatar
Richard M. Stallman committed
1244
{
1245
  normalize_filename (p, '\\');
Richard M. Stallman's avatar
Richard M. Stallman committed
1246 1247
}

1248 1249 1250
/* Remove all CR's that are followed by a LF.
   (From msdos.c...probably should figure out a way to share it,
   although this code isn't going to ever change.)  */
1251
static int
1252
crlf_to_lf (register int n, register unsigned char *buf)
Karl Heuer's avatar
Karl Heuer committed
1253
{
1254 1255 1256
  unsigned char *np = buf;
  unsigned char *startp = buf;
  unsigned char *endp = buf + n;
Karl Heuer's avatar
Karl Heuer committed
1257

1258 1259 1260
  if (n == 0)
    return n;
  while (buf < endp - 1)
Richard M. Stallman's avatar
Richard M. Stallman committed
1261
    {
1262 1263 1264 1265 1266 1267 1268
      if (*buf == 0x0d)
	{
	  if (*(++buf) != 0x0a)
	    *np++ = 0x0d;
	}
      else
	*np++ = *buf++;
Richard M. Stallman's avatar
Richard M. Stallman committed
1269
    }
1270 1271 1272
  if (buf < endp)
    *np++ = *buf++;
  return np - startp;
Richard M. Stallman's avatar
Richard M. Stallman committed
1273 1274
}

Geoff Voelker's avatar
Geoff Voelker committed
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
/* Parse the root part of file name, if present.  Return length and
    optionally store pointer to char after root.  */
static int
parse_root (char * name, char ** pPath)
{
  char * start = name;

  if (name == NULL)
    return 0;

  /* find the root name of the volume if given */
  if (isalpha (name[0]) && name[1] == ':')
    {
      /* skip past drive specifier */
      name += 2;
      if (IS_DIRECTORY_SEP (name[0]))
	name++;
    }
  else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
    {
      int slashes = 2;
      name += 2;
      do
        {
	  if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
	    break;
	  name++;
	}
      while ( *name );
      if (IS_DIRECTORY_SEP (name[0]))
	name++;
    }

  if (pPath)
    *pPath = name;

  return name - start;