winmanifest.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2013-2023, PyInstaller Development Team.
  3. #
  4. # Distributed under the terms of the GNU General Public License (version 2
  5. # or later) with exception for distributing the bootloader.
  6. #
  7. # The full license is in the file COPYING.txt, distributed with this software.
  8. #
  9. # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
  10. #-----------------------------------------------------------------------------
  11. import xml.dom
  12. import xml.dom.minidom
  13. #- Relevant constants from Windows headers
  14. # Manifest resource code
  15. RT_MANIFEST = 24
  16. # Resource IDs (names) for manifest.
  17. # See: https://www.gamedev.net/blogs/entry/2154553-manifest-embedding-and-activation
  18. CREATEPROCESS_MANIFEST_RESOURCE_ID = 1
  19. ISOLATIONAWARE_MANIFEST_RESOURCE_ID = 2
  20. LANG_NEUTRAL = 0
  21. #- Default application manifest template, based on the one found in python executable.
  22. _DEFAULT_MANIFEST_XML = \
  23. b"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  24. <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  25. <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
  26. <security>
  27. <requestedPrivileges>
  28. <requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel>
  29. </requestedPrivileges>
  30. </security>
  31. </trustInfo>
  32. <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
  33. <application>
  34. <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"></supportedOS>
  35. <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"></supportedOS>
  36. <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"></supportedOS>
  37. <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"></supportedOS>
  38. <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"></supportedOS>
  39. </application>
  40. </compatibility>
  41. <application xmlns="urn:schemas-microsoft-com:asm.v3">
  42. <windowsSettings>
  43. <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
  44. </windowsSettings>
  45. </application>
  46. <dependency>
  47. <dependentAssembly>
  48. <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"></assemblyIdentity>
  49. </dependentAssembly>
  50. </dependency>
  51. </assembly>
  52. """ # noqa: E122,E501
  53. #- DOM navigation helpers
  54. def _find_elements_by_tag(root, tag):
  55. """
  56. Find all elements with given tag under the given root element.
  57. """
  58. return [node for node in root.childNodes if node.nodeType == xml.dom.Node.ELEMENT_NODE and node.tagName == tag]
  59. def _find_element_by_tag(root, tag):
  60. """
  61. Attempt to find a single element with given tag under the given root element, and return None if no such element
  62. is found. Raises an error if multiple elements are found.
  63. """
  64. elements = _find_elements_by_tag(root, tag)
  65. if len(elements) > 1:
  66. raise ValueError(f"Expected a single {tag!r} element, found {len(elements)} element(s)!")
  67. if not elements:
  68. return None
  69. return elements[0]
  70. #- Application manifest modification helpers
  71. def _set_execution_level(manifest_dom, root_element, uac_admin=False, uac_uiaccess=False):
  72. """
  73. Find <security> -> <requestedPrivileges> -> <requestedExecutionLevel> element, and set its `level` and `uiAccess`
  74. attributes based on supplied arguments. Create the XML elements if necessary, as they are optional.
  75. """
  76. # <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
  77. trust_info_element = _find_element_by_tag(root_element, "trustInfo")
  78. if not trust_info_element:
  79. trust_info_element = manifest_dom.createElement("trustInfo")
  80. trust_info_element.setAttribute("xmlns", "urn:schemas-microsoft-com:asm.v3")
  81. root_element.appendChild(trust_info_element)
  82. # <security>
  83. security_element = _find_element_by_tag(trust_info_element, "security")
  84. if not security_element:
  85. security_element = manifest_dom.createElement("security")
  86. trust_info_element.appendChild(security_element)
  87. # <requestedPrivileges>
  88. requested_privileges_element = _find_element_by_tag(security_element, "requestedPrivileges")
  89. if not requested_privileges_element:
  90. requested_privileges_element = manifest_dom.createElement("requestedPrivileges")
  91. security_element.appendChild(requested_privileges_element)
  92. # <requestedExecutionLevel>
  93. requested_execution_level_element = _find_element_by_tag(requested_privileges_element, "requestedExecutionLevel")
  94. if not requested_execution_level_element:
  95. requested_execution_level_element = manifest_dom.createElement("requestedExecutionLevel")
  96. requested_privileges_element.appendChild(requested_execution_level_element)
  97. requested_execution_level_element.setAttribute("level", "requireAdministrator" if uac_admin else "asInvoker")
  98. requested_execution_level_element.setAttribute("uiAccess", "true" if uac_uiaccess else "false")
  99. def _ensure_common_controls_dependency(manifest_dom, root_element):
  100. """
  101. Scan <dependency> elements for the one whose <<dependentAssembly> -> <assemblyIdentity> corresponds to the
  102. `Microsoft.Windows.Common-Controls`. If found, overwrite its properties. If not, create new <dependency>
  103. element with corresponding sub-elements and attributes.
  104. """
  105. # <dependency>
  106. dependency_elements = _find_elements_by_tag(root_element, "dependency")
  107. for dependency_element in dependency_elements:
  108. # <dependentAssembly>
  109. dependent_assembly_element = _find_element_by_tag(dependency_element, "dependentAssembly")
  110. # <assemblyIdentity>
  111. assembly_identity_element = _find_element_by_tag(dependent_assembly_element, "assemblyIdentity")
  112. # Check the name attribute
  113. if assembly_identity_element.attributes["name"].value == "Microsoft.Windows.Common-Controls":
  114. common_controls_element = assembly_identity_element
  115. break
  116. else:
  117. # Create <dependency>
  118. dependency_element = manifest_dom.createElement("dependency")
  119. root_element.appendChild(dependency_element)
  120. # Create <dependentAssembly>
  121. dependent_assembly_element = manifest_dom.createElement("dependentAssembly")
  122. dependency_element.appendChild(dependent_assembly_element)
  123. # Create <assemblyIdentity>
  124. common_controls_element = manifest_dom.createElement("assemblyIdentity")
  125. dependent_assembly_element.appendChild(common_controls_element)
  126. common_controls_element.setAttribute("type", "win32")
  127. common_controls_element.setAttribute("name", "Microsoft.Windows.Common-Controls")
  128. common_controls_element.setAttribute("version", "6.0.0.0")
  129. common_controls_element.setAttribute("processorArchitecture", "*")
  130. common_controls_element.setAttribute("publicKeyToken", "6595b64144ccf1df")
  131. common_controls_element.setAttribute("language", "*")
  132. def create_application_manifest(manifest_xml=None, uac_admin=False, uac_uiaccess=False):
  133. """
  134. Create application manifest, from built-in or custom manifest XML template. If provided, `manifest_xml` must be
  135. a string or byte string containing XML source. The returned manifest is a byte string, encoded in UTF-8.
  136. This function sets the attributes of `requestedExecutionLevel` based on provided `uac_admin` and `auc_uiacces`
  137. arguments (creating the parent elements in the XML, if necessary). It also scans `dependency` elements for the
  138. entry corresponding to `Microsoft.Windows.Common-Controls` and creates or modifies it as necessary.
  139. """
  140. if manifest_xml is None:
  141. manifest_xml = _DEFAULT_MANIFEST_XML
  142. with xml.dom.minidom.parseString(manifest_xml) as manifest_dom:
  143. root_element = manifest_dom.documentElement
  144. # Validate root element - must be <assembly>
  145. assert root_element.tagName == "assembly"
  146. assert root_element.namespaceURI == "urn:schemas-microsoft-com:asm.v1"
  147. assert root_element.attributes["manifestVersion"].value == "1.0"
  148. # Modify the manifest
  149. _set_execution_level(manifest_dom, root_element, uac_admin, uac_uiaccess)
  150. _ensure_common_controls_dependency(manifest_dom, root_element)
  151. # Create output XML
  152. output = manifest_dom.toprettyxml(indent=" ", encoding="UTF-8")
  153. # Strip extra newlines
  154. output = [line for line in output.splitlines() if line.strip()]
  155. # Replace: `<?xml version="1.0" encoding="UTF-8"?>` with `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>`.
  156. # Support for `standalone` was added to `toprettyxml` in python 3.9, so do a manual work around.
  157. output[0] = b"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>"""
  158. output = b"\n".join(output)
  159. return output
  160. def write_manifest_to_executable(filename, manifest_xml):
  161. """
  162. Write the given manifest XML to the given executable's RT_MANIFEST resource.
  163. """
  164. from PyInstaller.utils.win32 import winresource
  165. # CREATEPROCESS_MANIFEST_RESOURCE_ID is used for manifest resource in executables.
  166. # ISOLATIONAWARE_MANIFEST_RESOURCE_ID is used for manifest resources in DLLs.
  167. names = [CREATEPROCESS_MANIFEST_RESOURCE_ID]
  168. # Ensure LANG_NEUTRAL is updated, and also update any other present languages.
  169. languages = [LANG_NEUTRAL, "*"]
  170. winresource.add_or_update_resource(filename, manifest_xml, RT_MANIFEST, names, languages)
  171. def read_manifest_from_executable(filename):
  172. """
  173. Read manifest from the given executable."
  174. """
  175. from PyInstaller.utils.win32 import winresource
  176. resources = winresource.get_resources(filename, [RT_MANIFEST])
  177. # `resources` is a three-level dictionary:
  178. # - level 1: resource type (RT_MANIFEST)
  179. # - level 2: resource name (CREATEPROCESS_MANIFEST_RESOURCE_ID)
  180. # - level 3: resource language (LANG_NEUTRAL)
  181. # Level 1
  182. if RT_MANIFEST not in resources:
  183. raise ValueError(f"No RT_MANIFEST resources found in {filename!r}.")
  184. resources = resources[RT_MANIFEST]
  185. # Level 2
  186. if CREATEPROCESS_MANIFEST_RESOURCE_ID not in resources:
  187. raise ValueError(f"No RT_MANIFEST resource named CREATEPROCESS_MANIFEST_RESOURCE_ID found in {filename!r}.")
  188. resources = resources[CREATEPROCESS_MANIFEST_RESOURCE_ID]
  189. # Level 3
  190. # We prefer LANG_NEUTRAL, but allow fall back to the first available entry.
  191. if LANG_NEUTRAL in resources:
  192. resources = resources[LANG_NEUTRAL]
  193. else:
  194. resources = next(iter(resources.items()))
  195. manifest_xml = resources
  196. return manifest_xml