platform_utils_win32.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #
  2. # Copyright (C) 2016 The Android Open Source Project
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import errno
  16. from ctypes import WinDLL, get_last_error, FormatError, WinError
  17. from ctypes.wintypes import BOOL, LPCWSTR, DWORD
  18. kernel32 = WinDLL('kernel32', use_last_error=True)
  19. # Win32 error codes
  20. ERROR_SUCCESS = 0
  21. ERROR_PRIVILEGE_NOT_HELD = 1314
  22. # Win32 API entry points
  23. CreateSymbolicLinkW = kernel32.CreateSymbolicLinkW
  24. CreateSymbolicLinkW.restype = BOOL
  25. CreateSymbolicLinkW.argtypes = (LPCWSTR, # lpSymlinkFileName In
  26. LPCWSTR, # lpTargetFileName In
  27. DWORD) # dwFlags In
  28. # Symbolic link creation flags
  29. SYMBOLIC_LINK_FLAG_FILE = 0x00
  30. SYMBOLIC_LINK_FLAG_DIRECTORY = 0x01
  31. def create_filesymlink(source, link_name):
  32. """Creates a Windows file symbolic link source pointing to link_name."""
  33. _create_symlink(source, link_name, SYMBOLIC_LINK_FLAG_FILE)
  34. def create_dirsymlink(source, link_name):
  35. """Creates a Windows directory symbolic link source pointing to link_name.
  36. """
  37. _create_symlink(source, link_name, SYMBOLIC_LINK_FLAG_DIRECTORY)
  38. def _create_symlink(source, link_name, dwFlags):
  39. # Note: Win32 documentation for CreateSymbolicLink is incorrect.
  40. # On success, the function returns "1".
  41. # On error, the function returns some random value (e.g. 1280).
  42. # The best bet seems to use "GetLastError" and check for error/success.
  43. CreateSymbolicLinkW(link_name, source, dwFlags)
  44. code = get_last_error()
  45. if code != ERROR_SUCCESS:
  46. error_desc = FormatError(code).strip()
  47. if code == ERROR_PRIVILEGE_NOT_HELD:
  48. raise OSError(errno.EPERM, error_desc, link_name)
  49. error_desc = 'Error creating symbolic link %s: %s'.format(
  50. link_name, error_desc)
  51. raise WinError(code, error_desc)