Debian Codegraph @

util/winmanifest.py

raw
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2009, Florian Hoech
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, USA
18
19 # DEV NOTES
20 #
21 # Currently not implemented in the Manifest class:
22 # * Validation (only very basic sanity checks are currently in place)
23 # * comClass, typelib, comInterfaceProxyStub and windowClass child elements of
24 # the file element
25 # * comInterfaceExternalProxyStub and windowClass child elements of the
26 # assembly element
27 # * Application Configuration File and Multilanguage User Interface (MUI)
28 # support when searching for assembly files
29 #
30 # Isolated Applications and Side-by-side Assemblies:
31 # http://msdn.microsoft.com/en-us/library/dd408052%28VS.85%29.aspx
32 #
33 # Changelog:
34 # 2009-12-17 fix: small glitch in toxml / toprettyxml methods (xml declaration
35 # wasn't replaced when a different encodig than UTF-8 was used)
36 # chg: catch xml.parsers.expat.ExpatError and re-raise as
37 # ManifestXMLParseError
38 # chg: support initialize option in parse method also
39 #
40 # 2009-12-13 fix: fixed os import
41 # fix: skip invalid / empty dependent assemblies
42 #
43 # 2009-08-21 fix: Corrected assembly searching sequence for localized
44 # assemblies
45 # fix: Allow assemblies with no dependent files
46 #
47 # 2009-07-31 chg: Find private assemblies even if unversioned
48 # add: Manifest.same_id method to check if two manifests have the
49 # same assemblyIdentity
50 #
51 # 2009-07-30 fix: Potential failure in File.calc_hash method if hash
52 # algorythm not supported
53 # add: Publisher configuration (policy) support when searching for
54 # assembly files
55 # fix: Private assemblies are now actually found if present (and no
56 # shared assembly exists)
57 # add: Python 2.3 compatibility (oldest version supported by
58 # pyinstaller)
59 #
60 # 2009-07-28 chg: Code cleanup, removed a bit of redundancy
61 # add: silent mode (set silent attribute on module)
62 # chg: Do not print messages in silent mode
63 #
64 # 2009-06-18 chg: Use glob instead of regular expression in Manifest.find_files
65 #
66 # 2009-05-04 fix: Don't fail if manifest has empty description
67 # fix: Manifests created by the toxml, toprettyxml, writexml or
68 # writeprettyxml methods are now correctly recognized by
69 # Windows, which expects the XML declaration to be ordered
70 # version-encoding-standalone (standalone being optional)
71 # add: 'encoding' keyword argument in toxml, toprettyxml, writexml
72 # and writeprettyxml methods
73 # chg: UpdateManifestResourcesFromXML and
74 # UpdateManifestResourcesFromXMLFile: set resource name
75 # depending on file type ie. exe or dll
76 # fix: typo in __main__: UpdateManifestResourcesFromDataFile
77 # should have been UpdateManifestResourcesFromXMLFile
78 #
79 # 2009-03-21 First version
80
81 """
82 winmanifest.py
83
84 Create, parse and write MS Windows Manifest files.
85 Find files which are part of an assembly, by searching shared and
86 private assemblies.
87 Update or add manifest resources in Win32 PE files.
88
89 Commandline usage:
90 winmanifest.py <dstpath> <xmlpath>
91 Updates or adds manifest <xmlpath> as resource in Win32 PE file <dstpath>.
92
93 """
94
95 try:
96 import hashlib
97 except ImportError:
98 hashlib = None
99 import md5
100 import sha
101 import os
102 from glob import glob
103 import sys
104 import xml
105 from xml.dom import Node, minidom
106 from xml.dom.minidom import Document, Element
107
108 try:
109 import winresource
110 except ImportError as detail:
111 winresource = None
112 print("W:", detail)
113 print("W: Cannot check for assembly dependencies - resource access ")
114 print("W: unavailable. To enable resource access, please install ")
115 print("W: http://sourceforge.net/projects/pywin32/")
116
117 silent = False # True suppresses all messages
118
119 LANGUAGE_NEUTRAL_NT5 = "x-ww"
120 LANGUAGE_NEUTRAL_NT6 = "none"
121 RT_MANIFEST = 24
122
123 Document.aChild = Document.appendChild
124 Document.cE = Document.createElement
125 Document.cT = Document.createTextNode
126 Document.getEByTN = Document.getElementsByTagName
127 Element.aChild = Element.appendChild
128 Element.getA = Element.getAttribute
129 Element.getEByTN = Element.getElementsByTagName
130 Element.remA = Element.removeAttribute
131 Element.setA = Element.setAttribute
132
133
134 def getChildElementsByTagName(self, tagName):
135 """Return child elements of type tagName if found, else []"""
136 result = []
137 for child in self.childNodes:
138 if isinstance(child, Element):
139 if child.tagName == tagName:
140 result.append(child)
141 return result
142
143
144 def getFirstChildElementByTagName(self, tagName):
145 """Return the first element of type tagName if found, else None"""
146 for child in self.childNodes:
147 if isinstance(child, Element):
148 if child.tagName == tagName:
149 return child
150 return None
151
152
153 Document.getCEByTN = getChildElementsByTagName
154 Document.getFCEByTN = getFirstChildElementByTagName
155 Element.getCEByTN = getChildElementsByTagName
156 Element.getFCEByTN = getFirstChildElementByTagName
157
158
159 class _Hash:
160 def __init__(self):
161 self.md5 = md5.new
162 self.sha = sha.new
163
164
165 if hashlib is None:
166 hashlib = _Hash()
167
168
169 class _Dummy:
170 pass
171
172
173 if winresource:
174 _File = winresource.File
175 else:
176 _File = _Dummy
177
178
179 class File(_File):
180
181 """A file referenced by an assembly inside a manifest."""
182
183 def __init__(
184 self,
185 filename="",
186 hashalg=None,
187 hash=None,
188 comClasses=None,
189 typelibs=None,
190 comInterfaceProxyStubs=None,
191 windowClasses=None,
192 ):
193 if winresource:
194 winresource.File.__init__(self, filename)
195 else:
196 self.filename = filename
197 self.name = os.path.basename(filename)
198 if hashalg:
199 self.hashalg = hashalg.upper()
200 else:
201 self.hashalg = None
202 if (
203 os.path.isfile(filename)
204 and hashalg
205 and hashlib
206 and hasattr(hashlib, hashalg.lower())
207 ):
208 self.calc_hash()
209 else:
210 self.hash = hash
211 self.comClasses = comClasses or [] # TO-DO: implement
212 self.typelibs = typelibs or [] # TO-DO: implement
213 self.comInterfaceProxyStubs = comInterfaceProxyStubs or [] # TO-DO: implement
214 self.windowClasses = windowClasses or [] # TO-DO: implement
215
216 def calc_hash(self, hashalg=None):
217 """Calculate the hash of the file.
218
219 Will be called automatically from the constructor if the file exists
220 and hashalg is given (and supported), but may also be called manually
221 e.g. to update the hash if the file has changed.
222
223 """
224 fd = open(self.filename, "rb")
225 buf = fd.read()
226 fd.close()
227 if hashalg:
228 self.hashalg = hashalg.upper()
229 self.hash = getattr(hashlib, self.hashalg.lower())(buf).hexdigest()
230
231 def find(self, searchpath):
232 if not silent:
233 print("I: Searching for file", self.name)
234 fn = os.path.join(searchpath, self.name)
235 if os.path.isfile(fn):
236 if not silent:
237 print("I: Found file", fn)
238 return fn
239 else:
240 if not silent:
241 print("W: No such file", fn)
242 return None
243
244
245 class InvalidManifestError(Exception):
246 pass
247
248
249 class ManifestXMLParseError(InvalidManifestError):
250 pass
251
252
253 class Manifest:
254
255 # Manifests:
256 # http://msdn.microsoft.com/en-us/library/aa375365%28VS.85%29.aspx
257
258 """
259 Manifest constructor.
260
261 To build a basic manifest for your application:
262 mf = Manifest(type='win32', name='YourAppName', language='*',
263 processorArchitecture='x86', version=[1, 0, 0, 0])
264
265 To write the XML to a manifest file:
266 mf.writexml("YourAppName.exe.manifest")
267 or
268 mf.writeprettyxml("YourAppName.exe.manifest")
269
270 """
271
272 def __init__(
273 self,
274 manifestVersion=None,
275 noInheritable=False,
276 noInherit=False,
277 type_=None,
278 name=None,
279 language=None,
280 processorArchitecture=None,
281 version=None,
282 publicKeyToken=None,
283 description=None,
284 requestedExecutionLevel=None,
285 uiAccess=None,
286 dependentAssemblies=None,
287 files=None,
288 comInterfaceExternalProxyStubs=None,
289 ):
290 self.filename = None
291 self.optional = None
292 self.manifestType = "assembly"
293 self.manifestVersion = manifestVersion or [1, 0]
294 self.noInheritable = noInheritable
295 self.noInherit = noInherit
296 self.type = type_
297 self.name = name
298 self.language = language
299 self.processorArchitecture = processorArchitecture
300 self.version = version
301 self.publicKeyToken = publicKeyToken
302 # publicKeyToken:
303 # A 16-character hexadecimal string that represents the last 8 bytes
304 # of the SHA-1 hash of the public key under which the assembly is
305 # signed. The public key used to sign the catalog must be 2048 bits
306 # or greater. Required for all shared side-by-side assemblies.
307 # http://msdn.microsoft.com/en-us/library/aa375692(VS.85).aspx
308 self.applyPublisherPolicy = None
309 self.description = None
310 self.requestedExecutionLevel = requestedExecutionLevel
311 self.uiAccess = uiAccess
312 self.dependentAssemblies = dependentAssemblies or []
313 self.bindingRedirects = []
314 self.files = files or []
315 self.comInterfaceExternalProxyStubs = (
316 comInterfaceExternalProxyStubs or []
317 ) # TO-DO: implement
318
319 def add_dependent_assembly(
320 self,
321 manifestVersion=None,
322 noInheritable=False,
323 noInherit=False,
324 type_=None,
325 name=None,
326 language=None,
327 processorArchitecture=None,
328 version=None,
329 publicKeyToken=None,
330 description=None,
331 requestedExecutionLevel=None,
332 uiAccess=None,
333 dependentAssemblies=None,
334 files=None,
335 comInterfaceExternalProxyStubs=None,
336 ):
337 """Shortcut for self.dependentAssemblies.append(Manifest(*args, **kwargs))"""
338 self.dependentAssemblies.append(
339 Manifest(
340 manifestVersion,
341 noInheritable,
342 noInherit,
343 type_,
344 name,
345 language,
346 processorArchitecture,
347 version,
348 publicKeyToken,
349 description,
350 requestedExecutionLevel,
351 uiAccess,
352 dependentAssemblies,
353 files,
354 comInterfaceExternalProxyStubs,
355 )
356 )
357 if self.filename:
358 # Enable search for private assembly by assigning bogus filename
359 # (only the directory has to be correct)
360 self.dependentAssemblies[-1].filename = ":".join((self.filename, name))
361
362 def add_file(
363 self,
364 name="",
365 hashalg="",
366 hash="",
367 comClasses=None,
368 typelibs=None,
369 comInterfaceProxyStubs=None,
370 windowClasses=None,
371 ):
372 """Shortcut for manifest.files.append"""
373 self.files.append(
374 File(
375 name,
376 hashalg,
377 hash,
378 comClasses,
379 typelibs,
380 comInterfaceProxyStubs,
381 windowClasses,
382 )
383 )
384
385 def find_files(self, ignore_policies=True):
386 """Search shared and private assemblies and return a list of files.
387
388 If any files are not found, return an empty list.
389
390 IMPORTANT NOTE: For the purpose of getting the dependent assembly
391 files of an executable, the publisher configuration (aka policy)
392 should be ignored (which is the default). Setting ignore_policies=False
393 is only useful to find out which files are actually loaded at
394 runtime.
395
396 """
397
398 # Shared Assemblies:
399 # http://msdn.microsoft.com/en-us/library/aa375996%28VS.85%29.aspx
400 #
401 # Private Assemblies:
402 # http://msdn.microsoft.com/en-us/library/aa375674%28VS.85%29.aspx
403 #
404 # Assembly Searching Sequence:
405 # http://msdn.microsoft.com/en-us/library/aa374224%28VS.85%29.aspx
406 #
407 # NOTE:
408 # Multilanguage User Interface (MUI) support not yet implemented
409
410 files = []
411
412 languages = []
413 if self.language not in (None, "", "*", "neutral"):
414 languages.append(self.getlanguage())
415 if "-" in self.language:
416 # language-culture syntax, e.g. en-us
417 # Add only the language part
418 languages.append(self.language.split("-")[0])
419 if self.language not in ("en-us", "en"):
420 languages.append("en-us")
421 if self.language != "en":
422 languages.append("en")
423 languages.append(self.getlanguage("*"))
424
425 winsxs = os.path.join(os.getenv("SystemRoot"), "WinSxS")
426 if not os.path.isdir(winsxs) and not silent:
427 print("W: No such dir", winsxs)
428 manifests = os.path.join(winsxs, "Manifests")
429 if not os.path.isdir(manifests) and not silent:
430 print("W: No such dir", manifests)
431 if not ignore_policies and self.version:
432 if sys.getwindowsversion() < (6,):
433 # Windows XP
434 pcfiles = os.path.join(winsxs, "Policies")
435 if not os.path.isdir(pcfiles) and not silent:
436 print("W: No such dir", pcfiles)
437 else:
438 # Vista or later
439 pcfiles = manifests
440
441 for language in languages:
442 version = self.version
443
444 # Search for publisher configuration
445 if not ignore_policies and version:
446 # Publisher Configuration (aka policy)
447 # A publisher configuration file globally redirects
448 # applications and assemblies having a dependence on one
449 # version of a side-by-side assembly to use another version of
450 # the same assembly. This enables applications and assemblies
451 # to use the updated assembly without having to rebuild all of
452 # the affected applications.
453 # http://msdn.microsoft.com/en-us/library/aa375680%28VS.85%29.aspx
454 #
455 # Under Windows XP and 2003, policies are stored as
456 # <version>.policy files inside
457 # %SystemRoot%\WinSxS\Policies\<name>
458 # Under Vista and later, policies are stored as
459 # <name>.manifest files inside %SystemRoot%\winsxs\Manifests
460 redirected = False
461 if os.path.isdir(pcfiles):
462 if not silent:
463 print(
464 "I: Searching for publisher configuration %s..."
465 % self.getpolicyid(True, language=language)
466 )
467 if sys.getwindowsversion() < (6,):
468 # Windows XP
469 policies = os.path.join(
470 pcfiles,
471 self.getpolicyid(True, language=language) + ".policy",
472 )
473 else:
474 # Vista or later
475 policies = os.path.join(
476 pcfiles,
477 self.getpolicyid(True, language=language) + ".manifest",
478 )
479 for manifestpth in glob(policies):
480 if not os.path.isfile(manifestpth):
481 if not silent:
482 print("W: Not a file", manifestpth)
483 continue
484 if not silent:
485 print("I: Found", manifestpth)
486 try:
487 policy = ManifestFromXMLFile(manifestpth)
488 except Exception as exc:
489 print("E: Could not parse file", manifestpth)
490 print("E:", str(exc))
491 else:
492 if not silent:
493 print(
494 "I: Checking publisher policy for "
495 "binding redirects"
496 )
497 for assembly in policy.dependentAssemblies:
498 if (
499 not assembly.same_id(self, True)
500 or assembly.optional
501 ):
502 continue
503 for redirect in assembly.bindingRedirects:
504 if not silent:
505 old = "-".join(
506 [
507 ".".join([str(i) for i in part])
508 for part in redirect[0]
509 ]
510 )
511 new = ".".join([str(i) for i in redirect[1]])
512 print(
513 "I: Found redirect for version(s)",
514 old,
515 "->",
516 new,
517 )
518 if (
519 redirect[0][0] <= version <= redirect[0][-1]
520 and version != redirect[1]
521 ):
522 if not silent:
523 print(
524 "I: Applying redirect",
525 ".".join([str(i) for i in version]),
526 "->",
527 new,
528 )
529 version = redirect[1]
530 redirected = True
531 if not redirected and not silent:
532 print("I: Publisher configuration not used")
533
534 # Search for assemblies according to assembly searching sequence
535 paths = []
536 if os.path.isdir(manifests):
537 # Add winsxs search paths
538 paths.extend(
539 glob(
540 os.path.join(
541 manifests,
542 self.getid(language=language, version=version)
543 + "_*.manifest",
544 )
545 )
546 )
547 if self.filename:
548 # Add private assembly search paths
549 dirnm = os.path.dirname(self.filename)
550 if language in (LANGUAGE_NEUTRAL_NT5, LANGUAGE_NEUTRAL_NT6):
551 for ext in (".dll", ".manifest"):
552 paths.extend(glob(os.path.join(dirnm, self.name + ext)))
553 paths.extend(
554 glob(os.path.join(dirnm, self.name, self.name + ext))
555 )
556 else:
557 for ext in (".dll", ".manifest"):
558 paths.extend(
559 glob(os.path.join(dirnm, language, self.name + ext))
560 )
561 for ext in (".dll", ".manifest"):
562 paths.extend(
563 glob(
564 os.path.join(
565 dirnm, language, self.name, self.name + ext
566 )
567 )
568 )
569 if not silent:
570 print(
571 "I: Searching for assembly %s..."
572 % self.getid(language=language, version=version)
573 )
574 for manifestpth in paths:
575 if not os.path.isfile(manifestpth):
576 if not silent:
577 print("W: Not a file", manifestpth)
578 continue
579 assemblynm = os.path.basename(os.path.splitext(manifestpth)[0])
580 if not silent:
581 if manifestpth.endswith(".dll"):
582 print("I: Found manifest in", manifestpth)
583 else:
584 print("I: Found manifest", manifestpth)
585 try:
586 if manifestpth.endswith(".dll"):
587 manifest = ManifestFromResFile(manifestpth, [1])
588 else:
589 manifest = ManifestFromXMLFile(manifestpth)
590 except Exception as exc:
591 print("E: Could not parse manifest", manifestpth)
592 print("E:", exc)
593 else:
594 if manifestpth.startswith(winsxs):
595 assemblydir = os.path.join(winsxs, assemblynm)
596 if not os.path.isdir(assemblydir):
597 if not silent:
598 print("W: No such dir", assemblydir)
599 print("W: Assembly incomplete")
600 return []
601 else:
602 assemblydir = os.path.dirname(manifestpth)
603 files.append(manifestpth)
604 for file_ in self.files or manifest.files:
605 fn = file_.find(assemblydir)
606 if fn:
607 files.append(fn)
608 else:
609 # If any of our files does not exist,
610 # the assembly is incomplete
611 if not silent:
612 print("W: Assembly incomplete")
613 return []
614 return files
615
616 print("W: Assembly not found")
617 return []
618
619 def getid(self, language=None, version=None):
620 """Return an identification string which uniquely names a manifest.
621
622 This string is a combination of the manifest's processorArchitecture,
623 name, publicKeyToken, version and language.
624
625 Arguments:
626 version (tuple or list of integers) - If version is given, use it
627 instead of the manifest's
628 version.
629
630 """
631 if not self.name:
632 if not silent:
633 print("W: Assembly metadata incomplete")
634 return ""
635 id = []
636 if self.processorArchitecture:
637 id.append(self.processorArchitecture)
638 id.append(self.name)
639 if self.publicKeyToken:
640 id.append(self.publicKeyToken)
641 if version or self.version:
642 id.append(".".join([str(i) for i in version or self.version]))
643 if not language:
644 language = self.getlanguage()
645 if language:
646 id.append(language)
647 return "_".join(id)
648
649 def getlanguage(self, language=None, windowsversion=None):
650 """Get and return the manifest's language as string.
651
652 Can be either language-culture e.g. 'en-us' or a string indicating
653 language neutrality, e.g. 'x-ww' on Windows XP or 'none' on Vista
654 and later.
655
656 """
657 if not language:
658 language = self.language
659 if language in (None, "", "*", "neutral"):
660 return (LANGUAGE_NEUTRAL_NT5, LANGUAGE_NEUTRAL_NT6)[
661 (windowsversion or sys.getwindowsversion()) >= (6,)
662 ]
663 return language
664
665 def getpolicyid(self, fuzzy=True, language=None, windowsversion=None):
666 """Return an identification string which can be used to find a policy.
667
668 This string is a combination of the manifest's processorArchitecture,
669 major and minor version, name, publicKeyToken and language.
670
671 Arguments:
672 fuzzy (boolean) - If False, insert the full version in
673 the id string. Default is True (omit).
674 windowsversion - If not specified (or None), default to
675 (tuple or list of integers) sys.getwindowsversion().
676
677 """
678 if not self.name:
679 if not silent:
680 print("W: Assembly metadata incomplete")
681 return ""
682 id = []
683 if self.processorArchitecture:
684 id.append(self.processorArchitecture)
685 name = []
686 name.append("policy")
687 if self.version:
688 name.append(str(self.version[0]))
689 name.append(str(self.version[1]))
690 name.append(self.name)
691 id.append(".".join(name))
692 if self.publicKeyToken:
693 id.append(self.publicKeyToken)
694 if self.version and (windowsversion or sys.getwindowsversion()) >= (6,):
695 # Vista and later
696 if fuzzy:
697 id.append("*")
698 else:
699 id.append(".".join([str(i) for i in self.version]))
700 if not language:
701 language = self.getlanguage(windowsversion=windowsversion)
702 if language:
703 id.append(language)
704 id.append("*")
705 id = "_".join(id)
706 if self.version and (windowsversion or sys.getwindowsversion()) < (6,):
707 # Windows XP
708 if fuzzy:
709 id = os.path.join(id, "*")
710 else:
711 id = os.path.join(id, ".".join([str(i) for i in self.version]))
712 return id
713
714 def load_dom(self, domtree, initialize=True):
715 """Load manifest from DOM tree.
716
717 If initialize is True (default), reset existing attributes first.
718
719 """
720 if domtree.nodeType == Node.DOCUMENT_NODE:
721 rootElement = domtree.documentElement
722 elif domtree.nodeType == Node.ELEMENT_NODE:
723 rootElement = domtree
724 else:
725 raise InvalidManifestError(
726 "Invalid root element node type %s - has to be one of "
727 "(DOCUMENT_NODE, ELEMENT_NODE)" % domtree
728 )
729 allowed_names = (
730 "assembly",
731 "assemblyBinding",
732 "configuration",
733 "dependentAssembly",
734 )
735 if rootElement.tagName not in allowed_names:
736 raise InvalidManifestError(
737 "Invalid root element <%s> - has to be one of <%s>"
738 % (rootElement.tagName, ">, <".join(allowed_names))
739 )
740 # print "I: loading manifest metadata from element <%s>" % \
741 # rootElement.tagName
742 if rootElement.tagName == "configuration":
743 for windows in rootElement.getCEByTN("windows"):
744 for assemblyBinding in windows.getCEByTN("assemblyBinding"):
745 self.load_dom(assemblyBinding, initialize)
746 else:
747 if initialize:
748 self.__init__()
749 self.manifestType = rootElement.tagName
750 self.manifestVersion = [
751 int(i)
752 for i in (rootElement.getA("manifestVersion") or "1.0").split(".")
753 ]
754 self.noInheritable = bool(rootElement.getFCEByTN("noInheritable"))
755 self.noInherit = bool(rootElement.getFCEByTN("noInherit"))
756 for assemblyIdentity in rootElement.getCEByTN("assemblyIdentity"):
757 self.type = assemblyIdentity.getA("type") or None
758 self.name = assemblyIdentity.getA("name") or None
759 self.language = assemblyIdentity.getA("language") or None
760 self.processorArchitecture = (
761 assemblyIdentity.getA("processorArchitecture") or None
762 )
763 version = assemblyIdentity.getA("version")
764 if version:
765 self.version = [int(i) for i in version.split(".")]
766 self.publicKeyToken = assemblyIdentity.getA("publicKeyToken") or None
767 for publisherPolicy in rootElement.getCEByTN("publisherPolicy"):
768 self.applyPublisherPolicy = (
769 publisherPolicy.getA("apply") or ""
770 ).lower() == "yes"
771 for description in rootElement.getCEByTN("description"):
772 if description.firstChild:
773 self.description = description.firstChild.wholeText
774 for trustInfo in rootElement.getCEByTN("trustInfo"):
775 for security in trustInfo.getCEByTN("security"):
776 for requestedPrivileges in security.getCEByTN(
777 "requestedPrivileges"
778 ):
779 for requestedExecutionLevel in requestedPrivileges.getCEByTN(
780 "requestedExecutionLevel"
781 ):
782 self.requestedExecutionLevel = requestedExecutionLevel.getA(
783 "level"
784 )
785 self.uiAccess = (
786 requestedExecutionLevel.getA("uiAccess") or ""
787 ).lower() == "true"
788 if rootElement.tagName == "assemblyBinding":
789 dependencies = [rootElement]
790 else:
791 dependencies = rootElement.getCEByTN("dependency")
792 for dependency in dependencies:
793 for dependentAssembly in dependency.getCEByTN("dependentAssembly"):
794 manifest = ManifestFromDOM(dependentAssembly)
795 if not manifest.name:
796 # invalid, skip
797 continue
798 manifest.optional = (
799 dependency.getA("optional") or ""
800 ).lower() == "yes"
801 self.dependentAssemblies.append(manifest)
802 if self.filename:
803 # Enable search for private assembly by assigning bogus
804 # filename (only the directory has to be correct)
805 self.dependentAssemblies[-1].filename = ":".join(
806 (self.filename, manifest.name)
807 )
808 for bindingRedirect in rootElement.getCEByTN("bindingRedirect"):
809 oldVersion = [
810 [int(i) for i in part.split(".")]
811 for part in bindingRedirect.getA("oldVersion").split("-")
812 ]
813 newVersion = [
814 int(i) for i in bindingRedirect.getA("newVersion").split(".")
815 ]
816 self.bindingRedirects.append((oldVersion, newVersion))
817 for file_ in rootElement.getCEByTN("file"):
818 self.add_file(
819 name=file_.getA("name"),
820 hashalg=file_.getA("hashalg"),
821 hash=file_.getA("hash"),
822 )
823
824 def parse(self, filename_or_file, initialize=True):
825 """Load manifest from file or file object"""
826 if isinstance(filename_or_file, str):
827 filename = filename_or_file
828 else:
829 filename = filename_or_file.name
830 try:
831 domtree = minidom.parse(filename_or_file)
832 except xml.parsers.expat.ExpatError as e:
833 args = [e.args[0]]
834 if isinstance(filename, str):
835 filename = filename.encode(sys.getdefaultencoding(), "replace")
836 args.insert(0, '\n File "%s"\n ' % filename)
837 raise ManifestXMLParseError(" ".join([str(arg) for arg in args]))
838 if initialize:
839 self.__init__()
840 self.filename = filename
841 self.load_dom(domtree, False)
842
843 def parse_string(self, xmlstr, initialize=True):
844 """Load manifest from XML string"""
845 try:
846 domtree = minidom.parseString(xmlstr)
847 except xml.parsers.expat.ExpatError as e:
848 raise ManifestXMLParseError(e)
849 self.load_dom(domtree, initialize)
850
851 def same_id(self, manifest, skip_version_check=False):
852 """Return a bool indicating if another manifest has the same identitiy.
853
854 This is done by comparing language, name, processorArchitecture,
855 publicKeyToken, type and version.
856
857 """
858 if skip_version_check:
859 version_check = True
860 else:
861 version_check = self.version == manifest.version
862 return (
863 self.language == manifest.language
864 and self.name == manifest.name
865 and self.processorArchitecture == manifest.processorArchitecture
866 and self.publicKeyToken == manifest.publicKeyToken
867 and self.type == manifest.type
868 and version_check
869 )
870
871 def todom(self):
872 """Return the manifest as DOM tree"""
873 doc = Document()
874 docE = doc.cE(self.manifestType)
875 if self.manifestType == "assemblyBinding":
876 cfg = doc.cE("configuration")
877 win = doc.cE("windows")
878 win.aChild(docE)
879 cfg.aChild(win)
880 doc.aChild(cfg)
881 else:
882 doc.aChild(docE)
883 if self.manifestType != "dependentAssembly":
884 docE.setA("xmlns", "urn:schemas-microsoft-com:asm.v1")
885 if self.manifestType != "assemblyBinding":
886 docE.setA(
887 "manifestVersion", ".".join([str(i) for i in self.manifestVersion])
888 )
889 if self.noInheritable:
890 docE.aChild(doc.cE("noInheritable"))
891 if self.noInherit:
892 docE.aChild(doc.cE("noInherit"))
893 aId = doc.cE("assemblyIdentity")
894 if self.type:
895 aId.setAttribute("type", self.type)
896 if self.name:
897 aId.setAttribute("name", self.name)
898 if self.language:
899 aId.setAttribute("language", self.language)
900 if self.processorArchitecture:
901 aId.setAttribute("processorArchitecture", self.processorArchitecture)
902 if self.version:
903 aId.setAttribute("version", ".".join([str(i) for i in self.version]))
904 if self.publicKeyToken:
905 aId.setAttribute("publicKeyToken", self.publicKeyToken)
906 if aId.hasAttributes():
907 docE.aChild(aId)
908 else:
909 aId.unlink()
910 if self.applyPublisherPolicy is not None:
911 ppE = doc.cE("publisherPolicy")
912 if self.applyPublisherPolicy:
913 ppE.setA("apply", "yes")
914 else:
915 ppE.setA("apply", "no")
916 docE.aChild(ppE)
917 if self.description:
918 descE = doc.cE("description")
919 descE.aChild(doc.cT(self.description))
920 docE.aChild(descE)
921 if self.requestedExecutionLevel in (
922 "asInvoker",
923 "highestAvailable",
924 "requireAdministrator",
925 ):
926 tE = doc.cE("trustInfo")
927 tE.setA("xmlns", "urn:schemas-microsoft-com:asm.v3")
928 sE = doc.cE("security")
929 rpE = doc.cE("requestedPrivileges")
930 relE = doc.cE("requestedExecutionLevel")
931 relE.setA("level", self.requestedExecutionLevel)
932 if self.uiAccess:
933 relE.setA("uiAccess", "true")
934 else:
935 relE.setA("uiAccess", "false")
936 rpE.aChild(relE)
937 sE.aChild(rpE)
938 tE.aChild(sE)
939 docE.aChild(tE)
940 if self.dependentAssemblies:
941 for assembly in self.dependentAssemblies:
942 if self.manifestType != "assemblyBinding":
943 dE = doc.cE("dependency")
944 if assembly.optional:
945 dE.setAttribute("optional", "yes")
946 daE = doc.cE("dependentAssembly")
947 adom = assembly.todom()
948 for child in adom.documentElement.childNodes:
949 daE.aChild(child.cloneNode(False))
950 adom.unlink()
951 if self.manifestType != "assemblyBinding":
952 dE.aChild(daE)
953 docE.aChild(dE)
954 else:
955 docE.aChild(daE)
956 if self.bindingRedirects:
957 for bindingRedirect in self.bindingRedirects:
958 brE = doc.cE("bindingRedirect")
959 brE.setAttribute(
960 "oldVersion",
961 "-".join(
962 [
963 ".".join([str(i) for i in part])
964 for part in bindingRedirect[0]
965 ]
966 ),
967 )
968 brE.setAttribute(
969 "newVersion", ".".join([str(i) for i in bindingRedirect[1]])
970 )
971 docE.aChild(brE)
972 if self.files:
973 for file_ in self.files:
974 fE = doc.cE("file")
975 for attr in ("name", "hashalg", "hash"):
976 val = getattr(file_, attr)
977 if val:
978 fE.setA(attr, val)
979 docE.aChild(fE)
980 return doc
981
982 def toprettyxml(self, indent=" ", newl=os.linesep, encoding="UTF-8"):
983 """Return the manifest as pretty-printed XML"""
984 domtree = self.todom()
985 # WARNING: The XML declaration has to follow the order
986 # version-encoding-standalone (standalone being optional), otherwise
987 # if it is embedded in an exe the exe will fail to launch!
988 # ('application configuration incorrect')
989 if sys.version_info >= (2, 3):
990 xmlstr = domtree.toprettyxml(indent, newl, encoding)
991 else:
992 xmlstr = domtree.toprettyxml(indent, newl)
993 xmlstr = xmlstr.strip(os.linesep.encode('utf-8')).replace(
994 ('<?xml version="1.0" encoding="%s"?>' % encoding).encode('utf-8'),
995 ('<?xml version="1.0" encoding="%s" standalone="yes"?>' % encoding).encode('utf-8'),
996 )
997 domtree.unlink()
998 return xmlstr
999
1000 def toxml(self, encoding="UTF-8"):
1001 """Return the manifest as XML"""
1002 domtree = self.todom()
1003 # WARNING: The XML declaration has to follow the order
1004 # version-encoding-standalone (standalone being optional), otherwise
1005 # if it is embedded in an exe the exe will fail to launch!
1006 # ('application configuration incorrect')
1007 xmlstr = domtree.toxml(encoding).replace(
1008 '<?xml version="1.0" encoding="%s"?>' % encoding,
1009 '<?xml version="1.0" encoding="%s" standalone="yes"?>' % encoding,
1010 )
1011 domtree.unlink()
1012 return xmlstr
1013
1014 def update_resources(self, dstpath, names=None, languages=None):
1015 """Update or add manifest resource in dll/exe file dstpath"""
1016 UpdateManifestResourcesFromXML(dstpath, self.toprettyxml(), names, languages)
1017
1018 def writeprettyxml(
1019 self, filename_or_file=None, indent=" ", newl=os.linesep, encoding="UTF-8"
1020 ):
1021 """Write the manifest as XML to a file or file object"""
1022 if not filename_or_file:
1023 filename_or_file = self.filename
1024 if isinstance(filename_or_file, str):
1025 filename_or_file = open(filename_or_file, "wb")
1026 xmlstr = self.toprettyxml(indent, newl, encoding)
1027 filename_or_file.write(xmlstr)
1028 filename_or_file.close()
1029
1030 def writexml(
1031 self, filename_or_file=None, indent=" ", newl=os.linesep, encoding="UTF-8"
1032 ):
1033 """Write the manifest as XML to a file or file object"""
1034 if not filename_or_file:
1035 filename_or_file = self.filename
1036 if isinstance(filename_or_file, str):
1037 filename_or_file = open(filename_or_file, "wb")
1038 xmlstr = self.toxml(indent, newl, encoding)
1039 filename_or_file.write(xmlstr)
1040 filename_or_file.close()
1041
1042
1043 def ManifestFromResFile(filename, names=None, languages=None):
1044 """Create and return manifest instance from resource in dll/exe file"""
1045 res = GetManifestResources(filename, names, languages)
1046 pth = []
1047 if res and res[RT_MANIFEST]:
1048 while isinstance(res, dict) and res.keys():
1049 key = res.keys()[0]
1050 pth.append(str(key))
1051 res = res[key]
1052 if isinstance(res, dict):
1053 raise InvalidManifestError(
1054 "No matching manifest resource found in '%s'" % filename
1055 )
1056 manifest = Manifest()
1057 manifest.filename = ":".join([filename] + pth)
1058 manifest.parse_string(res, False)
1059 return manifest
1060
1061
1062 def ManifestFromDOM(domtree):
1063 """Create and return manifest instance from DOM tree"""
1064 manifest = Manifest()
1065 manifest.load_dom(domtree)
1066 return manifest
1067
1068
1069 def ManifestFromXML(xmlstr):
1070 """Create and return manifest instance from XML"""
1071 manifest = Manifest()
1072 manifest.parse_string(xmlstr)
1073 return manifest
1074
1075
1076 def ManifestFromXMLFile(filename_or_file):
1077 """Create and return manifest instance from file"""
1078 manifest = Manifest()
1079 manifest.parse(filename_or_file)
1080 return manifest
1081
1082
1083 def GetManifestResources(filename, names=None, languages=None):
1084 """Get manifest resources from file"""
1085 return winresource.GetResources(filename, [RT_MANIFEST], names, languages)
1086
1087
1088 def UpdateManifestResourcesFromXML(dstpath, xmlstr, names=None, languages=None):
1089 """Update or add manifest XML as resource in dstpath"""
1090 if not silent:
1091 print("I: Updating manifest in", dstpath)
1092 if dstpath.lower().endswith(".exe"):
1093 name = 1
1094 else:
1095 name = 2
1096 winresource.UpdateResources(
1097 dstpath, xmlstr, RT_MANIFEST, names or [name], languages or [0, "*"]
1098 )
1099
1100
1101 def UpdateManifestResourcesFromXMLFile(dstpath, srcpath, names=None, languages=None):
1102 """Update or add manifest XML from srcpath as resource in dstpath"""
1103 if not silent:
1104 print("I: Updating manifest from", srcpath, "in", dstpath)
1105 if dstpath.lower().endswith(".exe"):
1106 name = 1
1107 else:
1108 name = 2
1109 winresource.UpdateResourcesFromDataFile(
1110 dstpath, srcpath, RT_MANIFEST, names or [name], languages or [0, "*"]
1111 )
1112
1113
1114 if __name__ == "__main__":
1115 dstpath = sys.argv[1]
1116 srcpath = sys.argv[2]
1117 UpdateManifestResourcesFromXMLFile(dstpath, srcpath)