1
# Copyright (C) 2005-2010 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Win32-specific helper functions
19
Only one dependency: ctypes should be installed.
30
from breezy.i18n import gettext
33
# Special Win32 API constants
34
# Handles of std streams
35
WIN32_STDIN_HANDLE = -10
36
WIN32_STDOUT_HANDLE = -11
37
WIN32_STDERR_HANDLE = -12
39
# CSIDL constants (from MSDN 2003)
40
CSIDL_APPDATA = 0x001A # Application Data folder
41
# <user name>\Local Settings\Application Data (non roaming)
42
CSIDL_LOCAL_APPDATA = 0x001c
43
CSIDL_PERSONAL = 0x0005 # My Documents folder
45
# from winapi C headers
48
MAX_COMPUTERNAME_LENGTH = 31
50
# Registry data type ids
55
def debug_memory_win32api(message='', short=True):
56
"""Use trace.note() to dump the running memory info."""
58
from breezy import trace
59
class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
60
"""Used by GetProcessMemoryInfo"""
61
_fields_ = [('cb', ctypes.c_ulong),
62
('PageFaultCount', ctypes.c_ulong),
63
('PeakWorkingSetSize', ctypes.c_size_t),
64
('WorkingSetSize', ctypes.c_size_t),
65
('QuotaPeakPagedPoolUsage', ctypes.c_size_t),
66
('QuotaPagedPoolUsage', ctypes.c_size_t),
67
('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t),
68
('QuotaNonPagedPoolUsage', ctypes.c_size_t),
69
('PagefileUsage', ctypes.c_size_t),
70
('PeakPagefileUsage', ctypes.c_size_t),
71
('PrivateUsage', ctypes.c_size_t),
73
cur_process = ctypes.windll.kernel32.GetCurrentProcess()
74
mem_struct = PROCESS_MEMORY_COUNTERS_EX()
75
ret = ctypes.windll.psapi.GetProcessMemoryInfo(
76
cur_process, ctypes.byref(mem_struct), ctypes.sizeof(mem_struct))
78
trace.note(gettext('Failed to GetProcessMemoryInfo()'))
80
info = {'PageFaultCount': mem_struct.PageFaultCount,
81
'PeakWorkingSetSize': mem_struct.PeakWorkingSetSize,
82
'WorkingSetSize': mem_struct.WorkingSetSize,
83
'QuotaPeakPagedPoolUsage': mem_struct.QuotaPeakPagedPoolUsage,
84
'QuotaPagedPoolUsage': mem_struct.QuotaPagedPoolUsage,
85
'QuotaPeakNonPagedPoolUsage':
86
mem_struct.QuotaPeakNonPagedPoolUsage,
87
'QuotaNonPagedPoolUsage': mem_struct.QuotaNonPagedPoolUsage,
88
'PagefileUsage': mem_struct.PagefileUsage,
89
'PeakPagefileUsage': mem_struct.PeakPagefileUsage,
90
'PrivateUsage': mem_struct.PrivateUsage,
93
# using base-2 units (see HACKING.txt).
94
trace.note(gettext('WorkingSize {0:>7}KiB'
95
'\tPeakWorking {1:>7}KiB\t{2}').format(
96
info['WorkingSetSize'] / 1024,
97
info['PeakWorkingSetSize'] / 1024,
101
trace.note('%s', message)
102
trace.note(gettext('WorkingSize %8d KiB'),
103
info['WorkingSetSize'] / 1024)
104
trace.note(gettext('PeakWorking %8d KiB'),
105
info['PeakWorkingSetSize'] / 1024)
106
trace.note(gettext('PagefileUsage %8d KiB'),
107
info.get('PagefileUsage', 0) / 1024)
108
trace.note(gettext('PeakPagefileUsage %8d KiB'),
109
info.get('PeakPagefileUsage', 0) / 1024)
110
trace.note(gettext('PrivateUsage %8d KiB'),
111
info.get('PrivateUsage', 0) / 1024)
112
trace.note(gettext('PageFaultCount %8d'), info.get('PageFaultCount', 0))
115
def get_console_size(defaultx=80, defaulty=25):
116
"""Return size of current console.
118
This function try to determine actual size of current working
119
console window and return tuple (sizex, sizey) if success,
120
or default size (defaultx, defaulty) otherwise.
123
# To avoid problem with redirecting output via pipe
124
# we need to use stderr instead of stdout
125
h = ctypes.windll.kernel32.GetStdHandle(WIN32_STDERR_HANDLE)
126
csbi = ctypes.create_string_buffer(22)
127
res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
130
(bufx, bufy, curx, cury, wattr,
131
left, top, right, bottom, maxx, maxy) = struct.unpack(
132
"hhhhHhhhhhh", csbi.raw)
133
sizex = right - left + 1
134
sizey = bottom - top + 1
135
return (sizex, sizey)
137
return (defaultx, defaulty)
140
def _get_sh_special_folder_path(csidl):
141
"""Call SHGetSpecialFolderPathW if available, or return None.
143
Result is always unicode (or None).
147
SHGetSpecialFolderPath = \
148
ctypes.windll.shell32.SHGetSpecialFolderPathW
149
except AttributeError:
152
buf = ctypes.create_unicode_buffer(MAX_PATH)
153
if SHGetSpecialFolderPath(None, buf, csidl, 0):
157
def get_appdata_location():
158
"""Return Application Data location.
159
Return None if we cannot obtain location.
161
Windows defines two 'Application Data' folders per user - a 'roaming'
162
one that moves with the user as they logon to different machines, and
163
a 'local' one that stays local to the machine. This returns the 'roaming'
164
directory, and thus is suitable for storing user-preferences, etc.
166
appdata = _get_sh_special_folder_path(CSIDL_APPDATA)
169
# Use APPDATA if defined, will return None if not
170
return os.environ.get('APPDATA')
173
def get_local_appdata_location():
174
"""Return Local Application Data location.
175
Return the same as get_appdata_location() if we cannot obtain location.
177
Windows defines two 'Application Data' folders per user - a 'roaming'
178
one that moves with the user as they logon to different machines, and
179
a 'local' one that stays local to the machine. This returns the 'local'
180
directory, and thus is suitable for caches, temp files and other things
181
which don't need to move with the user.
183
local = _get_sh_special_folder_path(CSIDL_LOCAL_APPDATA)
186
# Vista supplies LOCALAPPDATA, but XP and earlier do not.
187
local = os.environ.get('LOCALAPPDATA')
190
return get_appdata_location()
193
def get_home_location():
194
"""Return user's home location.
195
Assume on win32 it's the <My Documents> folder.
196
If location cannot be obtained return system drive root,
199
home = _get_sh_special_folder_path(CSIDL_PERSONAL)
202
home = os.environ.get('HOME')
205
homepath = os.environ.get('HOMEPATH')
206
if homepath is not None:
207
return os.path.join(os.environ.get('HOMEDIR', ''), home)
208
# at least return windows root directory
209
windir = os.environ.get('WINDIR')
211
return os.path.splitdrive(windir)[0] + '/'
212
# otherwise C:\ is good enough for 98% users
217
"""Return user name as login name.
218
If name cannot be obtained return None.
221
advapi32 = ctypes.windll.advapi32
222
GetUserName = getattr(advapi32, 'GetUserNameW')
223
except AttributeError:
226
buf = ctypes.create_unicode_buffer(UNLEN + 1)
227
n = ctypes.c_int(UNLEN + 1)
228
if GetUserName(buf, ctypes.byref(n)):
230
# otherwise try env variables
231
return os.environ.get('USERNAME')
234
# 1 == ComputerNameDnsHostname, which returns "The DNS host name of the local
235
# computer or the cluster associated with the local computer."
236
_WIN32_ComputerNameDnsHostname = 1
240
"""Return host machine name.
241
If name cannot be obtained return None.
243
:return: A unicode string representing the host name.
246
buf = ctypes.create_unicode_buffer(MAX_COMPUTERNAME_LENGTH + 1)
247
n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH + 1)
249
# Try GetComputerNameEx which gives a proper Unicode hostname
250
GetComputerNameEx = getattr(
251
ctypes.windll.kernel32, 'GetComputerNameExW', None)
252
if (GetComputerNameEx is not None
253
and GetComputerNameEx(_WIN32_ComputerNameDnsHostname,
254
buf, ctypes.byref(n))):
256
return os.environ.get('COMPUTERNAME')
259
def _ensure_with_dir(path):
260
if (not os.path.split(path)[0] or path.startswith(u'*')
261
or path.startswith(u'?')):
262
return u'./' + path, True
267
def _undo_ensure_with_dir(path, corrected):
274
def glob_one(possible_glob):
275
"""Same as glob.glob().
277
work around bugs in glob.glob()
278
- Python bug #1001604 ("glob doesn't return unicode with ...")
279
- failing expansion for */* with non-iso-8859-* chars
281
corrected_glob, corrected = _ensure_with_dir(possible_glob)
282
glob_files = glob.glob(corrected_glob)
285
# special case to let the normal code path handle
286
# files that do not exist, etc.
287
glob_files = [possible_glob]
289
glob_files = [_undo_ensure_with_dir(elem, corrected)
290
for elem in glob_files]
291
return [elem.replace(u'\\', u'/') for elem in glob_files]
294
def glob_expand(file_list):
295
"""Replacement for glob expansion by the shell.
297
Win32's cmd.exe does not do glob expansion (eg ``*.py``), so we do our own
300
:param file_list: A list of filenames which may include shell globs.
301
:return: An expanded list of filenames.
303
Introduced in breezy 0.18.
307
expanded_file_list = []
308
for possible_glob in file_list:
309
expanded_file_list.extend(glob_one(possible_glob))
310
return expanded_file_list
313
def get_app_path(appname):
314
r"""Look up in Windows registry for full path to application executable.
315
Typically, applications create subkey with their basename
316
in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\
318
:param appname: name of application (if no filename extension
319
is specified, .exe used)
320
:return: full path to aplication executable from registry,
321
or appname itself if nothing found.
326
if not os.path.splitext(basename)[1]:
327
basename = appname + '.exe'
330
hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
331
'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' +
333
except EnvironmentError:
338
path, type_id = _winreg.QueryValueEx(hkey, '')
342
_winreg.CloseKey(hkey)
344
if type_id == REG_SZ:
349
def set_file_attr_hidden(path):
350
"""Set file attributes to hidden if possible"""
351
from ctypes.wintypes import BOOL, DWORD, LPWSTR
353
# <https://docs.microsoft.com/windows/desktop/api/fileapi/nf-fileapi-setfileattributesw>
354
SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
355
SetFileAttributes.argtypes = LPWSTR, DWORD
356
SetFileAttributes.restype = BOOL
357
FILE_ATTRIBUTE_HIDDEN = 2
358
if not SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN):
359
e = ctypes.WinError()
361
trace.mutter('Unable to set hidden attribute on %r: %s', path, e)
364
def _command_line_to_argv(command_line, argv, single_quotes_allowed=False):
365
"""Convert a Unicode command line into a list of argv arguments.
367
It performs wildcard expansion to make wildcards act closer to how they
368
work in posix shells, versus how they work by default on Windows. Quoted
369
arguments are left untouched.
371
:param command_line: The unicode string to split into an arg list.
372
:param single_quotes_allowed: Whether single quotes are accepted as quoting
373
characters like double quotes. False by
375
:return: A list of unicode strings.
377
# First, split the command line
378
s = cmdline.Splitter(
379
command_line, single_quotes_allowed=single_quotes_allowed)
381
# Bug #587868 Now make sure that the length of s agrees with sys.argv
382
# we do this by simply counting the number of arguments in each. The counts should
383
# agree no matter what encoding sys.argv is in (AFAIK)
384
# len(arguments) < len(sys.argv) should be an impossibility since python gets
385
# args from the very same PEB as does GetCommandLineW
388
# Now shorten the command line we get from GetCommandLineW to match sys.argv
389
if len(arguments) < len(argv):
390
raise AssertionError("Split command line can't be shorter than argv")
391
arguments = arguments[len(arguments) - len(argv):]
393
# Carry on to process globs (metachars) in the command line
394
# expand globs if necessary
395
# TODO: Use 'globbing' instead of 'glob.glob', this gives us stuff like
398
for is_quoted, arg in arguments:
399
if is_quoted or not glob.has_magic(arg):
402
args.extend(glob_one(arg))
406
def _ctypes_is_local_pid_dead(pid):
408
kernel32 = ctypes.wintypes.windll.kernel32
409
"""True if pid doesn't correspond to live process on this machine"""
410
handle = kernel32.OpenProcess(1, False, pid)
412
errorcode = ctypes.GetLastError()
413
if errorcode == 5: # ERROR_ACCESS_DENIED
414
# Probably something alive we're not allowed to kill
416
elif errorcode == 87: # ERROR_INVALID_PARAMETER
418
raise ctypes.WinError(errorcode)
419
Kernel32.CloseHandle(handle)
422
is_local_pid_dead = _ctypes_is_local_pid_dead