versioninfo.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. # -*- coding: utf-8 -*-
  2. #-----------------------------------------------------------------------------
  3. # Copyright (c) 2013-2021, PyInstaller Development Team.
  4. #
  5. # Distributed under the terms of the GNU General Public License (version 2
  6. # or later) with exception for distributing the bootloader.
  7. #
  8. # The full license is in the file COPYING.txt, distributed with this software.
  9. #
  10. # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
  11. #-----------------------------------------------------------------------------
  12. import struct
  13. # ::TODO:: #1920 revert to using pypi version
  14. import pefile
  15. from PyInstaller.compat import win32api
  16. def pefile_check_control_flow_guard(filename):
  17. """
  18. Checks if the specified PE file has CFG (Control Flow Guard) enabled.
  19. Parameters
  20. ----------
  21. filename : str
  22. Path to the PE file to inspect.
  23. Returns
  24. ----------
  25. bool
  26. True if file is a PE file with CFG enabled. False if CFG is not enabled or if file could not be processed using
  27. the pefile library.
  28. """
  29. try:
  30. pe = pefile.PE(filename, fast_load=True)
  31. # https://docs.microsoft.com/en-us/windows/win32/debug/pe-format
  32. # IMAGE_DLLCHARACTERISTICS_GUARD_CF = 0x4000
  33. return bool(pe.OPTIONAL_HEADER.DllCharacteristics & 0x4000)
  34. except Exception:
  35. return False
  36. # Ensures no code from the executable is executed.
  37. LOAD_LIBRARY_AS_DATAFILE = 2
  38. def getRaw(text):
  39. """
  40. Encodes text as UTF-16LE (Microsoft 'Unicode') for use in structs.
  41. """
  42. return text.encode('UTF-16LE')
  43. def decode(pathnm):
  44. h = win32api.LoadLibraryEx(pathnm, 0, LOAD_LIBRARY_AS_DATAFILE)
  45. res = win32api.EnumResourceNames(h, pefile.RESOURCE_TYPE['RT_VERSION'])
  46. if not len(res):
  47. return None
  48. data = win32api.LoadResource(h, pefile.RESOURCE_TYPE['RT_VERSION'], res[0])
  49. vs = VSVersionInfo()
  50. vs.fromRaw(data)
  51. win32api.FreeLibrary(h)
  52. return vs
  53. def nextDWord(offset):
  54. """
  55. Align `offset` to the next 4-byte boundary.
  56. """
  57. return ((offset + 3) >> 2) << 2
  58. class VSVersionInfo:
  59. """
  60. WORD wLength; // length of the VS_VERSION_INFO structure
  61. WORD wValueLength; // length of the Value member
  62. WORD wType; // 1 means text, 0 means binary
  63. WCHAR szKey[]; // Contains the Unicode string "VS_VERSION_INFO".
  64. WORD Padding1[];
  65. VS_FIXEDFILEINFO Value;
  66. WORD Padding2[];
  67. WORD Children[]; // zero or more StringFileInfo or VarFileInfo
  68. // structures (or both) that are children of the
  69. // current version structure.
  70. """
  71. def __init__(self, ffi=None, kids=None):
  72. self.ffi = ffi
  73. self.kids = kids or []
  74. def fromRaw(self, data):
  75. i, (sublen, vallen, wType, nm) = parseCommon(data)
  76. #vallen is length of the ffi, typ is 0, nm is 'VS_VERSION_INFO'.
  77. i = nextDWord(i)
  78. # Now a VS_FIXEDFILEINFO
  79. self.ffi = FixedFileInfo()
  80. j = self.ffi.fromRaw(data, i)
  81. i = j
  82. while i < sublen:
  83. j = i
  84. i, (csublen, cvallen, ctyp, nm) = parseCommon(data, i)
  85. if nm.strip() == 'StringFileInfo':
  86. sfi = StringFileInfo()
  87. k = sfi.fromRaw(csublen, cvallen, nm, data, i, j + csublen)
  88. self.kids.append(sfi)
  89. i = k
  90. else:
  91. vfi = VarFileInfo()
  92. k = vfi.fromRaw(csublen, cvallen, nm, data, i, j + csublen)
  93. self.kids.append(vfi)
  94. i = k
  95. i = j + csublen
  96. i = nextDWord(i)
  97. return i
  98. def toRaw(self):
  99. raw_name = getRaw('VS_VERSION_INFO')
  100. rawffi = self.ffi.toRaw()
  101. vallen = len(rawffi)
  102. typ = 0
  103. sublen = 6 + len(raw_name) + 2
  104. pad = b''
  105. if sublen % 4:
  106. pad = b'\000\000'
  107. sublen = sublen + len(pad) + vallen
  108. pad2 = b''
  109. if sublen % 4:
  110. pad2 = b'\000\000'
  111. tmp = b''.join([kid.toRaw() for kid in self.kids])
  112. sublen = sublen + len(pad2) + len(tmp)
  113. return struct.pack('hhh', sublen, vallen, typ) + raw_name + b'\000\000' + pad + rawffi + pad2 + tmp
  114. def __eq__(self, other):
  115. return self.toRaw() == other
  116. def __str__(self, indent=''):
  117. indent = indent + ' '
  118. tmp = [kid.__str__(indent + ' ') for kid in self.kids]
  119. tmp = ', \n'.join(tmp)
  120. return '\n'.join([
  121. "# UTF-8",
  122. "#",
  123. "# For more details about fixed file info 'ffi' see:",
  124. "# http://msdn.microsoft.com/en-us/library/ms646997.aspx",
  125. "VSVersionInfo(",
  126. indent + f"ffi={self.ffi.__str__(indent)},",
  127. indent + "kids=[",
  128. tmp,
  129. indent + "]",
  130. ")",
  131. ])
  132. def __repr__(self):
  133. return "versioninfo.VSVersionInfo(ffi=%r, kids=%r)" % (self.ffi, self.kids)
  134. def parseCommon(data, start=0):
  135. i = start + 6
  136. (wLength, wValueLength, wType) = struct.unpack('3h', data[start:i])
  137. i, text = parseUString(data, i, i + wLength)
  138. return i, (wLength, wValueLength, wType, text)
  139. def parseUString(data, start, limit):
  140. i = start
  141. while i < limit:
  142. if data[i:i + 2] == b'\000\000':
  143. break
  144. i += 2
  145. text = data[start:i].decode('UTF-16LE')
  146. i += 2
  147. return i, text
  148. class FixedFileInfo:
  149. """
  150. DWORD dwSignature; //Contains the value 0xFEEFO4BD
  151. DWORD dwStrucVersion; // binary version number of this structure.
  152. // The high-order word of this member contains
  153. // the major version number, and the low-order
  154. // word contains the minor version number.
  155. DWORD dwFileVersionMS; // most significant 32 bits of the file's binary
  156. // version number
  157. DWORD dwFileVersionLS; //
  158. DWORD dwProductVersionMS; // most significant 32 bits of the binary version
  159. // number of the product with which this file was
  160. // distributed
  161. DWORD dwProductVersionLS; //
  162. DWORD dwFileFlagsMask; // bitmask that specifies the valid bits in
  163. // dwFileFlags. A bit is valid only if it was
  164. // defined when the file was created.
  165. DWORD dwFileFlags; // VS_FF_DEBUG, VS_FF_PATCHED etc.
  166. DWORD dwFileOS; // VOS_NT, VOS_WINDOWS32 etc.
  167. DWORD dwFileType; // VFT_APP etc.
  168. DWORD dwFileSubtype; // 0 unless VFT_DRV or VFT_FONT or VFT_VXD
  169. DWORD dwFileDateMS;
  170. DWORD dwFileDateLS;
  171. """
  172. def __init__(
  173. self,
  174. filevers=(0, 0, 0, 0),
  175. prodvers=(0, 0, 0, 0),
  176. mask=0x3f,
  177. flags=0x0,
  178. OS=0x40004,
  179. fileType=0x1,
  180. subtype=0x0,
  181. date=(0, 0)
  182. ):
  183. self.sig = 0xfeef04bd
  184. self.strucVersion = 0x10000
  185. self.fileVersionMS = (filevers[0] << 16) | (filevers[1] & 0xffff)
  186. self.fileVersionLS = (filevers[2] << 16) | (filevers[3] & 0xffff)
  187. self.productVersionMS = (prodvers[0] << 16) | (prodvers[1] & 0xffff)
  188. self.productVersionLS = (prodvers[2] << 16) | (prodvers[3] & 0xffff)
  189. self.fileFlagsMask = mask
  190. self.fileFlags = flags
  191. self.fileOS = OS
  192. self.fileType = fileType
  193. self.fileSubtype = subtype
  194. self.fileDateMS = date[0]
  195. self.fileDateLS = date[1]
  196. def fromRaw(self, data, i):
  197. (
  198. self.sig,
  199. self.strucVersion,
  200. self.fileVersionMS,
  201. self.fileVersionLS,
  202. self.productVersionMS,
  203. self.productVersionLS,
  204. self.fileFlagsMask,
  205. self.fileFlags,
  206. self.fileOS,
  207. self.fileType,
  208. self.fileSubtype,
  209. self.fileDateMS,
  210. self.fileDateLS,
  211. ) = struct.unpack('13L', data[i:i + 52])
  212. return i + 52
  213. def toRaw(self):
  214. return struct.pack(
  215. '13L',
  216. self.sig,
  217. self.strucVersion,
  218. self.fileVersionMS,
  219. self.fileVersionLS,
  220. self.productVersionMS,
  221. self.productVersionLS,
  222. self.fileFlagsMask,
  223. self.fileFlags,
  224. self.fileOS,
  225. self.fileType,
  226. self.fileSubtype,
  227. self.fileDateMS,
  228. self.fileDateLS,
  229. )
  230. def __eq__(self, other):
  231. return self.toRaw() == other
  232. def __str__(self, indent=''):
  233. fv = (
  234. self.fileVersionMS >> 16, self.fileVersionMS & 0xffff,
  235. self.fileVersionLS >> 16, self.fileVersionLS & 0xffff,
  236. ) # yapf: disable
  237. pv = (
  238. self.productVersionMS >> 16, self.productVersionMS & 0xffff,
  239. self.productVersionLS >> 16, self.productVersionLS & 0xffff,
  240. ) # yapf: disable
  241. fd = (self.fileDateMS, self.fileDateLS)
  242. tmp = [
  243. 'FixedFileInfo(',
  244. '# filevers and prodvers should be always a tuple with four items: (1, 2, 3, 4)',
  245. '# Set not needed items to zero 0.',
  246. 'filevers=%s,' % (fv,),
  247. 'prodvers=%s,' % (pv,),
  248. "# Contains a bitmask that specifies the valid bits 'flags'r",
  249. 'mask=%s,' % hex(self.fileFlagsMask),
  250. '# Contains a bitmask that specifies the Boolean attributes of the file.',
  251. 'flags=%s,' % hex(self.fileFlags),
  252. '# The operating system for which this file was designed.',
  253. '# 0x4 - NT and there is no need to change it.',
  254. 'OS=%s,' % hex(self.fileOS),
  255. '# The general type of file.',
  256. '# 0x1 - the file is an application.',
  257. 'fileType=%s,' % hex(self.fileType),
  258. '# The function of the file.',
  259. '# 0x0 - the function is not defined for this fileType',
  260. 'subtype=%s,' % hex(self.fileSubtype),
  261. '# Creation date and time stamp.',
  262. 'date=%s' % (fd,),
  263. ')',
  264. ]
  265. return f'\n{indent} '.join(tmp)
  266. def __repr__(self):
  267. fv = (
  268. self.fileVersionMS >> 16, self.fileVersionMS & 0xffff,
  269. self.fileVersionLS >> 16, self.fileVersionLS & 0xffff,
  270. ) # yapf: disable
  271. pv = (
  272. self.productVersionMS >> 16, self.productVersionMS & 0xffff,
  273. self.productVersionLS >> 16, self.productVersionLS & 0xffff,
  274. ) # yapf: disable
  275. fd = (self.fileDateMS, self.fileDateLS)
  276. return (
  277. 'versioninfo.FixedFileInfo(filevers=%r, prodvers=%r, '
  278. 'mask=0x%x, flags=0x%x, OS=0x%x, '
  279. 'fileType=%r, subtype=0x%x, date=%r)' %
  280. (fv, pv, self.fileFlagsMask, self.fileFlags, self.fileOS, self.fileType, self.fileSubtype, fd)
  281. )
  282. class StringFileInfo(object):
  283. """
  284. WORD wLength; // length of the version resource
  285. WORD wValueLength; // length of the Value member in the current
  286. // VS_VERSION_INFO structure
  287. WORD wType; // 1 means text, 0 means binary
  288. WCHAR szKey[]; // Contains the Unicode string 'StringFileInfo'.
  289. WORD Padding[];
  290. StringTable Children[]; // list of zero or more String structures
  291. """
  292. def __init__(self, kids=None):
  293. self.name = 'StringFileInfo'
  294. self.kids = kids or []
  295. def fromRaw(self, sublen, vallen, name, data, i, limit):
  296. self.name = name
  297. while i < limit:
  298. st = StringTable()
  299. j = st.fromRaw(data, i, limit)
  300. self.kids.append(st)
  301. i = j
  302. return i
  303. def toRaw(self):
  304. raw_name = getRaw(self.name)
  305. vallen = 0
  306. typ = 1
  307. sublen = 6 + len(raw_name) + 2
  308. pad = b''
  309. if sublen % 4:
  310. pad = b'\000\000'
  311. tmp = b''.join([kid.toRaw() for kid in self.kids])
  312. sublen = sublen + len(pad) + len(tmp)
  313. return struct.pack('hhh', sublen, vallen, typ) + raw_name + b'\000\000' + pad + tmp
  314. def __eq__(self, other):
  315. return self.toRaw() == other
  316. def __str__(self, indent=''):
  317. new_indent = indent + ' '
  318. tmp = ', \n'.join(kid.__str__(new_indent) for kid in self.kids)
  319. return f'{indent}StringFileInfo(\n{new_indent}[\n{tmp}\n{new_indent}])'
  320. def __repr__(self):
  321. return 'versioninfo.StringFileInfo(%r)' % self.kids
  322. class StringTable:
  323. """
  324. WORD wLength;
  325. WORD wValueLength;
  326. WORD wType;
  327. WCHAR szKey[];
  328. String Children[]; // list of zero or more String structures.
  329. """
  330. def __init__(self, name=None, kids=None):
  331. self.name = name or ''
  332. self.kids = kids or []
  333. def fromRaw(self, data, i, limit):
  334. i, (cpsublen, cpwValueLength, cpwType, self.name) = parseCodePage(data, i, limit) # should be code page junk
  335. i = nextDWord(i)
  336. while i < limit:
  337. ss = StringStruct()
  338. j = ss.fromRaw(data, i, limit)
  339. i = j
  340. self.kids.append(ss)
  341. i = nextDWord(i)
  342. return i
  343. def toRaw(self):
  344. raw_name = getRaw(self.name)
  345. vallen = 0
  346. typ = 1
  347. sublen = 6 + len(raw_name) + 2
  348. tmp = []
  349. for kid in self.kids:
  350. raw = kid.toRaw()
  351. if len(raw) % 4:
  352. raw = raw + b'\000\000'
  353. tmp.append(raw)
  354. tmp = b''.join(tmp)
  355. sublen += len(tmp)
  356. return struct.pack('hhh', sublen, vallen, typ) + raw_name + b'\000\000' + tmp
  357. def __eq__(self, other):
  358. return self.toRaw() == other
  359. def __str__(self, indent=''):
  360. new_indent = indent + ' '
  361. tmp = (',\n' + new_indent).join(str(kid) for kid in self.kids)
  362. return f"{indent}StringTable(\n{new_indent}'{self.name}',\n{new_indent}[{tmp}])"
  363. def __repr__(self):
  364. return 'versioninfo.StringTable(%r, %r)' % (self.name, self.kids)
  365. class StringStruct:
  366. """
  367. WORD wLength;
  368. WORD wValueLength;
  369. WORD wType;
  370. WCHAR szKey[];
  371. WORD Padding[];
  372. String Value[];
  373. """
  374. def __init__(self, name=None, val=None):
  375. self.name = name or ''
  376. self.val = val or ''
  377. def fromRaw(self, data, i, limit):
  378. i, (sublen, vallen, typ, self.name) = parseCommon(data, i)
  379. limit = i + sublen
  380. i = nextDWord(i)
  381. i, self.val = parseUString(data, i, limit)
  382. return i
  383. def toRaw(self):
  384. raw_name = getRaw(self.name)
  385. raw_val = getRaw(self.val)
  386. # TODO: document the size of vallen and sublen.
  387. vallen = len(self.val) + 1 # Number of (wide-)characters, not bytes!
  388. typ = 1
  389. sublen = 6 + len(raw_name) + 2
  390. pad = b''
  391. if sublen % 4:
  392. pad = b'\000\000'
  393. sublen = sublen + len(pad) + (vallen * 2)
  394. return struct.pack('hhh', sublen, vallen, typ) + raw_name + b'\000\000' + pad + raw_val + b'\000\000'
  395. def __eq__(self, other):
  396. return self.toRaw() == other
  397. def __str__(self, indent=''):
  398. return "StringStruct('%s', '%s')" % (self.name, self.val)
  399. def __repr__(self):
  400. return 'versioninfo.StringStruct(%r, %r)' % (self.name, self.val)
  401. def parseCodePage(data, i, limit):
  402. i, (sublen, wValueLength, wType, nm) = parseCommon(data, i)
  403. return i, (sublen, wValueLength, wType, nm)
  404. class VarFileInfo:
  405. """
  406. WORD wLength; // length of the version resource
  407. WORD wValueLength; // length of the Value member in the current
  408. // VS_VERSION_INFO structure
  409. WORD wType; // 1 means text, 0 means binary
  410. WCHAR szKey[]; // Contains the Unicode string 'VarFileInfo'.
  411. WORD Padding[];
  412. Var Children[]; // list of zero or more Var structures
  413. """
  414. def __init__(self, kids=None):
  415. self.kids = kids or []
  416. def fromRaw(self, sublen, vallen, name, data, i, limit):
  417. self.sublen = sublen
  418. self.vallen = vallen
  419. self.name = name
  420. i = nextDWord(i)
  421. while i < limit:
  422. vs = VarStruct()
  423. j = vs.fromRaw(data, i, limit)
  424. self.kids.append(vs)
  425. i = j
  426. return i
  427. def toRaw(self):
  428. self.vallen = 0
  429. self.wType = 1
  430. self.name = 'VarFileInfo'
  431. raw_name = getRaw(self.name)
  432. sublen = 6 + len(raw_name) + 2
  433. pad = b''
  434. if sublen % 4:
  435. pad = b'\000\000'
  436. tmp = b''.join([kid.toRaw() for kid in self.kids])
  437. self.sublen = sublen + len(pad) + len(tmp)
  438. return struct.pack('hhh', self.sublen, self.vallen, self.wType) + raw_name + b'\000\000' + pad + tmp
  439. def __eq__(self, other):
  440. return self.toRaw() == other
  441. def __str__(self, indent=''):
  442. return indent + "VarFileInfo([%s])" % ', '.join(str(kid) for kid in self.kids)
  443. def __repr__(self):
  444. return 'versioninfo.VarFileInfo(%r)' % self.kids
  445. class VarStruct:
  446. """
  447. WORD wLength; // length of the version resource
  448. WORD wValueLength; // length of the Value member in the current
  449. // VS_VERSION_INFO structure
  450. WORD wType; // 1 means text, 0 means binary
  451. WCHAR szKey[]; // Contains the Unicode string 'Translation'
  452. // or a user-defined key string value
  453. WORD Padding[]; //
  454. WORD Value[]; // list of one or more values that are language
  455. // and code-page identifiers
  456. """
  457. def __init__(self, name=None, kids=None):
  458. self.name = name or ''
  459. self.kids = kids or []
  460. def fromRaw(self, data, i, limit):
  461. i, (self.sublen, self.wValueLength, self.wType, self.name) = parseCommon(data, i)
  462. i = nextDWord(i)
  463. for j in range(0, self.wValueLength, 2):
  464. kid = struct.unpack('h', data[i:i + 2])[0]
  465. self.kids.append(kid)
  466. i += 2
  467. return i
  468. def toRaw(self):
  469. self.wValueLength = len(self.kids) * 2
  470. self.wType = 0
  471. raw_name = getRaw(self.name)
  472. sublen = 6 + len(raw_name) + 2
  473. pad = b''
  474. if sublen % 4:
  475. pad = b'\000\000'
  476. self.sublen = sublen + len(pad) + self.wValueLength
  477. tmp = b''.join([struct.pack('h', kid) for kid in self.kids])
  478. return struct.pack('hhh', self.sublen, self.wValueLength, self.wType) + raw_name + b'\000\000' + pad + tmp
  479. def __eq__(self, other):
  480. return self.toRaw() == other
  481. def __str__(self, indent=''):
  482. return "VarStruct('%s', %r)" % (self.name, self.kids)
  483. def __repr__(self):
  484. return 'versioninfo.VarStruct(%r, %r)' % (self.name, self.kids)
  485. def SetVersion(exenm, versionfile):
  486. if isinstance(versionfile, VSVersionInfo):
  487. vs = versionfile
  488. else:
  489. # Read and parse the version file. It may have a byte order marker or encoding cookie - respect it if it does.
  490. from PyInstaller.utils.misc import decode
  491. with open(versionfile, 'rb') as fp:
  492. txt = decode(fp.read())
  493. vs = eval(txt)
  494. # Remember overlay
  495. pe = pefile.PE(exenm, fast_load=True)
  496. overlay_before = pe.get_overlay()
  497. pe.close()
  498. hdst = win32api.BeginUpdateResource(exenm, 0)
  499. win32api.UpdateResource(hdst, pefile.RESOURCE_TYPE['RT_VERSION'], 1, vs.toRaw())
  500. win32api.EndUpdateResource(hdst, 0)
  501. if overlay_before:
  502. # Check if the overlay is still present
  503. pe = pefile.PE(exenm, fast_load=True)
  504. overlay_after = pe.get_overlay()
  505. pe.close()
  506. # If the update removed the overlay data, re-append it
  507. if not overlay_after:
  508. with open(exenm, 'ab') as exef:
  509. exef.write(overlay_before)